code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.keybindings;
import java.awt.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import net.java.sip.communicator.service.keybindings.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.fileaccess.*;
import org.osgi.framework.*;
//disambiguation
/**
* Service that concerns keybinding mappings used by various parts of the UI.
* Persistence is handled as follows when started:
* <ol>
* <li>Load default bindings from relative directory</li>
* <li>Attempt to load custom bindings and resolve any duplicates</li>
* <li>If merged bindings differ from the custom bindings then this attempts to
* save the merged version</li>
* </ol>
* Custom bindings attempt to be written again whenever they're changed if the
* service is running. Each category of keybindings are stored in its own file.
*
* @author Damian Johnson
*/
class KeybindingsServiceImpl
implements KeybindingsService, Observer
{
/**
* The <tt>Logger</tt> instance used by the
* <tt>KeybindingsServiceImpl</tt> class and its instances for logging
* output.
*/
private static final Logger logger =
Logger.getLogger(KeybindingsServiceImpl.class);
/**
* Name of the relative directory that holds default bindings.
*/
private static final String DEFAULT_KEYBINDING_DIR =
"/resources/config/defaultkeybindings";
/**
* Name of the directory that holds custom bindings.
*/
private static final String CUSTOM_KEYBINDING_DIR = "keybindings";
/**
* Path where to store the global shortcuts.
*/
private final static String CONFIGURATION_PATH =
"net.java.sip.communicator.impl.keybinding.global";
/**
* Path where to store the global shortcuts defaults values.
*/
private final static String DEFAULTS_VALUES_PATH =
"impl.keybinding.global";
/**
* Flag indicating if service is running.
*/
private boolean isRunning = false;
/**
* Loaded keybinding mappings, maps to null if defaults failed to be loaded.
*/
private final HashMap<KeybindingSet.Category, KeybindingSetImpl> bindings =
new HashMap<KeybindingSet.Category, KeybindingSetImpl>();
/**
* Loaded global keybinding mappings.
*/
private GlobalKeybindingSet globalBindings = null;
/**
* Starts the KeybindingService, for each keybinding category retrieving the
* default bindings then overwriting them with any custom bindings that can
* be retrieved. This writes the merged copy back if it differs from the
* custom bindings. This is a no-op if the service has already been started.
*
* @param bc the currently valid OSGI bundle context.
*/
synchronized void start(BundleContext bc)
{
if (this.isRunning)
return;
for (KeybindingSet.Category category : KeybindingSet.Category.values())
{
// Retrieves default bindings
Persistence format = category.getFormat();
LinkedHashMap<KeyStroke, String> defaultBindings;
try
{
String defaultPath =
DEFAULT_KEYBINDING_DIR + "/" + category.getResource();
InputStream in = getClass().getResourceAsStream(defaultPath);
defaultBindings = format.load(in);
}
catch (IOException exc)
{
logger.error("default bindings set missing: "
+ category.getResource(), exc);
this.bindings.put(category, null);
continue;
}
catch (ParseException exc)
{
logger.error("unable to parse default bindings set: "
+ category.getResource(), exc);
this.bindings.put(category, null);
continue;
}
// Attempts to retrieve custom bindings
String customPath =
CUSTOM_KEYBINDING_DIR + "/" + category.getResource();
File customFile;
try
{
ServiceReference faServiceReference =
bc.getServiceReference(FileAccessService.class.getName());
FileAccessService faService =
(FileAccessService) bc.getService(faServiceReference);
// Makes directory for custom bindings if it doesn't exist
File customDir =
faService
.getPrivatePersistentDirectory(CUSTOM_KEYBINDING_DIR);
if (!customDir.exists())
customDir.mkdir();
// Gets file access service to reference persistent storage
// of the user
customFile = faService.getPrivatePersistentFile(customPath);
}
catch (Exception exc)
{
String msg =
"unable to secure file for custom bindings (" + customPath
+ "), using defaults but won't be able to save changes";
logger.error(msg, exc);
KeybindingSetImpl newSet =
new KeybindingSetImpl(defaultBindings, category, null);
this.bindings.put(category, newSet);
newSet.addObserver(this);
continue;
}
LinkedHashMap<KeyStroke, String> customBindings = null;
if (customFile.exists())
{
try
{
FileInputStream in = new FileInputStream(customFile);
customBindings = format.load(in);
in.close();
}
catch (Exception exc)
{
// If either an IO or ParseException occur then we skip
// loading custom bindings
}
}
// Merges custom bindings
LinkedHashMap<KeyStroke, String> merged =
new LinkedHashMap<KeyStroke, String>();
if (customBindings != null)
{
Map<KeyStroke, String> customTmp =
new LinkedHashMap<KeyStroke, String>(customBindings);
for (Map.Entry<KeyStroke, String> shortcut2action :
defaultBindings.entrySet())
{
String action = shortcut2action.getValue();
if (customTmp.containsValue(action))
{
KeyStroke custom = null;
for(Map.Entry<KeyStroke, String> customShortcut2action :
customTmp.entrySet())
{
if (customShortcut2action.getValue().equals(action))
{
custom = customShortcut2action.getKey();
break;
}
}
assert custom != null;
customTmp.remove(custom);
merged.put(custom, action);
}
else
{
merged.put(shortcut2action.getKey(), action);
}
}
}
else
{
merged = defaultBindings;
}
// Writes merged result
if (!merged.equals(customBindings))
{
try
{
FileOutputStream out = new FileOutputStream(customFile);
format.save(out, merged);
out.close();
}
catch (IOException exc)
{
logger.error("unable to write to: "
+ customFile.getAbsolutePath(), exc);
}
}
KeybindingSetImpl newSet =
new KeybindingSetImpl(merged, category, customFile);
this.bindings.put(category, newSet);
newSet.addObserver(this);
}
// global shortcut initialization
globalBindings = new GlobalKeybindingSetImpl();
globalBindings.setBindings(getGlobalShortcutFromConfiguration());
this.isRunning = true;
}
/**
* Invalidates references to custom bindings, preventing further writes.
*/
synchronized void stop()
{
if (!this.isRunning)
return;
for (KeybindingSetImpl bindingSet : this.bindings.values())
{
bindingSet.invalidate();
}
this.bindings.clear();
this.saveGlobalShortcutFromConfiguration();
this.isRunning = false;
}
/**
* Provides the bindings associated with a given category. This may be null
* if the default bindings failed to be loaded.
*
* @param category segment of the UI for which bindings should be retrieved
* @return mappings of keystrokes to the string representation of their
* actions
* @throws UnsupportedOperationException if the service isn't running
*/
public synchronized KeybindingSet getBindings(
KeybindingSet.Category category)
{
if (!this.isRunning)
throw new UnsupportedOperationException();
// Started services should have all categories
assert this.bindings.containsKey(category);
return this.bindings.get(category);
}
/**
* Listens for changes in binding sets so changes can be written.
*/
public void update(Observable obs, Object arg)
{
if (obs instanceof KeybindingSetImpl)
{
KeybindingSetImpl changedBindings = (KeybindingSetImpl) obs;
// Attempts to avoid lock if unwritable (this works since bindings
// can't become re-writable)
if (changedBindings.isWritable())
{
synchronized (this)
{
if (changedBindings.isWritable())
{
// Writes new bindings to custom file
File customFile = changedBindings.getCustomFile();
try
{
FileOutputStream out =
new FileOutputStream(customFile);
Persistence format =
changedBindings.getCategory().getFormat();
format.save(out, changedBindings.getBindings());
out.close();
}
catch (IOException exc)
{
logger.error("unable to write to: "
+ customFile.getAbsolutePath(), exc);
}
}
}
}
}
}
/**
* Returns list of global shortcuts from the configuration file.
*
* @return list of global shortcuts.
*/
public Map<String, List<AWTKeyStroke>> getGlobalShortcutFromConfiguration()
{
Map<String, List<AWTKeyStroke>> gBindings = new
LinkedHashMap<String, List<AWTKeyStroke>>();
ConfigurationService configService =
KeybindingsActivator.getConfigService();
String shortcut = null;
String shortcut2 = null;
String propName = null;
String propName2 = null;
String names[] = new String[]{"answer", "hangup", "answer_hangup",
"contactlist", "mute", "push_to_talk"};
Object configured = configService.getProperty(
"net.java.sip.communicator.impl.keybinding.global.configured");
if(configured == null)
{
// default keystrokes
for(String name : names)
{
List<AWTKeyStroke> kss = new ArrayList<AWTKeyStroke>();
propName = DEFAULTS_VALUES_PATH + "." + name + ".1";
shortcut = propName != null ?
KeybindingsActivator.getResourceService().getSettingsString(
propName) : null;
if(shortcut != null)
{
kss.add(AWTKeyStroke.getAWTKeyStroke(shortcut));
}
gBindings.put(name, kss);
}
configService.setProperty(
"net.java.sip.communicator.impl.keybinding.global.configured",
"true");
return gBindings;
}
for(String name : names)
{
List<AWTKeyStroke> kss = new ArrayList<AWTKeyStroke>();
propName = CONFIGURATION_PATH + "." + name + ".1";
propName2 = CONFIGURATION_PATH + "." + name + ".2";
shortcut = propName != null ?
(String)configService.getProperty(propName) : null;
shortcut2 = propName2 != null ?
(String)configService.getProperty(propName2) : null;
if(shortcut != null)
{
kss.add(AWTKeyStroke.getAWTKeyStroke(shortcut));
}
// second shortcut is always "special"
if(shortcut2 != null)
{
//16367 is the combination of all possible modifiers
//(shift ctrl meta alt altGraph button1 button2 button3 pressed)
//it is used to distinguish special key (headset) and others
int nb = Integer.parseInt(shortcut2);
kss.add(AWTKeyStroke.getAWTKeyStroke(nb, 16367));
}
gBindings.put(name, kss);
}
return gBindings;
}
/**
* Save the configuration file.
*/
public void saveGlobalShortcutFromConfiguration()
{
ConfigurationService configService =
KeybindingsActivator.getConfigService();
String shortcut = null;
String shortcut2 = null;
for(Map.Entry<String, List<AWTKeyStroke>> entry :
globalBindings.getBindings().entrySet())
{
String key = entry.getKey();
List<AWTKeyStroke> kss = entry.getValue();
String path = CONFIGURATION_PATH;
path += "." + key;
shortcut = path + ".1";
shortcut2 = path + ".2";
configService.setProperty(shortcut, kss.size() > 0 ?
kss.get(0) : null);
// second shortcut is special
configService.setProperty(shortcut2,
(kss.size() > 1 && kss.get(1) != null) ?
kss.get(1).getKeyCode() : null);
}
}
/**
* Provides the bindings associated with the global category.
*
* @return global keybinding set
*/
public GlobalKeybindingSet getGlobalBindings()
{
return globalBindings;
}
}
| Metaswitch/jitsi | src/net/java/sip/communicator/impl/keybindings/KeybindingsServiceImpl.java | Java | lgpl-2.1 | 15,260 |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2016
// cesarsouza at gmail.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.
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.MachineLearning
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Common interface for parallel algorithms.
/// </summary>
///
public interface IParallel : ISupportsCancellation
{
/// <summary>
/// Gets or sets the parallelization options for this algorithm.
/// </summary>
///
ParallelOptions ParallelOptions { get; set; }
}
/// <summary>
/// Common interface for algorithms that can be canceled
/// in the middle of execution.
/// </summary>
///
public interface ISupportsCancellation
{
/// <summary>
/// Gets or sets a cancellation token that can be used
/// to cancel the algorithm while it is running.
/// </summary>
///
CancellationToken Token { get; set; }
}
}
| cureos/accord | Sources/Accord.Statistics/Accord.MachineLearning/Learning/IParallel.cs | C# | lgpl-2.1 | 1,980 |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Editor configuration settings.
*
* Follow this link for more information:
* http://wiki.fckeditor.net/Developer%27s_Guide/Configuration/Configurations_Settings
*/
FCKConfig.CustomConfigurationsPath = '' ;
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;
FCKConfig.EditorAreaStyles = '' ;
FCKConfig.ToolbarComboPreviewCSS = '' ;
FCKConfig.DocType = '' ;
FCKConfig.BaseHref = '' ;
FCKConfig.FullPage = false ;
// The following option determines whether the "Show Blocks" feature is enabled or not at startup.
FCKConfig.StartupShowBlocks = false ;
FCKConfig.Debug = false ;
FCKConfig.AllowQueryStringDebug = true ;
FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ;
FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ;
FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ;
// FCKConfig.Plugins.Add( 'autogrow' ) ;
// FCKConfig.Plugins.Add( 'dragresizetable' );
FCKConfig.AutoGrowMax = 400 ;
// FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%>
// FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code
// FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control>
FCKConfig.AutoDetectLanguage = true ;
FCKConfig.DefaultLanguage = 'en' ;
FCKConfig.ContentLangDirection = 'ltr' ;
FCKConfig.ProcessHTMLEntities = true ;
FCKConfig.IncludeLatinEntities = true ;
FCKConfig.IncludeGreekEntities = true ;
FCKConfig.ProcessNumericEntities = false ;
FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'"
FCKConfig.FillEmptyBlocks = true ;
FCKConfig.FormatSource = true ;
FCKConfig.FormatOutput = true ;
FCKConfig.FormatIndentator = ' ' ;
FCKConfig.GeckoUseSPAN = false ;
FCKConfig.StartupFocus = false ;
FCKConfig.ForcePasteAsPlainText = false ;
FCKConfig.AutoDetectPasteFromWord = true ; // IE only.
FCKConfig.ShowDropDialog = true ;
FCKConfig.ForceSimpleAmpersand = false ;
FCKConfig.TabSpaces = 0 ;
FCKConfig.ShowBorders = true ;
FCKConfig.SourcePopup = false ;
FCKConfig.ToolbarStartExpanded = true ;
FCKConfig.ToolbarCanCollapse = true ;
FCKConfig.IgnoreEmptyParagraphValue = true ;
FCKConfig.PreserveSessionOnFileBrowser = false ;
FCKConfig.FloatingPanelsZIndex = 10000 ;
FCKConfig.HtmlEncodeOutput = false ;
FCKConfig.TemplateReplaceAll = true ;
FCKConfig.TemplateReplaceCheckbox = true ;
FCKConfig.ToolbarLocation = 'In' ;
FCKConfig.ToolbarSets["Default"] = [
['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
] ;
FCKConfig.ToolbarSets["Basic"] = [
['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About']
] ;
FCKConfig.ToolbarSets["Copix"] = [
['Source'],
['Cut','Copy','Paste','PasteText','PasteWord'],
['Undo','Redo','-','Find','Replace'],
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Rule','SpecialChar','Smiley']
//['Style', 'mailto'],//, 'phototheque','document','cmslink','cmslinkpopup'],'/',
//['Table','-','TableInsertRow','TableDeleteRows','TableInsertColumn','TableDeleteColumns','TableInsertCell','TableDeleteCells','TableMergeCells','TableSplitCell']
] ;
FCKConfig.EnterMode = 'p' ; // p | div | br
FCKConfig.ShiftEnterMode = 'br' ; // p | div | br
FCKConfig.Keystrokes = [
[ CTRL + 65 /*A*/, true ],
[ CTRL + 67 /*C*/, true ],
[ CTRL + 70 /*F*/, true ],
[ CTRL + 83 /*S*/, true ],
[ CTRL + 88 /*X*/, true ],
[ CTRL + 86 /*V*/, 'Paste' ],
[ SHIFT + 45 /*INS*/, 'Paste' ],
[ CTRL + 88 /*X*/, 'Cut' ],
[ SHIFT + 46 /*DEL*/, 'Cut' ],
[ CTRL + 90 /*Z*/, 'Undo' ],
[ CTRL + 89 /*Y*/, 'Redo' ],
[ CTRL + SHIFT + 90 /*Z*/, 'Redo' ],
[ CTRL + 76 /*L*/, 'Link' ],
[ CTRL + 66 /*B*/, 'Bold' ],
[ CTRL + 73 /*I*/, 'Italic' ],
[ CTRL + 85 /*U*/, 'Underline' ],
[ CTRL + SHIFT + 83 /*S*/, 'Save' ],
[ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ],
[ CTRL + 9 /*TAB*/, 'Source' ]
] ;
FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form'] ;
FCKConfig.BrowserContextMenuOnCtrl = false ;
FCKConfig.EnableMoreFontColors = true ;
FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ;
FCKConfig.FontFormats = 'p;div;pre;address;h1;h2;h3;h4;h5;h6' ;
FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;
FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ;
FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ;
FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ;
FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages'
FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ;
FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl
FCKConfig.FirefoxSpellChecker = false ;
FCKConfig.MaxUndoLevels = 15 ;
FCKConfig.DisableObjectResizing = false ;
FCKConfig.DisableFFTableHandles = true ;
FCKConfig.LinkDlgHideTarget = false ;
FCKConfig.LinkDlgHideAdvanced = false ;
FCKConfig.ImageDlgHideLink = false ;
FCKConfig.ImageDlgHideAdvanced = false ;
FCKConfig.FlashDlgHideAdvanced = false ;
FCKConfig.ProtectedTags = '' ;
// This will be applied to the body element of the editor
FCKConfig.BodyId = '' ;
FCKConfig.BodyClass = '' ;
FCKConfig.DefaultStyleLabel = '' ;
FCKConfig.DefaultFontFormatLabel = '' ;
FCKConfig.DefaultFontLabel = '' ;
FCKConfig.DefaultFontSizeLabel = '' ;
FCKConfig.DefaultLinkTarget = '' ;
// The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word
FCKConfig.CleanWordKeepsStructure = false ;
// Only inline elements are valid.
FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ;
FCKConfig.CustomStyles =
{
'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } }
};
// Do not add, rename or remove styles here. Only apply definition changes.
FCKConfig.CoreStyles =
{
// Basic Inline Styles.
'Bold' : { Element : 'b', Overrides : 'strong' },
'Italic' : { Element : 'i', Overrides : 'em' },
'Underline' : { Element : 'u' },
'StrikeThrough' : { Element : 'strike' },
'Subscript' : { Element : 'sub' },
'Superscript' : { Element : 'sup' },
// Basic Block Styles (Font Format Combo).
'p' : { Element : 'p' },
'div' : { Element : 'div' },
'pre' : { Element : 'pre' },
'address' : { Element : 'address' },
'h1' : { Element : 'h1' },
'h2' : { Element : 'h2' },
'h3' : { Element : 'h3' },
'h4' : { Element : 'h4' },
'h5' : { Element : 'h5' },
'h6' : { Element : 'h6' },
// Other formatting features.
'FontFace' :
{
Element : 'span',
Styles : { 'font-family' : '#("Font")' },
Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ]
},
'Size' :
{
Element : 'span',
Styles : { 'font-size' : '#("Size","fontSize")' },
Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ]
},
'Color' :
{
Element : 'span',
Styles : { 'color' : '#("Color","color")' },
Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ]
},
'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } }
};
// The distance of an indentation step.
FCKConfig.IndentLength = 40 ;
FCKConfig.IndentUnit = 'px' ;
// Alternatively, FCKeditor allows the use of CSS classes for block indentation.
// This overrides the IndentLength/IndentUnit settings.
FCKConfig.IndentClasses = [] ;
// [ Left, Center, Right, Justified ]
FCKConfig.JustifyClasses = [] ;
// The following value defines which File Browser connector and Quick Upload
// "uploader" to use. It is valid for the default implementaion and it is here
// just to make this configuration file cleaner.
// It is not possible to change this value using an external file or even
// inline when creating the editor instance. In that cases you must set the
// values of LinkBrowserURL, ImageBrowserURL and so on.
// Custom implementations should just ignore it.
var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
// Don't care about the following line. It just calculates the correct connector
// extension to use for the default File Browser (Perl uses "cgi").
var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ;
FCKConfig.LinkBrowser = true ;
FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ;
FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70%
FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70%
FCKConfig.ImageBrowser = true ;
FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ;
FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ;
FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ;
FCKConfig.FlashBrowser = true ;
FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ;
FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ;
FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ;
FCKConfig.LinkUpload = true ;
FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage ;
FCKConfig.LinkUploadAllowedExtensions = "" ; // empty for all
FCKConfig.LinkUploadDeniedExtensions = ".(html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|sh|shtml|shtm|phtm)$" ; // empty for no one
FCKConfig.ImageUpload = true ;
FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage + '?Type=Image' ;
FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all
FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.FlashUpload = true ;
FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage + '?Type=Flash' ;
FCKConfig.FlashUploadAllowedExtensions = ".(swf|fla)$" ; // empty for all
FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ;
FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ;
FCKConfig.SmileyColumns = 8 ;
FCKConfig.SmileyWindowWidth = 320 ;
FCKConfig.SmileyWindowHeight = 240 ;
| Copix/Copix3 | www/js/FCKeditor/fckconfig.js | JavaScript | lgpl-2.1 | 13,198 |
/////////////////////////////////////////////////////////////////////////////
// Name: controls.cpp
// Purpose: Controls wxWidgets sample
// Author: Robert Roebling
// Modified by:
// RCS-ID: $Id$
// Copyright: (c) Robert Roebling, Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/spinbutt.h"
#include "wx/tglbtn.h"
#include "wx/bookctrl.h"
#include "wx/imaglist.h"
#include "wx/artprov.h"
#include "wx/cshelp.h"
#include "wx/gbsizer.h"
#if wxUSE_TOOLTIPS
#include "wx/tooltip.h"
#ifdef __WXMSW__
#include "wx/numdlg.h"
#endif // __WXMSW__
#endif // wxUSE_TOOLTIPS
#ifndef __WXMSW__
#include "icons/choice.xpm"
#include "icons/combo.xpm"
#include "icons/list.xpm"
#include "icons/radio.xpm"
#include "icons/text.xpm"
#include "icons/gauge.xpm"
#endif
#ifndef wxUSE_SPINBTN
#define wxUSE_SPINBTN 1
#endif
#include "wx/progdlg.h"
#if wxUSE_SPINCTRL
#include "wx/spinctrl.h"
#endif // wxUSE_SPINCTRL
#if !wxUSE_TOGGLEBTN
#define wxToggleButton wxCheckBox
#define EVT_TOGGLEBUTTON EVT_CHECKBOX
#endif
#ifndef wxHAS_IMAGES_IN_RESOURCES
#include "../sample.xpm"
#endif
//----------------------------------------------------------------------
// class definitions
//----------------------------------------------------------------------
class MyApp: public wxApp
{
public:
bool OnInit();
};
class MyPanel: public wxPanel
{
public:
MyPanel(wxFrame *frame, int x, int y, int w, int h);
virtual ~MyPanel();
#if wxUSE_TOOLTIPS
void SetAllToolTips();
#endif // wxUSE_TOOLTIPS
void OnIdle( wxIdleEvent &event );
void OnListBox( wxCommandEvent &event );
void OnListBoxDoubleClick( wxCommandEvent &event );
void OnListBoxButtons( wxCommandEvent &event );
#if wxUSE_CHOICE
void OnChoice( wxCommandEvent &event );
void OnChoiceButtons( wxCommandEvent &event );
#endif
void OnCombo( wxCommandEvent &event );
void OnComboTextChanged( wxCommandEvent &event );
void OnComboTextEnter( wxCommandEvent &event );
void OnComboButtons( wxCommandEvent &event );
void OnRadio( wxCommandEvent &event );
void OnRadioButtons( wxCommandEvent &event );
void OnRadioButton1( wxCommandEvent &event );
void OnRadioButton2( wxCommandEvent &event );
void OnSetFont( wxCommandEvent &event );
void OnPageChanged( wxBookCtrlEvent &event );
void OnPageChanging( wxBookCtrlEvent &event );
void OnSliderUpdate( wxCommandEvent &event );
void OnUpdateLabel( wxCommandEvent &event );
#if wxUSE_SPINBTN
void OnSpinUp( wxSpinEvent &event );
void OnSpinDown( wxSpinEvent &event );
void OnSpinUpdate( wxSpinEvent &event );
#if wxUSE_PROGRESSDLG
void OnUpdateShowProgress( wxUpdateUIEvent& event );
void OnShowProgress( wxCommandEvent &event );
#endif // wxUSE_PROGRESSDLG
#endif // wxUSE_SPINBTN
void OnNewText( wxCommandEvent &event );
#if wxUSE_SPINCTRL
void OnSpinCtrl(wxSpinEvent& event);
void OnSpinCtrlUp(wxSpinEvent& event);
void OnSpinCtrlDown(wxSpinEvent& event);
void OnSpinCtrlText(wxCommandEvent& event);
#endif // wxUSE_SPINCTRL
void OnEnableAll(wxCommandEvent& event);
void OnChangeColour(wxCommandEvent& event);
void OnTestButton(wxCommandEvent& event);
void OnBmpButton(wxCommandEvent& event);
void OnBmpButtonToggle(wxCommandEvent& event);
void OnSizerCheck (wxCommandEvent &event);
wxListBox *m_listbox,
*m_listboxSorted;
#if wxUSE_CHOICE
wxChoice *m_choice,
*m_choiceSorted;
#endif // wxUSE_CHOICE
wxComboBox *m_combo;
wxRadioBox *m_radio;
#if wxUSE_GAUGE
wxGauge *m_gauge,
*m_gaugeVert;
#endif // wxUSE_GAUGE
#if wxUSE_SLIDER
wxSlider *m_slider;
#endif // wxUSE_SLIDER
wxButton *m_fontButton;
wxButton *m_lbSelectNum;
wxButton *m_lbSelectThis;
#if wxUSE_SPINBTN
wxSpinButton *m_spinbutton;
#if wxUSE_PROGRESSDLG
wxButton *m_btnProgress;
#endif // wxUSE_PROGRESSDLG
#endif // wxUSE_SPINBTN
wxStaticText *m_wrappingText;
wxStaticText *m_nonWrappingText;
#if wxUSE_SPINCTRL
wxSpinCtrl *m_spinctrl;
#endif // wxUSE_SPINCTRL
wxTextCtrl *m_spintext;
wxCheckBox *m_checkbox;
wxTextCtrl *m_text;
wxBookCtrl *m_book;
wxStaticText *m_label;
wxBoxSizer *m_buttonSizer;
wxButton *m_sizerBtn1;
wxButton *m_sizerBtn2;
wxButton *m_sizerBtn3;
wxButton *m_sizerBtn4;
wxBoxSizer *m_hsizer;
wxButton *m_bigBtn;
private:
wxLog *m_logTargetOld;
DECLARE_EVENT_TABLE()
};
class MyFrame: public wxFrame
{
public:
MyFrame(const wxChar *title, int x, int y);
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnClearLog(wxCommandEvent& event);
#if wxUSE_TOOLTIPS
void OnSetTooltipDelay(wxCommandEvent& event);
void OnToggleTooltips(wxCommandEvent& event);
#ifdef __WXMSW__
void OnSetMaxTooltipWidth(wxCommandEvent& event);
#endif // __WXMSW__
#endif // wxUSE_TOOLTIPS
void OnEnableAll(wxCommandEvent& event);
void OnHideAll(wxCommandEvent& event);
void OnHideList(wxCommandEvent& event);
void OnContextHelp(wxCommandEvent& event);
void OnIdle( wxIdleEvent& event );
void OnIconized( wxIconizeEvent& event );
void OnMaximized( wxMaximizeEvent& event );
void OnSize( wxSizeEvent& event );
void OnMove( wxMoveEvent& event );
MyPanel *GetPanel() const { return m_panel; }
private:
#if wxUSE_STATUSBAR
void UpdateStatusBar(const wxPoint& pos, const wxSize& size)
{
if ( m_frameStatusBar )
{
wxString msg;
wxSize sizeAll = GetSize(),
sizeCl = GetClientSize();
msg.Printf(_("pos=(%d, %d), size=%dx%d or %dx%d (client=%dx%d)"),
pos.x, pos.y,
size.x, size.y,
sizeAll.x, sizeAll.y,
sizeCl.x, sizeCl.y);
SetStatusText(msg, 1);
}
}
#endif // wxUSE_STATUSBAR
MyPanel *m_panel;
DECLARE_EVENT_TABLE()
};
// a button which intercepts double clicks (for testing...)
class MyButton : public wxButton
{
public:
MyButton(wxWindow *parent,
wxWindowID id,
const wxString& label = wxEmptyString,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize)
: wxButton(parent, id, label, pos, size)
{
}
void OnDClick(wxMouseEvent& event)
{
wxLogMessage(wxT("MyButton::OnDClick"));
event.Skip();
}
private:
DECLARE_EVENT_TABLE()
};
// a combo which intercepts chars (to test Windows behaviour)
class MyComboBox : public wxComboBox
{
public:
MyComboBox(wxWindow *parent, wxWindowID id,
const wxString& value = wxEmptyString,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
int n = 0, const wxString choices[] = NULL,
long style = 0,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxComboBoxNameStr)
: wxComboBox(parent, id, value, pos, size, n, choices, style,
validator, name) { }
protected:
void OnChar(wxKeyEvent& event);
void OnKeyDown(wxKeyEvent& event);
void OnKeyUp(wxKeyEvent& event);
void OnFocusGot(wxFocusEvent& event)
{
wxLogMessage(wxT("MyComboBox::OnFocusGot"));
event.Skip();
}
private:
DECLARE_EVENT_TABLE()
};
// a radiobox which handles focus set/kill (for testing)
class MyRadioBox : public wxRadioBox
{
public:
MyRadioBox(wxWindow *parent,
wxWindowID id,
const wxString& title = wxEmptyString,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
int n = 0, const wxString choices[] = NULL,
int majorDim = 1,
long style = wxRA_SPECIFY_COLS,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxRadioBoxNameStr)
: wxRadioBox(parent, id, title, pos, size, n, choices, majorDim,
style, validator, name)
{
}
protected:
void OnFocusGot(wxFocusEvent& event)
{
wxLogMessage(wxT("MyRadioBox::OnFocusGot"));
event.Skip();
}
void OnFocusLost(wxFocusEvent& event)
{
wxLogMessage(wxT("MyRadioBox::OnFocusLost"));
event.Skip();
}
private:
DECLARE_EVENT_TABLE()
};
// a choice which handles focus set/kill (for testing)
class MyChoice : public wxChoice
{
public:
MyChoice(wxWindow *parent,
wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
int n = 0, const wxString choices[] = NULL,
long style = 0,
const wxValidator& validator = wxDefaultValidator,
const wxString& name = wxChoiceNameStr )
: wxChoice(parent, id, pos, size, n, choices,
style, validator, name) { }
protected:
void OnFocusGot(wxFocusEvent& event)
{
wxLogMessage(wxT("MyChoice::OnFocusGot"));
event.Skip();
}
void OnFocusLost(wxFocusEvent& event)
{
wxLogMessage(wxT("MyChoice::OnFocusLost"));
event.Skip();
}
private:
DECLARE_EVENT_TABLE()
};
//----------------------------------------------------------------------
// other
//----------------------------------------------------------------------
static void SetListboxClientData(const wxChar *name, wxListBox *control);
#if wxUSE_CHOICE
static void SetChoiceClientData(const wxChar *name, wxChoice *control);
#endif // wxUSE_CHOICE
IMPLEMENT_APP(MyApp)
//----------------------------------------------------------------------
// MyApp
//----------------------------------------------------------------------
enum
{
CONTROLS_QUIT = wxID_EXIT,
CONTROLS_ABOUT = wxID_ABOUT,
CONTROLS_TEXT = 100,
CONTROLS_CLEAR_LOG,
// tooltip menu
CONTROLS_SET_TOOLTIP_DELAY = 200,
CONTROLS_ENABLE_TOOLTIPS,
CONTROLS_SET_TOOLTIPS_MAX_WIDTH,
// panel menu
CONTROLS_ENABLE_ALL,
CONTROLS_HIDE_ALL,
CONTROLS_HIDE_LIST,
CONTROLS_CONTEXT_HELP
};
bool MyApp::OnInit()
{
// use standard command line handling:
if ( !wxApp::OnInit() )
return false;
// parse the cmd line
int x = 50,
y = 50;
if ( argc == 3 )
{
wxSscanf(wxString(argv[1]), wxT("%d"), &x);
wxSscanf(wxString(argv[2]), wxT("%d"), &y);
}
#if wxUSE_HELP
wxHelpProvider::Set( new wxSimpleHelpProvider );
#endif // wxUSE_HELP
// Create the main frame window
MyFrame *frame = new MyFrame(wxT("Controls wxWidgets App"), x, y);
frame->Show(true);
return true;
}
//----------------------------------------------------------------------
// MyPanel
//----------------------------------------------------------------------
const int ID_BOOK = 1000;
const int ID_LISTBOX = 130;
const int ID_LISTBOX_SEL_NUM = 131;
const int ID_LISTBOX_SEL_STR = 132;
const int ID_LISTBOX_CLEAR = 133;
const int ID_LISTBOX_APPEND = 134;
const int ID_LISTBOX_DELETE = 135;
const int ID_LISTBOX_FONT = 136;
const int ID_LISTBOX_ENABLE = 137;
const int ID_LISTBOX_SORTED = 138;
const int ID_CHOICE = 120;
const int ID_CHOICE_SEL_NUM = 121;
const int ID_CHOICE_SEL_STR = 122;
const int ID_CHOICE_CLEAR = 123;
const int ID_CHOICE_APPEND = 124;
const int ID_CHOICE_DELETE = 125;
const int ID_CHOICE_FONT = 126;
const int ID_CHOICE_ENABLE = 127;
const int ID_CHOICE_SORTED = 128;
const int ID_COMBO = 140;
const int ID_COMBO_SEL_NUM = 141;
const int ID_COMBO_SEL_STR = 142;
const int ID_COMBO_CLEAR = 143;
const int ID_COMBO_APPEND = 144;
const int ID_COMBO_DELETE = 145;
const int ID_COMBO_FONT = 146;
const int ID_COMBO_ENABLE = 147;
const int ID_COMBO_SET_TEXT = 148;
const int ID_RADIOBOX = 160;
const int ID_RADIOBOX_SEL_NUM = 161;
const int ID_RADIOBOX_SEL_STR = 162;
const int ID_RADIOBOX_FONT = 163;
const int ID_RADIOBOX_ENABLE = 164;
const int ID_RADIOBOX2 = 165;
const int ID_RADIOBUTTON_1 = 166;
const int ID_RADIOBUTTON_2 = 167;
const int ID_SET_FONT = 170;
#if wxUSE_GAUGE
const int ID_GAUGE = 180;
#endif // wxUSE_GAUGE
#if wxUSE_SLIDER
const int ID_SLIDER = 181;
#endif // wxUSE_SLIDER
const int ID_SPIN = 182;
#if wxUSE_PROGRESSDLG
const int ID_BTNPROGRESS = 183;
#endif // wxUSE_PROGRESSDLG
const int ID_BUTTON_LABEL = 184;
const int ID_SPINCTRL = 185;
const int ID_BTNNEWTEXT = 186;
const int ID_BUTTON_TEST1 = 190;
const int ID_BUTTON_TEST2 = 191;
const int ID_BITMAP_BTN = 192;
const int ID_BITMAP_BTN_ENABLE = 193;
const int ID_CHANGE_COLOUR = 200;
const int ID_SIZER_CHECK1 = 201;
const int ID_SIZER_CHECK2 = 202;
const int ID_SIZER_CHECK3 = 203;
const int ID_SIZER_CHECK4 = 204;
const int ID_SIZER_CHECK14 = 205;
const int ID_SIZER_CHECKBIG = 206;
const int ID_HYPERLINK = 300;
BEGIN_EVENT_TABLE(MyPanel, wxPanel)
EVT_IDLE ( MyPanel::OnIdle)
EVT_BOOKCTRL_PAGE_CHANGING(ID_BOOK, MyPanel::OnPageChanging)
EVT_BOOKCTRL_PAGE_CHANGED(ID_BOOK, MyPanel::OnPageChanged)
EVT_LISTBOX (ID_LISTBOX, MyPanel::OnListBox)
EVT_LISTBOX (ID_LISTBOX_SORTED, MyPanel::OnListBox)
EVT_LISTBOX_DCLICK(ID_LISTBOX, MyPanel::OnListBoxDoubleClick)
EVT_BUTTON (ID_LISTBOX_SEL_NUM, MyPanel::OnListBoxButtons)
EVT_BUTTON (ID_LISTBOX_SEL_STR, MyPanel::OnListBoxButtons)
EVT_BUTTON (ID_LISTBOX_CLEAR, MyPanel::OnListBoxButtons)
EVT_BUTTON (ID_LISTBOX_APPEND, MyPanel::OnListBoxButtons)
EVT_BUTTON (ID_LISTBOX_DELETE, MyPanel::OnListBoxButtons)
EVT_BUTTON (ID_LISTBOX_FONT, MyPanel::OnListBoxButtons)
EVT_CHECKBOX (ID_LISTBOX_ENABLE, MyPanel::OnListBoxButtons)
#if wxUSE_CHOICE
EVT_CHOICE (ID_CHOICE, MyPanel::OnChoice)
EVT_CHOICE (ID_CHOICE_SORTED, MyPanel::OnChoice)
EVT_BUTTON (ID_CHOICE_SEL_NUM, MyPanel::OnChoiceButtons)
EVT_BUTTON (ID_CHOICE_SEL_STR, MyPanel::OnChoiceButtons)
EVT_BUTTON (ID_CHOICE_CLEAR, MyPanel::OnChoiceButtons)
EVT_BUTTON (ID_CHOICE_APPEND, MyPanel::OnChoiceButtons)
EVT_BUTTON (ID_CHOICE_DELETE, MyPanel::OnChoiceButtons)
EVT_BUTTON (ID_CHOICE_FONT, MyPanel::OnChoiceButtons)
EVT_CHECKBOX (ID_CHOICE_ENABLE, MyPanel::OnChoiceButtons)
#endif
EVT_COMBOBOX (ID_COMBO, MyPanel::OnCombo)
EVT_TEXT (ID_COMBO, MyPanel::OnComboTextChanged)
EVT_TEXT_ENTER(ID_COMBO, MyPanel::OnComboTextEnter)
EVT_BUTTON (ID_COMBO_SEL_NUM, MyPanel::OnComboButtons)
EVT_BUTTON (ID_COMBO_SEL_STR, MyPanel::OnComboButtons)
EVT_BUTTON (ID_COMBO_CLEAR, MyPanel::OnComboButtons)
EVT_BUTTON (ID_COMBO_APPEND, MyPanel::OnComboButtons)
EVT_BUTTON (ID_COMBO_DELETE, MyPanel::OnComboButtons)
EVT_BUTTON (ID_COMBO_FONT, MyPanel::OnComboButtons)
EVT_BUTTON (ID_COMBO_SET_TEXT, MyPanel::OnComboButtons)
EVT_CHECKBOX (ID_COMBO_ENABLE, MyPanel::OnComboButtons)
EVT_RADIOBOX (ID_RADIOBOX, MyPanel::OnRadio)
EVT_RADIOBOX (ID_RADIOBOX2, MyPanel::OnRadio)
EVT_BUTTON (ID_RADIOBOX_SEL_NUM, MyPanel::OnRadioButtons)
EVT_BUTTON (ID_RADIOBOX_SEL_STR, MyPanel::OnRadioButtons)
EVT_BUTTON (ID_RADIOBOX_FONT, MyPanel::OnRadioButtons)
EVT_CHECKBOX (ID_RADIOBOX_ENABLE, MyPanel::OnRadioButtons)
EVT_RADIOBUTTON(ID_RADIOBUTTON_1, MyPanel::OnRadioButton1)
EVT_RADIOBUTTON(ID_RADIOBUTTON_2, MyPanel::OnRadioButton2)
EVT_BUTTON (ID_SET_FONT, MyPanel::OnSetFont)
#if wxUSE_SLIDER
EVT_SLIDER (ID_SLIDER, MyPanel::OnSliderUpdate)
#endif // wxUSE_SLIDER
#if wxUSE_SPINBTN
EVT_SPIN (ID_SPIN, MyPanel::OnSpinUpdate)
EVT_SPIN_UP (ID_SPIN, MyPanel::OnSpinUp)
EVT_SPIN_DOWN (ID_SPIN, MyPanel::OnSpinDown)
#if wxUSE_PROGRESSDLG
EVT_UPDATE_UI (ID_BTNPROGRESS, MyPanel::OnUpdateShowProgress)
EVT_BUTTON (ID_BTNPROGRESS, MyPanel::OnShowProgress)
#endif // wxUSE_PROGRESSDLG
#endif // wxUSE_SPINBTN
#if wxUSE_SPINCTRL
EVT_SPINCTRL (ID_SPINCTRL, MyPanel::OnSpinCtrl)
EVT_SPIN_UP (ID_SPINCTRL, MyPanel::OnSpinCtrlUp)
EVT_SPIN_DOWN (ID_SPINCTRL, MyPanel::OnSpinCtrlDown)
EVT_TEXT (ID_SPINCTRL, MyPanel::OnSpinCtrlText)
#endif // wxUSE_SPINCTRL
EVT_BUTTON (ID_BTNNEWTEXT, MyPanel::OnNewText)
EVT_TOGGLEBUTTON(ID_BUTTON_LABEL, MyPanel::OnUpdateLabel)
EVT_CHECKBOX (ID_CHANGE_COLOUR, MyPanel::OnChangeColour)
EVT_BUTTON (ID_BUTTON_TEST1, MyPanel::OnTestButton)
EVT_BUTTON (ID_BUTTON_TEST2, MyPanel::OnTestButton)
EVT_BUTTON (ID_BITMAP_BTN, MyPanel::OnBmpButton)
EVT_TOGGLEBUTTON(ID_BITMAP_BTN_ENABLE, MyPanel::OnBmpButtonToggle)
EVT_CHECKBOX (ID_SIZER_CHECK1, MyPanel::OnSizerCheck)
EVT_CHECKBOX (ID_SIZER_CHECK2, MyPanel::OnSizerCheck)
EVT_CHECKBOX (ID_SIZER_CHECK3, MyPanel::OnSizerCheck)
EVT_CHECKBOX (ID_SIZER_CHECK4, MyPanel::OnSizerCheck)
EVT_CHECKBOX (ID_SIZER_CHECK14, MyPanel::OnSizerCheck)
EVT_CHECKBOX (ID_SIZER_CHECKBIG, MyPanel::OnSizerCheck)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(MyButton, wxButton)
EVT_LEFT_DCLICK(MyButton::OnDClick)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(MyComboBox, wxComboBox)
EVT_CHAR(MyComboBox::OnChar)
EVT_KEY_DOWN(MyComboBox::OnKeyDown)
EVT_KEY_UP(MyComboBox::OnKeyUp)
EVT_SET_FOCUS(MyComboBox::OnFocusGot)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(MyRadioBox, wxRadioBox)
EVT_SET_FOCUS(MyRadioBox::OnFocusGot)
EVT_KILL_FOCUS(MyRadioBox::OnFocusLost)
END_EVENT_TABLE()
BEGIN_EVENT_TABLE(MyChoice, wxChoice)
EVT_SET_FOCUS(MyChoice::OnFocusGot)
EVT_KILL_FOCUS(MyChoice::OnFocusLost)
END_EVENT_TABLE()
// ============================================================================
// implementation
// ============================================================================
MyPanel::MyPanel( wxFrame *frame, int x, int y, int w, int h )
: wxPanel( frame, wxID_ANY, wxPoint(x, y), wxSize(w, h) )
{
m_listbox = NULL;
m_listboxSorted = NULL;
#if wxUSE_CHOICE
m_choice = NULL;
m_choiceSorted = NULL;
#endif // wxUSE_CHOICE
m_combo = NULL;
m_radio = NULL;
#if wxUSE_GAUGE
m_gauge = NULL;
m_gaugeVert = NULL;
#endif // wxUSE_GAUGE
#if wxUSE_SLIDER
m_slider = NULL;
#endif // wxUSE_SLIDER
m_fontButton = NULL;
m_lbSelectNum = NULL;
m_lbSelectThis = NULL;
#if wxUSE_SPINBTN
m_spinbutton = NULL;
#if wxUSE_PROGRESSDLG
m_btnProgress = NULL;
#endif // wxUSE_PROGRESSDLG
#endif // wxUSE_SPINBTN
#if wxUSE_SPINCTRL
m_spinctrl = NULL;
#endif // wxUSE_SPINCTRL
m_spintext = NULL;
m_checkbox = NULL;
m_text = NULL;
m_book = NULL;
m_label = NULL;
m_text = new wxTextCtrl(this, wxID_ANY, wxT("This is the log window.\n"),
wxPoint(0, 250), wxSize(100, 50), wxTE_MULTILINE);
m_logTargetOld = wxLog::SetActiveTarget(new wxLogTextCtrl(m_text));
m_book = new wxBookCtrl(this, ID_BOOK);
wxString choices[] =
{
wxT("This"),
wxT("is"),
wxT("one of my long and"),
wxT("wonderful"),
wxT("examples.")
};
#ifndef __WXMSW__
// image ids
enum
{
Image_List,
Image_Choice,
Image_Combo,
Image_Text,
Image_Radio,
#if wxUSE_GAUGE
Image_Gauge,
#endif // wxUSE_GAUGE
Image_Max
};
// fill the image list
wxBitmap bmp(list_xpm);
wxImageList *imagelist = new wxImageList(bmp.GetWidth(), bmp.GetHeight());
imagelist-> Add( bmp );
imagelist-> Add( wxBitmap( choice_xpm ));
imagelist-> Add( wxBitmap( combo_xpm ));
imagelist-> Add( wxBitmap( text_xpm ));
imagelist-> Add( wxBitmap( radio_xpm ));
#if wxUSE_GAUGE
imagelist-> Add( wxBitmap( gauge_xpm ));
#endif // wxUSE_GAUGE
m_book->SetImageList(imagelist);
#else
// load images from resources
enum
{
Image_List,
Image_Choice,
Image_Combo,
Image_Text,
Image_Radio,
#if wxUSE_GAUGE
Image_Gauge,
#endif // wxUSE_GAUGE
Image_Max
};
wxImageList *imagelist = new wxImageList(16, 16, false, Image_Max);
static const wxChar *s_iconNames[Image_Max] =
{
wxT("list")
, wxT("choice")
, wxT("combo")
, wxT("text")
, wxT("radio")
#if wxUSE_GAUGE
, wxT("gauge")
#endif // wxUSE_GAUGE
};
for ( size_t n = 0; n < Image_Max; n++ )
{
wxBitmap bmp(s_iconNames[n]);
if ( !bmp.IsOk() || (imagelist->Add(bmp) == -1) )
{
wxLogWarning(wxT("Couldn't load the image '%s' for the book control page %d."),
s_iconNames[n], n);
}
}
m_book->SetImageList(imagelist);
#endif
// ------------------------------------------------------------------------
// listbox page
// ------------------------------------------------------------------------
wxPanel *panel = new wxPanel(m_book);
m_listbox = new wxListBox( panel, ID_LISTBOX,
wxPoint(10,10), wxSize(120,70),
5, choices, wxLB_MULTIPLE | wxLB_ALWAYS_SB | wxHSCROLL );
m_listboxSorted = new wxListBox( panel, ID_LISTBOX_SORTED,
wxPoint(10,90), wxSize(120,70),
3, choices, wxLB_SORT );
SetListboxClientData(wxT("listbox"), m_listbox);
SetListboxClientData(wxT("listbox"), m_listboxSorted);
m_listbox->SetCursor(*wxCROSS_CURSOR);
m_lbSelectNum = new wxButton( panel, ID_LISTBOX_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) );
m_lbSelectThis = new wxButton( panel, ID_LISTBOX_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) );
(void)new wxButton( panel, ID_LISTBOX_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) );
(void)new MyButton( panel, ID_LISTBOX_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) );
(void)new wxButton( panel, ID_LISTBOX_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) );
wxButton *button = new MyButton( panel, ID_LISTBOX_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) );
button->SetDefault();
m_checkbox = new wxCheckBox( panel, ID_LISTBOX_ENABLE, wxT("&Disable"), wxPoint(20,170) );
m_checkbox->SetValue(false);
button->MoveAfterInTabOrder(m_checkbox);
(void)new wxCheckBox( panel, ID_CHANGE_COLOUR, wxT("&Toggle colour"),
wxPoint(110,170) );
panel->SetCursor(wxCursor(wxCURSOR_HAND));
m_book->AddPage(panel, wxT("wxListBox"), true, Image_List);
// ------------------------------------------------------------------------
// choice page
// ------------------------------------------------------------------------
#if wxUSE_CHOICE
panel = new wxPanel(m_book);
m_choice = new MyChoice( panel, ID_CHOICE, wxPoint(10,10), wxSize(120,wxDefaultCoord), 5, choices );
m_choiceSorted = new MyChoice( panel, ID_CHOICE_SORTED, wxPoint(10,70), wxSize(120,wxDefaultCoord),
5, choices, wxCB_SORT );
SetChoiceClientData(wxT("choice"), m_choice);
SetChoiceClientData(wxT("choice"), m_choiceSorted);
m_choice->SetSelection(2);
(void)new wxButton( panel, ID_CHOICE_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) );
(void)new wxButton( panel, ID_CHOICE_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) );
(void)new wxButton( panel, ID_CHOICE_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) );
(void)new wxButton( panel, ID_CHOICE_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) );
(void)new wxButton( panel, ID_CHOICE_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) );
(void)new wxButton( panel, ID_CHOICE_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) );
(void)new wxCheckBox( panel, ID_CHOICE_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) );
m_book->AddPage(panel, wxT("wxChoice"), false, Image_Choice);
#endif // wxUSE_CHOICE
// ------------------------------------------------------------------------
// combo page
// ------------------------------------------------------------------------
panel = new wxPanel(m_book);
(void)new wxStaticBox( panel, wxID_ANY, wxT("&Box around combobox"),
wxPoint(5, 5), wxSize(150, 100));
m_combo = new MyComboBox( panel, ID_COMBO, wxT("This"),
wxPoint(20,25), wxSize(120, wxDefaultCoord),
5, choices,
wxTE_PROCESS_ENTER);
(void)new wxButton( panel, ID_COMBO_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) );
(void)new wxButton( panel, ID_COMBO_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) );
(void)new wxButton( panel, ID_COMBO_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) );
(void)new wxButton( panel, ID_COMBO_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) );
(void)new wxButton( panel, ID_COMBO_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) );
(void)new wxButton( panel, ID_COMBO_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) );
(void)new wxButton( panel, ID_COMBO_SET_TEXT, wxT("Set 'Hi!' at #2"), wxPoint(340,180), wxSize(140,30) );
(void)new wxCheckBox( panel, ID_COMBO_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) );
m_book->AddPage(panel, wxT("wxComboBox"), false, Image_Combo);
// ------------------------------------------------------------------------
// radio box
// ------------------------------------------------------------------------
wxString choices2[] =
{
wxT("First"), wxT("Second"),
/* "Third",
"Fourth", "Fifth", "Sixth",
"Seventh", "Eighth", "Nineth", "Tenth" */
};
panel = new wxPanel(m_book);
wxGridBagSizer* radio_page_sizer = new wxGridBagSizer(5, 5);
m_radio = new wxRadioBox(panel, ID_RADIOBOX, wxT("T&his"),
wxPoint(10,10), wxDefaultSize,
WXSIZEOF(choices), choices,
1, wxRA_SPECIFY_COLS );
MyRadioBox* mybox = new MyRadioBox(panel, ID_RADIOBOX2, wxT("&That"),
wxPoint(10,160), wxDefaultSize,
WXSIZEOF(choices2), choices2,
1, wxRA_SPECIFY_ROWS );
radio_page_sizer->Add( m_radio, wxGBPosition(0,0), wxGBSpan(2,1) );
radio_page_sizer->Add( mybox, wxGBPosition(2,0), wxGBSpan(2,1) );
#if wxUSE_HELP
for (unsigned int item = 0; item < WXSIZEOF(choices); ++item)
m_radio->SetItemHelpText( item, wxString::Format( wxT("Help text for \"%s\""),
choices[item].c_str() ) );
// erase help text for the second item
m_radio->SetItemHelpText( 1, wxT("") );
// set default help text for control
m_radio->SetHelpText( wxT("Default helptext for wxRadioBox") );
#endif // wxUSE_HELP
wxButton* select_two = new wxButton ( panel, ID_RADIOBOX_SEL_NUM, wxT("Select #&2") );
wxButton* select_this = new wxButton ( panel, ID_RADIOBOX_SEL_STR, wxT("&Select 'This'") );
m_fontButton = new wxButton ( panel, ID_SET_FONT, wxT("Set &more Italic font") );
wxButton* set_italic = new wxButton ( panel, ID_RADIOBOX_FONT, wxT("Set &Italic font") );
wxCheckBox* disable_cb = new wxCheckBox( panel, ID_RADIOBOX_ENABLE, wxT("&Disable") );
wxRadioButton *rb = new wxRadioButton( panel, ID_RADIOBUTTON_1, wxT("Radiobutton1"),
wxDefaultPosition, wxDefaultSize, wxRB_GROUP );
wxRadioButton *rb2 = new wxRadioButton( panel, ID_RADIOBUTTON_2, wxT("&Radiobutton2"),
wxDefaultPosition, wxDefaultSize );
rb->SetValue( false );
radio_page_sizer->Add( select_two, wxGBPosition(0, 1), wxDefaultSpan, wxALL , 10 );
radio_page_sizer->Add( select_this, wxGBPosition(1, 1), wxDefaultSpan, wxALL , 10 );
radio_page_sizer->Add( m_fontButton, wxGBPosition(0, 2), wxDefaultSpan, wxALL , 10 );
radio_page_sizer->Add( set_italic, wxGBPosition(1, 2), wxDefaultSpan, wxALL , 10 );
radio_page_sizer->Add( disable_cb, wxGBPosition(2, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 );
radio_page_sizer->Add( rb, wxGBPosition(3, 1), wxDefaultSpan, wxLEFT | wxRIGHT, 10 );
radio_page_sizer->Add( rb2, wxGBPosition(3, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 );
panel->SetSizer( radio_page_sizer );
m_book->AddPage(panel, wxT("wxRadioBox"), false, Image_Radio);
// ------------------------------------------------------------------------
// gauge and slider
// ------------------------------------------------------------------------
#if wxUSE_SLIDER && wxUSE_GAUGE
panel = new wxPanel(m_book);
wxBoxSizer *gauge_page_vsizer = new wxBoxSizer( wxVERTICAL );
wxBoxSizer *gauge_page_first_row_sizer = new wxBoxSizer( wxHORIZONTAL );
wxStaticBoxSizer *gauge_sizer = new wxStaticBoxSizer( wxHORIZONTAL, panel, wxT("&wxGauge and wxSlider") );
gauge_page_first_row_sizer->Add( gauge_sizer, 0, wxALL, 5 );
wxBoxSizer *sz = new wxBoxSizer( wxVERTICAL );
gauge_sizer->Add( sz );
m_gauge = new wxGauge( panel, wxID_ANY, 200, wxDefaultPosition, wxSize(155, 30), wxGA_HORIZONTAL|wxNO_BORDER );
sz->Add( m_gauge, 0, wxALL, 10 );
m_slider = new wxSlider( panel, ID_SLIDER, 0, 0, 200,
wxDefaultPosition, wxSize(155,wxDefaultCoord),
wxSL_AUTOTICKS | wxSL_LABELS);
m_slider->SetTickFreq(40);
sz->Add( m_slider, 0, wxALL, 10 );
m_gaugeVert = new wxGauge( panel, wxID_ANY, 100,
wxDefaultPosition, wxSize(wxDefaultCoord, 90),
wxGA_VERTICAL | wxGA_SMOOTH | wxNO_BORDER );
gauge_sizer->Add( m_gaugeVert, 0, wxALL, 10 );
wxStaticBox *sb = new wxStaticBox( panel, wxID_ANY, wxT("&Explanation"),
wxDefaultPosition, wxDefaultSize ); //, wxALIGN_CENTER );
wxStaticBoxSizer *wrapping_sizer = new wxStaticBoxSizer( sb, wxVERTICAL );
gauge_page_first_row_sizer->Add( wrapping_sizer, 0, wxALL, 5 );
#ifdef __WXMOTIF__
// No wrapping text in wxStaticText yet :-(
m_wrappingText = new wxStaticText( panel, wxID_ANY,
wxT("Drag the slider!"),
wxPoint(250,30),
wxSize(240, wxDefaultCoord)
);
#else
m_wrappingText = new wxStaticText( panel, wxID_ANY,
wxT("In order see the gauge (aka progress bar) ")
wxT("control do something you have to drag the ")
wxT("handle of the slider to the right.")
wxT("\n\n")
wxT("This is also supposed to demonstrate how ")
wxT("to use static controls with line wrapping."),
wxDefaultPosition,
wxSize(240, wxDefaultCoord)
);
#endif
wrapping_sizer->Add( m_wrappingText );
wxStaticBoxSizer *non_wrapping_sizer = new wxStaticBoxSizer( wxVERTICAL, panel, wxT("Non-wrapping") );
gauge_page_first_row_sizer->Add( non_wrapping_sizer, 0, wxALL, 5 );
m_nonWrappingText = new wxStaticText( panel, wxID_ANY,
wxT("This static text has two lines.\nThey do not wrap."),
wxDefaultPosition,
wxDefaultSize
);
non_wrapping_sizer->Add( m_nonWrappingText );
gauge_page_vsizer->Add( gauge_page_first_row_sizer, 1 );
wxBoxSizer *gauge_page_second_row_sizer = new wxBoxSizer( wxHORIZONTAL );
int initialSpinValue = -5;
wxString s;
s << initialSpinValue;
m_spintext = new wxTextCtrl( panel, wxID_ANY, s );
gauge_page_second_row_sizer->Add( m_spintext, 0, wxALL, 5 );
#if wxUSE_SPINBTN
m_spinbutton = new wxSpinButton( panel, ID_SPIN );
m_spinbutton->SetRange(-40,30);
m_spinbutton->SetValue(initialSpinValue);
gauge_page_second_row_sizer->Add( m_spinbutton, 0, wxALL, 5 );
#endif // wxUSE_SPINBTN
#if wxUSE_SPINCTRL
m_spinctrl = new wxSpinCtrl( panel, ID_SPINCTRL, wxEmptyString );
m_spinctrl->SetRange(-10,30);
m_spinctrl->SetValue(15);
gauge_page_second_row_sizer->Add( m_spinctrl, 0, wxALL, 5 );
#endif // wxUSE_SPINCTRL
#if wxUSE_SPINBTN
#if wxUSE_PROGRESSDLG
m_btnProgress = new wxButton( panel, ID_BTNPROGRESS, wxT("&Show progress dialog") );
gauge_page_second_row_sizer->Add( m_btnProgress, 0, wxALL, 5 );
#endif // wxUSE_PROGRESSDLG
#endif // wxUSE_SPINBTN
wxButton* newTextButton = new wxButton( panel, ID_BTNNEWTEXT, wxT("New text"));
gauge_page_second_row_sizer->Add( newTextButton, 0, wxALL, 5 );
gauge_page_vsizer->Add(gauge_page_second_row_sizer, 1);
panel->SetSizer( gauge_page_vsizer );
m_book->AddPage(panel, wxT("wxGauge"), false, Image_Gauge);
#endif // wxUSE_SLIDER && wxUSE_GAUGE
// ------------------------------------------------------------------------
// wxBitmapXXX
// ------------------------------------------------------------------------
panel = new wxPanel(m_book);
#if !defined(__WXMOTIF__) // wxStaticBitmap not working under Motif yet.
wxIcon icon = wxArtProvider::GetIcon(wxART_INFORMATION);
(void) new wxStaticBitmap( panel, wxID_ANY, icon, wxPoint(10, 10) );
// VZ: don't leak memory
// bmpStatic = new wxStaticBitmap(panel, wxID_ANY, wxNullIcon, wxPoint(50, 10));
// bmpStatic->SetIcon(wxArtProvider::GetIcon(wxART_QUESTION));
#endif // !Motif
wxBitmap bitmap( 100, 100 );
wxMemoryDC dc;
dc.SelectObject( bitmap );
dc.SetBackground(*wxGREEN);
dc.SetPen(*wxRED_PEN);
dc.Clear();
dc.DrawEllipse(5, 5, 90, 90);
dc.DrawText(wxT("Bitmap"), 30, 40);
dc.SelectObject( wxNullBitmap );
wxPanel *panel2 = new wxPanel(panel, -1, wxPoint(100, 0), wxSize(100, 200));
(void)new wxBitmapButton(panel2, ID_BITMAP_BTN, bitmap, wxPoint(0, 20));
(void)new wxToggleButton(panel2, ID_BITMAP_BTN_ENABLE,
wxT("Enable/disable &bitmap"), wxPoint(0, 140));
#if defined(__WXMSW__) || defined(__WXMOTIF__)
// test for masked bitmap display
bitmap = wxBitmap(wxT("test2.bmp"), wxBITMAP_TYPE_BMP);
if (bitmap.IsOk())
{
bitmap.SetMask(new wxMask(bitmap, *wxBLUE));
(void)new wxStaticBitmap(panel, wxID_ANY, bitmap, wxPoint(300, 120));
}
#endif
wxBitmap bmp1(wxArtProvider::GetBitmap(wxART_INFORMATION)),
bmp2(wxArtProvider::GetBitmap(wxART_WARNING)),
bmp3(wxArtProvider::GetBitmap(wxART_QUESTION));
wxBitmapButton *bmpBtn = new wxBitmapButton
(
panel, wxID_ANY,
bmp1,
wxPoint(30, 70)
);
bmpBtn->SetBitmapSelected(bmp2);
bmpBtn->SetBitmapFocus(bmp3);
(void)new wxToggleButton(panel, ID_BUTTON_LABEL,
wxT("&Toggle label"), wxPoint(250, 20));
m_label = new wxStaticText(panel, wxID_ANY, wxT("Label with some long text"),
wxPoint(250, 60), wxDefaultSize,
wxALIGN_RIGHT /*| wxST_NO_AUTORESIZE*/);
m_label->SetForegroundColour( *wxBLUE );
m_book->AddPage(panel, wxT("wxBitmapXXX"));
// ------------------------------------------------------------------------
// sizer page
// ------------------------------------------------------------------------
panel = new wxPanel(m_book);
wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer *csizer =
new wxStaticBoxSizer (new wxStaticBox (panel, wxID_ANY, wxT("Show Buttons")), wxHORIZONTAL );
wxCheckBox *check1, *check2, *check3, *check4, *check14, *checkBig;
check1 = new wxCheckBox (panel, ID_SIZER_CHECK1, wxT("1"));
check1->SetValue (true);
csizer->Add (check1);
check2 = new wxCheckBox (panel, ID_SIZER_CHECK2, wxT("2"));
check2->SetValue (true);
csizer->Add (check2);
check3 = new wxCheckBox (panel, ID_SIZER_CHECK3, wxT("3"));
check3->SetValue (true);
csizer->Add (check3);
check4 = new wxCheckBox (panel, ID_SIZER_CHECK4, wxT("4"));
check4->SetValue (true);
csizer->Add (check4);
check14 = new wxCheckBox (panel, ID_SIZER_CHECK14, wxT("1-4"));
check14->SetValue (true);
csizer->Add (check14);
checkBig = new wxCheckBox (panel, ID_SIZER_CHECKBIG, wxT("Big"));
checkBig->SetValue (true);
csizer->Add (checkBig);
sizer->Add (csizer);
m_hsizer = new wxBoxSizer( wxHORIZONTAL );
m_buttonSizer = new wxBoxSizer (wxVERTICAL);
m_sizerBtn1 = new wxButton(panel, wxID_ANY, wxT("Test Button &1 (tab order 1)") );
m_buttonSizer->Add( m_sizerBtn1, 0, wxALL, 10 );
m_sizerBtn2 = new wxButton(panel, wxID_ANY, wxT("Test Button &2 (tab order 3)") );
m_buttonSizer->Add( m_sizerBtn2, 0, wxALL, 10 );
m_sizerBtn3 = new wxButton(panel, wxID_ANY, wxT("Test Button &3 (tab order 2)") );
m_buttonSizer->Add( m_sizerBtn3, 0, wxALL, 10 );
m_sizerBtn4 = new wxButton(panel, wxID_ANY, wxT("Test Button &4 (tab order 4)") );
m_buttonSizer->Add( m_sizerBtn4, 0, wxALL, 10 );
m_sizerBtn3->MoveBeforeInTabOrder(m_sizerBtn2);
m_hsizer->Add (m_buttonSizer);
m_hsizer->Add( 20,20, 1 );
m_bigBtn = new wxButton(panel, wxID_ANY, wxT("Multiline\nbutton") );
m_hsizer->Add( m_bigBtn , 3, wxGROW|wxALL, 10 );
sizer->Add (m_hsizer, 1, wxGROW);
panel->SetSizer( sizer );
m_book->AddPage(panel, wxT("wxSizer"));
// set the sizer for the panel itself
sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(m_book, wxSizerFlags().Border().Expand());
sizer->Add(m_text, wxSizerFlags(1).Border().Expand());
SetSizer(sizer);
#if wxUSE_TOOLTIPS
SetAllToolTips();
#endif // wxUSE_TOOLTIPS
}
#if wxUSE_TOOLTIPS
namespace
{
void ResetToolTip(wxWindow *win, const char *tip)
{
wxCHECK_RET( win, "NULL window?" );
win->UnsetToolTip();
win->SetToolTip(tip);
}
}
void MyPanel::SetAllToolTips()
{
ResetToolTip(FindWindow(ID_LISTBOX_FONT), "Press here to set italic font");
ResetToolTip(m_checkbox, "Click here to disable the listbox");
ResetToolTip(m_listbox, "This is a list box");
ResetToolTip(m_combo, "This is a natural\ncombobox - can you believe me?");
ResetToolTip(m_slider, "This is a sliding slider");
ResetToolTip(FindWindow(ID_RADIOBOX2), "Ever seen a radiobox?");
//ResetToolTip(m_radio, "Tooltip for the entire radiobox");
for ( unsigned int nb = 0; nb < m_radio->GetCount(); nb++ )
{
m_radio->SetItemToolTip(nb, "");
m_radio->SetItemToolTip(nb, "tooltip for\n" + m_radio->GetString(nb));
}
// remove the tooltip for one of the items
m_radio->SetItemToolTip(2, "");
}
#endif // wxUSE_TOOLTIPS
void MyPanel::OnIdle(wxIdleEvent& event)
{
static const int INVALID_SELECTION = -2;
static int s_selCombo = INVALID_SELECTION;
if (!m_combo || !m_choice)
{
event.Skip();
return;
}
int sel = m_combo->GetSelection();
if ( sel != s_selCombo )
{
if ( s_selCombo != INVALID_SELECTION )
{
wxLogMessage(wxT("EVT_IDLE: combobox selection changed from %d to %d"),
s_selCombo, sel);
}
s_selCombo = sel;
}
static int s_selChoice = INVALID_SELECTION;
sel = m_choice->GetSelection();
if ( sel != s_selChoice )
{
if ( s_selChoice != INVALID_SELECTION )
{
wxLogMessage(wxT("EVT_IDLE: choice selection changed from %d to %d"),
s_selChoice, sel);
}
s_selChoice = sel;
}
event.Skip();
}
void MyPanel::OnPageChanging( wxBookCtrlEvent &event )
{
int selOld = event.GetOldSelection();
if ( selOld == 2 )
{
if ( wxMessageBox(wxT("This demonstrates how a program may prevent the\n")
wxT("page change from taking place - if you select\n")
wxT("[No] the current page will stay the third one\n"),
wxT("Control sample"),
wxICON_QUESTION | wxYES_NO, this) != wxYES )
{
event.Veto();
return;
}
}
*m_text << wxT("Book selection is being changed from ") << selOld
<< wxT(" to ") << event.GetSelection()
<< wxT(" (current page from book is ")
<< m_book->GetSelection() << wxT(")\n");
}
void MyPanel::OnPageChanged( wxBookCtrlEvent &event )
{
*m_text << wxT("Book selection is now ") << event.GetSelection()
<< wxT(" (from book: ") << m_book->GetSelection()
<< wxT(")\n");
}
void MyPanel::OnTestButton(wxCommandEvent& event)
{
wxLogMessage(wxT("Button %c clicked."),
event.GetId() == ID_BUTTON_TEST1 ? wxT('1') : wxT('2'));
}
void MyPanel::OnBmpButton(wxCommandEvent& WXUNUSED(event))
{
wxLogMessage(wxT("Bitmap button clicked."));
}
void MyPanel::OnBmpButtonToggle(wxCommandEvent& event)
{
FindWindow(ID_BITMAP_BTN)->Enable(!event.IsChecked());
}
void MyPanel::OnChangeColour(wxCommandEvent& WXUNUSED(event))
{
static wxColour s_colOld;
SetThemeEnabled(false);
// test panel colour changing and propagation to the subcontrols
if ( s_colOld.IsOk() )
{
SetBackgroundColour(s_colOld);
s_colOld = wxNullColour;
m_lbSelectThis->SetForegroundColour(wxNullColour);
m_lbSelectThis->SetBackgroundColour(wxNullColour);
}
else
{
s_colOld = wxColour(wxT("red"));
SetBackgroundColour(wxT("white"));
m_lbSelectThis->SetForegroundColour(wxT("white"));
m_lbSelectThis->SetBackgroundColour(wxT("red"));
}
m_lbSelectThis->Refresh();
Refresh();
}
void MyPanel::OnListBox( wxCommandEvent &event )
{
wxListBox *listbox = event.GetId() == ID_LISTBOX ? m_listbox
: m_listboxSorted;
bool deselect = false;
if (listbox->HasFlag(wxLB_MULTIPLE) || listbox->HasFlag(wxLB_EXTENDED))
{
deselect = !event.IsSelection();
if (deselect)
m_text->AppendText( wxT("ListBox deselection event\n") );
}
m_text->AppendText( wxT("ListBox event selection string is: '") );
m_text->AppendText( event.GetString() );
m_text->AppendText( wxT("'\n") );
// can't use GetStringSelection() with multiple selections, there could be
// more than one of them
if ( !listbox->HasFlag(wxLB_MULTIPLE) && !listbox->HasFlag(wxLB_EXTENDED) )
{
m_text->AppendText( wxT("ListBox control selection string is: '") );
m_text->AppendText( listbox->GetStringSelection() );
m_text->AppendText( wxT("'\n") );
}
wxStringClientData *obj = ((wxStringClientData *)event.GetClientObject());
m_text->AppendText( wxT("ListBox event client data string is: '") );
if (obj) // BC++ doesn't like use of '? .. : .. ' in this context
m_text->AppendText( obj->GetData() );
else
m_text->AppendText( wxString(wxT("none")) );
m_text->AppendText( wxT("'\n") );
m_text->AppendText( wxT("ListBox control client data string is: '") );
obj = (wxStringClientData *)listbox->GetClientObject(event.GetInt());
if (obj)
m_text->AppendText( obj->GetData() );
else
m_text->AppendText( wxString(wxT("none")) );
m_text->AppendText( wxT("'\n") );
}
void MyPanel::OnListBoxDoubleClick( wxCommandEvent &event )
{
m_text->AppendText( wxT("ListBox double click string is: ") );
m_text->AppendText( event.GetString() );
m_text->AppendText( wxT("\n") );
}
void MyPanel::OnListBoxButtons( wxCommandEvent &event )
{
switch (event.GetId())
{
case ID_LISTBOX_ENABLE:
{
m_text->AppendText(wxT("Checkbox clicked.\n"));
#if wxUSE_TOOLTIPS
wxCheckBox *cb = (wxCheckBox*)event.GetEventObject();
if (event.GetInt())
cb->SetToolTip( wxT("Click to enable listbox") );
else
cb->SetToolTip( wxT("Click to disable listbox") );
#endif // wxUSE_TOOLTIPS
m_listbox->Enable( event.GetInt() == 0 );
m_lbSelectThis->Enable( event.GetInt() == 0 );
m_lbSelectNum->Enable( event.GetInt() == 0 );
m_listboxSorted->Enable( event.GetInt() == 0 );
FindWindow(ID_CHANGE_COLOUR)->Enable( event.GetInt() == 0 );
break;
}
case ID_LISTBOX_SEL_NUM:
{
if (m_listbox->GetCount() > 2)
m_listbox->SetSelection( 2 );
if (m_listboxSorted->GetCount() > 2)
m_listboxSorted->SetSelection( 2 );
m_lbSelectThis->WarpPointer( 40, 14 );
break;
}
case ID_LISTBOX_SEL_STR:
{
if (m_listbox->FindString(wxT("This")) != wxNOT_FOUND)
m_listbox->SetStringSelection( wxT("This") );
if (m_listboxSorted->FindString(wxT("This")) != wxNOT_FOUND)
m_listboxSorted->SetStringSelection( wxT("This") );
m_lbSelectNum->WarpPointer( 40, 14 );
break;
}
case ID_LISTBOX_CLEAR:
{
m_listbox->Clear();
m_listboxSorted->Clear();
break;
}
case ID_LISTBOX_APPEND:
{
m_listbox->Append( wxT("Hi kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk!") );
m_listboxSorted->Append( wxT("Hi hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!") );
break;
}
case ID_LISTBOX_DELETE:
{
int idx;
idx = m_listbox->GetSelection();
if ( idx != wxNOT_FOUND )
m_listbox->Delete( idx );
idx = m_listboxSorted->GetSelection();
if ( idx != wxNOT_FOUND )
m_listboxSorted->Delete( idx );
break;
}
case ID_LISTBOX_FONT:
{
m_listbox->SetFont( *wxITALIC_FONT );
m_listboxSorted->SetFont( *wxITALIC_FONT );
m_checkbox->SetFont( *wxITALIC_FONT );
break;
}
}
}
#if wxUSE_CHOICE
static wxString GetDataString(wxClientData *data)
{
return data ? static_cast<wxStringClientData *>(data)->GetData()
: wxString("none");
}
void MyPanel::OnChoice( wxCommandEvent &event )
{
wxChoice *choice = event.GetId() == ID_CHOICE ? m_choice
: m_choiceSorted;
const int sel = choice->GetSelection();
wxClientData *dataEvt = event.GetClientObject(),
*dataCtrl = choice->GetClientObject(sel);
wxLogMessage(wxT("EVT_CHOICE: item %d/%d (event/control), ")
wxT("string \"%s\"/\"%s\", ")
wxT("data \"%s\"/\"%s\""),
(int)event.GetInt(),
sel,
event.GetString(),
choice->GetStringSelection(),
GetDataString(dataEvt),
GetDataString(dataCtrl));
}
void MyPanel::OnChoiceButtons( wxCommandEvent &event )
{
switch (event.GetId())
{
case ID_CHOICE_ENABLE:
{
m_choice->Enable( event.GetInt() == 0 );
m_choiceSorted->Enable( event.GetInt() == 0 );
break;
}
case ID_CHOICE_SEL_NUM:
{
m_choice->SetSelection( 2 );
m_choiceSorted->SetSelection( 2 );
break;
}
case ID_CHOICE_SEL_STR:
{
m_choice->SetStringSelection( wxT("This") );
m_choiceSorted->SetStringSelection( wxT("This") );
break;
}
case ID_CHOICE_CLEAR:
{
m_choice->Clear();
m_choiceSorted->Clear();
break;
}
case ID_CHOICE_APPEND:
{
m_choice->Append( wxT("Hi!") );
m_choiceSorted->Append( wxT("Hi!") );
break;
}
case ID_CHOICE_DELETE:
{
int idx = m_choice->GetSelection();
if ( idx != wxNOT_FOUND )
m_choice->Delete( idx );
idx = m_choiceSorted->GetSelection();
if ( idx != wxNOT_FOUND )
m_choiceSorted->Delete( idx );
break;
}
case ID_CHOICE_FONT:
{
m_choice->SetFont( *wxITALIC_FONT );
m_choiceSorted->SetFont( *wxITALIC_FONT );
break;
}
}
}
#endif // wxUSE_CHOICE
void MyPanel::OnCombo( wxCommandEvent &event )
{
if (!m_combo)
return;
wxLogMessage(wxT("EVT_COMBOBOX: item %d/%d (event/control), string \"%s\"/\"%s\""),
(int)event.GetInt(),
m_combo->GetSelection(),
event.GetString().c_str(),
m_combo->GetStringSelection().c_str());
}
void MyPanel::OnComboTextChanged(wxCommandEvent& event)
{
if (m_combo)
{
wxLogMessage(wxT("EVT_TEXT for the combobox: \"%s\" (event) or \"%s\" (control)."),
event.GetString().c_str(),
m_combo->GetValue().c_str());
}
}
void MyPanel::OnComboTextEnter(wxCommandEvent& WXUNUSED(event))
{
if (m_combo)
{
wxLogMessage(wxT("Enter pressed in the combobox: value is '%s'."),
m_combo->GetValue().c_str());
}
}
void MyPanel::OnComboButtons( wxCommandEvent &event )
{
switch (event.GetId())
{
case ID_COMBO_ENABLE:
{
m_combo->Enable( event.GetInt() == 0 );
break;
}
case ID_COMBO_SEL_NUM:
{
m_combo->SetSelection( 2 );
break;
}
case ID_COMBO_SEL_STR:
{
m_combo->SetStringSelection( wxT("This") );
break;
}
case ID_COMBO_CLEAR:
{
m_combo->Clear();
break;
}
case ID_COMBO_APPEND:
{
m_combo->Append( wxT("Hi!") );
break;
}
case ID_COMBO_DELETE:
{
int idx = m_combo->GetSelection();
m_combo->Delete( idx );
break;
}
case ID_COMBO_FONT:
{
m_combo->SetFont( *wxITALIC_FONT );
break;
}
case ID_COMBO_SET_TEXT:
{
m_combo->SetString( 2, wxT("Hi!") );
break;
}
}
}
void MyPanel::OnRadio( wxCommandEvent &event )
{
m_text->AppendText( wxT("RadioBox selection string is: ") );
m_text->AppendText( event.GetString() );
m_text->AppendText( wxT("\n") );
}
void MyPanel::OnRadioButton1( wxCommandEvent & WXUNUSED(event) )
{
wxMessageBox(wxT("First wxRadioButton selected."), wxT("wxControl sample"));
}
void MyPanel::OnRadioButton2( wxCommandEvent & WXUNUSED(event) )
{
m_text->AppendText(wxT("Second wxRadioButton selected.\n"));
}
void MyPanel::OnRadioButtons( wxCommandEvent &event )
{
switch (event.GetId())
{
case ID_RADIOBOX_ENABLE:
m_radio->Enable( event.GetInt() == 0 );
break;
case ID_RADIOBOX_SEL_NUM:
m_radio->SetSelection( 2 );
break;
case ID_RADIOBOX_SEL_STR:
m_radio->SetStringSelection( wxT("This") );
break;
case ID_RADIOBOX_FONT:
m_radio->SetFont( *wxITALIC_FONT );
break;
}
}
void MyPanel::OnSetFont( wxCommandEvent &WXUNUSED(event) )
{
m_fontButton->SetFont( *wxITALIC_FONT );
m_text->SetFont( *wxITALIC_FONT );
}
void MyPanel::OnUpdateLabel( wxCommandEvent &event )
{
m_label->SetLabel(event.GetInt() ? wxT("Very very very very very long text.")
: wxT("Shorter text."));
}
#if wxUSE_SLIDER
void MyPanel::OnSliderUpdate( wxCommandEvent &WXUNUSED(event) )
{
#if wxUSE_GAUGE
m_gauge->SetValue( m_slider->GetValue() );
m_gaugeVert->SetValue( m_slider->GetValue() / 2 );
#endif // wxUSE_GAUGE
}
#endif // wxUSE_SLIDER
#if wxUSE_SPINCTRL
void MyPanel::OnSpinCtrlText(wxCommandEvent& event)
{
if ( m_spinctrl )
{
wxString s;
s.Printf( wxT("Spin ctrl text changed: now %d (from event: %s)\n"),
m_spinctrl->GetValue(), event.GetString().c_str() );
m_text->AppendText(s);
}
}
void MyPanel::OnSpinCtrl(wxSpinEvent& event)
{
if ( m_spinctrl )
{
wxString s;
s.Printf( wxT("Spin ctrl changed: now %d (from event: %d)\n"),
m_spinctrl->GetValue(), event.GetInt() );
m_text->AppendText(s);
}
}
void MyPanel::OnSpinCtrlUp(wxSpinEvent& event)
{
if ( m_spinctrl )
{
m_text->AppendText( wxString::Format(
wxT("Spin up: %d (from event: %d)\n"),
m_spinctrl->GetValue(), event.GetInt() ) );
}
}
void MyPanel::OnSpinCtrlDown(wxSpinEvent& event)
{
if ( m_spinctrl )
{
m_text->AppendText( wxString::Format(
wxT("Spin down: %d (from event: %d)\n"),
m_spinctrl->GetValue(), event.GetInt() ) );
}
}
#endif // wxUSE_SPINCTRL
#if wxUSE_SPINBTN
void MyPanel::OnSpinUp( wxSpinEvent &event )
{
wxString value;
value.Printf( wxT("Spin control up: current = %d\n"),
m_spinbutton->GetValue());
if ( event.GetPosition() > 17 )
{
value += wxT("Preventing the spin button from going above 17.\n");
event.Veto();
}
m_text->AppendText(value);
}
void MyPanel::OnSpinDown( wxSpinEvent &event )
{
wxString value;
value.Printf( wxT("Spin control down: current = %d\n"),
m_spinbutton->GetValue());
if ( event.GetPosition() < -17 )
{
value += wxT("Preventing the spin button from going below -17.\n");
event.Veto();
}
m_text->AppendText(value);
}
void MyPanel::OnSpinUpdate( wxSpinEvent &event )
{
wxString value;
value.Printf( wxT("%d"), event.GetPosition() );
m_spintext->SetValue( value );
value.Printf( wxT("Spin control range: (%d, %d), current = %d\n"),
m_spinbutton->GetMin(), m_spinbutton->GetMax(),
m_spinbutton->GetValue());
m_text->AppendText(value);
}
void MyPanel::OnNewText( wxCommandEvent& /* event */)
{
m_nonWrappingText->SetLabel( wxT("This text is short\nbut still spans\nover three lines.") );
m_wrappingText->SetLabel( wxT("This text is short but will still be wrapped if it is too long.") );
m_wrappingText->GetParent()->Layout();
}
#if wxUSE_PROGRESSDLG
void MyPanel::OnUpdateShowProgress( wxUpdateUIEvent& event )
{
event.Enable( m_spinbutton->GetValue() > 0 );
}
void MyPanel::OnShowProgress( wxCommandEvent& WXUNUSED(event) )
{
int max = m_spinbutton->GetValue();
if ( max <= 0 )
{
wxLogError(wxT("You must set positive range!"));
return;
}
wxProgressDialog dialog(wxT("Progress dialog example"),
wxT("An informative message"),
max, // range
this, // parent
wxPD_CAN_ABORT |
wxPD_AUTO_HIDE |
wxPD_APP_MODAL |
wxPD_ELAPSED_TIME |
wxPD_ESTIMATED_TIME |
wxPD_REMAINING_TIME);
bool cont = true;
for ( int i = 0; i <= max && cont; i++ )
{
wxSleep(1);
if ( i == max )
{
cont = dialog.Update(i, wxT("That's all, folks!"));
}
else if ( i == max / 2 )
{
cont = dialog.Update(i, wxT("Only a half left (very long message)!"));
}
else
{
cont = dialog.Update(i);
}
}
if ( !cont )
{
*m_text << wxT("Progress dialog aborted!\n");
}
else
{
*m_text << wxT("Countdown from ") << max << wxT(" finished.\n");
}
}
#endif // wxUSE_PROGRESSDLG
#endif // wxUSE_SPINBTN
void MyPanel::OnSizerCheck( wxCommandEvent &event)
{
switch (event.GetId ()) {
case ID_SIZER_CHECK1:
m_buttonSizer->Show (m_sizerBtn1, event.IsChecked ());
m_buttonSizer->Layout ();
break;
case ID_SIZER_CHECK2:
m_buttonSizer->Show (m_sizerBtn2, event.IsChecked ());
m_buttonSizer->Layout ();
break;
case ID_SIZER_CHECK3:
m_buttonSizer->Show (m_sizerBtn3, event.IsChecked ());
m_buttonSizer->Layout ();
break;
case ID_SIZER_CHECK4:
m_buttonSizer->Show (m_sizerBtn4, event.IsChecked ());
m_buttonSizer->Layout ();
break;
case ID_SIZER_CHECK14:
m_hsizer->Show (m_buttonSizer, event.IsChecked ());
m_hsizer->Layout ();
break;
case ID_SIZER_CHECKBIG:
m_hsizer->Show (m_bigBtn, event.IsChecked ());
m_hsizer->Layout ();
break;
}
}
MyPanel::~MyPanel()
{
//wxLog::RemoveTraceMask(wxT("focus"));
delete wxLog::SetActiveTarget(m_logTargetOld);
delete m_book->GetImageList();
}
//----------------------------------------------------------------------
// MyFrame
//----------------------------------------------------------------------
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(CONTROLS_QUIT, MyFrame::OnQuit)
EVT_MENU(CONTROLS_ABOUT, MyFrame::OnAbout)
EVT_MENU(CONTROLS_CLEAR_LOG, MyFrame::OnClearLog)
#if wxUSE_TOOLTIPS
EVT_MENU(CONTROLS_SET_TOOLTIP_DELAY, MyFrame::OnSetTooltipDelay)
EVT_MENU(CONTROLS_ENABLE_TOOLTIPS, MyFrame::OnToggleTooltips)
#ifdef __WXMSW__
EVT_MENU(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, MyFrame::OnSetMaxTooltipWidth)
#endif // __WXMSW__
#endif // wxUSE_TOOLTIPS
EVT_MENU(CONTROLS_ENABLE_ALL, MyFrame::OnEnableAll)
EVT_MENU(CONTROLS_HIDE_ALL, MyFrame::OnHideAll)
EVT_MENU(CONTROLS_HIDE_LIST, MyFrame::OnHideList)
EVT_MENU(CONTROLS_CONTEXT_HELP, MyFrame::OnContextHelp)
EVT_ICONIZE(MyFrame::OnIconized)
EVT_MAXIMIZE(MyFrame::OnMaximized)
EVT_SIZE(MyFrame::OnSize)
EVT_MOVE(MyFrame::OnMove)
EVT_IDLE(MyFrame::OnIdle)
END_EVENT_TABLE()
MyFrame::MyFrame(const wxChar *title, int x, int y)
: wxFrame(NULL, wxID_ANY, title, wxPoint(x, y), wxSize(700, 450))
{
SetHelpText( wxT("Controls sample demonstrating various widgets") );
// Give it an icon
// The wxICON() macros loads an icon from a resource under Windows
// and uses an #included XPM image under GTK+ and Motif
SetIcon( wxICON(sample) );
wxMenu *file_menu = new wxMenu;
file_menu->Append(CONTROLS_CLEAR_LOG, wxT("&Clear log\tCtrl-L"));
file_menu->AppendSeparator();
file_menu->Append(CONTROLS_ABOUT, wxT("&About\tF1"));
file_menu->AppendSeparator();
file_menu->Append(CONTROLS_QUIT, wxT("E&xit\tAlt-X"), wxT("Quit controls sample"));
wxMenuBar *menu_bar = new wxMenuBar;
menu_bar->Append(file_menu, wxT("&File"));
#if wxUSE_TOOLTIPS
wxMenu *tooltip_menu = new wxMenu;
tooltip_menu->Append(CONTROLS_SET_TOOLTIP_DELAY, wxT("Set &delay\tCtrl-D"));
tooltip_menu->AppendSeparator();
tooltip_menu->Append(CONTROLS_ENABLE_TOOLTIPS, wxT("&Toggle tooltips\tCtrl-T"),
wxT("enable/disable tooltips"), true);
tooltip_menu->Check(CONTROLS_ENABLE_TOOLTIPS, true);
#ifdef __WXMSW__
tooltip_menu->Append(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, "Set maximal &width");
#endif // __WXMSW__
menu_bar->Append(tooltip_menu, wxT("&Tooltips"));
#endif // wxUSE_TOOLTIPS
wxMenu *panel_menu = new wxMenu;
panel_menu->Append(CONTROLS_ENABLE_ALL, wxT("&Disable all\tCtrl-E"),
wxT("Enable/disable all panel controls"), true);
panel_menu->Append(CONTROLS_HIDE_ALL, wxT("&Hide all\tCtrl-I"),
wxT("Show/hide thoe whole panel controls"), true);
panel_menu->Append(CONTROLS_HIDE_LIST, wxT("Hide &list ctrl\tCtrl-S"),
wxT("Enable/disable all panel controls"), true);
panel_menu->Append(CONTROLS_CONTEXT_HELP, wxT("&Context help...\tCtrl-H"),
wxT("Get context help for a control"));
menu_bar->Append(panel_menu, wxT("&Panel"));
SetMenuBar(menu_bar);
#if wxUSE_STATUSBAR
CreateStatusBar(2);
#endif // wxUSE_STATUSBAR
m_panel = new MyPanel( this, 10, 10, 300, 100 );
}
void MyFrame::OnQuit (wxCommandEvent& WXUNUSED(event) )
{
Close(true);
}
void MyFrame::OnAbout( wxCommandEvent& WXUNUSED(event) )
{
wxBusyCursor bc;
wxMessageDialog dialog(this, wxT("This is a control sample"), wxT("About Controls"), wxOK );
dialog.ShowModal();
}
void MyFrame::OnClearLog(wxCommandEvent& WXUNUSED(event))
{
m_panel->m_text->Clear();
}
#if wxUSE_TOOLTIPS
void MyFrame::OnSetTooltipDelay(wxCommandEvent& WXUNUSED(event))
{
static long s_delay = 5000;
wxString delay;
delay.Printf( wxT("%ld"), s_delay);
delay = wxGetTextFromUser(wxT("Enter delay (in milliseconds)"),
wxT("Set tooltip delay"),
delay,
this);
if ( !delay )
return; // cancelled
wxSscanf(delay, wxT("%ld"), &s_delay);
wxToolTip::SetDelay(s_delay);
wxLogStatus(this, wxT("Tooltip delay set to %ld milliseconds"), s_delay);
}
void MyFrame::OnToggleTooltips(wxCommandEvent& WXUNUSED(event))
{
static bool s_enabled = true;
s_enabled = !s_enabled;
wxToolTip::Enable(s_enabled);
wxLogStatus(this, wxT("Tooltips %sabled"), s_enabled ? wxT("en") : wxT("dis") );
}
#ifdef __WXMSW__
void MyFrame::OnSetMaxTooltipWidth(wxCommandEvent& WXUNUSED(event))
{
static int s_maxWidth = 0;
wxNumberEntryDialog dlg
(
this,
"Change maximal tooltip width",
"&Width in pixels:",
GetTitle(),
s_maxWidth,
-1,
600
);
if ( dlg.ShowModal() == wxID_CANCEL )
return;
s_maxWidth = dlg.GetValue();
wxToolTip::SetMaxWidth(s_maxWidth);
// we need to set the tooltip again to test the new width
m_panel->SetAllToolTips();
}
#endif // __WXMSW__
#endif // wxUSE_TOOLTIPS
void MyFrame::OnEnableAll(wxCommandEvent& WXUNUSED(event))
{
static bool s_enable = true;
s_enable = !s_enable;
m_panel->Enable(s_enable);
static bool s_enableCheckbox = true;
if ( !s_enable )
{
// this is a test for correct behaviour of either enabling or disabling
// a child when its parent is disabled: the checkbox should have the
// correct state when the parent is enabled back
m_panel->m_checkbox->Enable(s_enableCheckbox);
s_enableCheckbox = !s_enableCheckbox;
}
}
void MyFrame::OnHideAll(wxCommandEvent& WXUNUSED(event))
{
static bool s_show = true;
s_show = !s_show;
m_panel->Show(s_show);
}
void MyFrame::OnHideList(wxCommandEvent& WXUNUSED(event))
{
static bool s_show = true;
s_show = !s_show;
m_panel->m_listbox->Show(s_show);
}
void MyFrame::OnContextHelp(wxCommandEvent& WXUNUSED(event))
{
// starts a local event loop
wxContextHelp chelp(this);
}
void MyFrame::OnMove( wxMoveEvent& event )
{
#if wxUSE_STATUSBAR
UpdateStatusBar(event.GetPosition(), GetSize());
#endif // wxUSE_STATUSBAR
event.Skip();
}
void MyFrame::OnIconized( wxIconizeEvent& event )
{
wxLogMessage(wxT("Frame %s"), event.IsIconized() ? wxT("iconized")
: wxT("restored"));
event.Skip();
}
void MyFrame::OnMaximized( wxMaximizeEvent& WXUNUSED(event) )
{
wxLogMessage(wxT("Frame maximized"));
}
void MyFrame::OnSize( wxSizeEvent& event )
{
#if wxUSE_STATUSBAR
UpdateStatusBar(GetPosition(), event.GetSize());
#endif // wxUSE_STATUSBAR
event.Skip();
}
void MyFrame::OnIdle( wxIdleEvent& WXUNUSED(event) )
{
// track the window which has the focus in the status bar
static wxWindow *s_windowFocus = NULL;
wxWindow *focus = wxWindow::FindFocus();
if ( focus != s_windowFocus )
{
s_windowFocus = focus;
wxString msg;
if ( focus )
{
msg.Printf(
"Focus: %s"
#ifdef __WXMSW__
", HWND = %08x"
#endif
, s_windowFocus->GetName().c_str()
#ifdef __WXMSW__
, (unsigned int) s_windowFocus->GetHWND()
#endif
);
}
else
{
msg = wxT("No focus");
}
#if wxUSE_STATUSBAR
SetStatusText(msg);
#endif // wxUSE_STATUSBAR
}
}
void MyComboBox::OnChar(wxKeyEvent& event)
{
wxLogMessage(wxT("MyComboBox::OnChar"));
if ( event.GetKeyCode() == 'w' )
{
wxLogMessage(wxT("MyComboBox: 'w' will be ignored."));
}
else
{
event.Skip();
}
}
void MyComboBox::OnKeyDown(wxKeyEvent& event)
{
wxLogMessage(wxT("MyComboBox::OnKeyDown"));
if ( event.GetKeyCode() == 'w' )
{
wxLogMessage(wxT("MyComboBox: 'w' will be ignored."));
}
else
{
event.Skip();
}
}
void MyComboBox::OnKeyUp(wxKeyEvent& event)
{
wxLogMessage(wxT("MyComboBox::OnKeyUp"));
event.Skip();
}
static void SetListboxClientData(const wxChar *name, wxListBox *control)
{
size_t count = control->GetCount();
for ( size_t n = 0; n < count; n++ )
{
wxString s;
s.Printf(wxT("%s client data for '%s'"),
name, control->GetString(n).c_str());
control->SetClientObject(n, new wxStringClientData(s));
}
}
#if wxUSE_CHOICE
static void SetChoiceClientData(const wxChar *name, wxChoice *control)
{
size_t count = control->GetCount();
for ( size_t n = 0; n < count; n++ )
{
wxString s;
s.Printf(wxT("%s client data for '%s'"),
name, control->GetString(n).c_str());
control->SetClientObject(n, new wxStringClientData(s));
}
}
#endif // wxUSE_CHOICE
| enachb/freetel-code | src/wxWidgets-2.9.4/samples/controls/controls.cpp | C++ | lgpl-2.1 | 68,101 |
//
// CodeAnalysisRunner.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
//
// 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.
//#define PROFILE
using System;
using System.Linq;
using MonoDevelop.AnalysisCore;
using System.Collections.Generic;
using MonoDevelop.AnalysisCore.Fixes;
using ICSharpCode.NRefactory.CSharp;
using MonoDevelop.Core;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Refactoring;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using MonoDevelop.SourceEditor.QuickTasks;
using ICSharpCode.NRefactory.TypeSystem;
using MonoDevelop.CodeIssues;
using Mono.TextEditor;
using ICSharpCode.NRefactory.Refactoring;
using MonoDevelop.CodeActions;
using System.Diagnostics;
using MonoDevelop.Ide.TypeSystem;
namespace MonoDevelop.CodeIssues
{
public static class CodeAnalysisRunner
{
static IEnumerable<BaseCodeIssueProvider> EnumerateProvider (CodeIssueProvider p)
{
if (p.HasSubIssues)
return p.SubIssues;
return new BaseCodeIssueProvider[] { p };
}
public static IEnumerable<Result> Check (Document input, ParsedDocument parsedDocument, CancellationToken cancellationToken)
{
if (!QuickTaskStrip.EnableFancyFeatures || input.Project == null || !input.IsCompileableInProject)
return Enumerable.Empty<Result> ();
#if PROFILE
var runList = new List<Tuple<long, string>> ();
#endif
var editor = input.Editor;
if (editor == null)
return Enumerable.Empty<Result> ();
var loc = editor.Caret.Location;
var result = new BlockingCollection<Result> ();
var codeIssueProvider = RefactoringService.GetInspectors (editor.Document.MimeType).ToArray ();
var context = parsedDocument.CreateRefactoringContext != null ?
parsedDocument.CreateRefactoringContext (input, cancellationToken) : null;
Parallel.ForEach (codeIssueProvider, (parentProvider) => {
try {
#if PROFILE
var clock = new Stopwatch();
clock.Start ();
#endif
foreach (var provider in EnumerateProvider (parentProvider)) {
cancellationToken.ThrowIfCancellationRequested ();
var severity = provider.GetSeverity ();
if (severity == Severity.None || !provider.GetIsEnabled ())
continue;
foreach (var r in provider.GetIssues (context, cancellationToken)) {
cancellationToken.ThrowIfCancellationRequested ();
var fixes = r.Actions == null ? new List<GenericFix> () : new List<GenericFix> (r.Actions.Where (a => a != null).Select (a => {
Action batchAction = null;
if (a.SupportsBatchRunning)
batchAction = () => a.BatchRun (input, loc);
return new GenericFix (
a.Title,
() => {
using (var script = context.CreateScript ()) {
a.Run (context, script);
}
},
batchAction) {
DocumentRegion = new DocumentRegion (r.Region.Begin, r.Region.End),
IdString = a.IdString
};
}));
result.Add (new InspectorResults (
provider,
r.Region,
r.Description,
severity,
r.IssueMarker,
fixes.ToArray ()
));
}
}
#if PROFILE
clock.Stop ();
lock (runList) {
runList.Add (Tuple.Create (clock.ElapsedMilliseconds, parentProvider.Title));
}
#endif
} catch (OperationCanceledException) {
//ignore
} catch (Exception e) {
LoggingService.LogError ("CodeAnalysis: Got exception in inspector '" + parentProvider + "'", e);
}
});
#if PROFILE
runList.Sort ();
foreach (var item in runList) {
Console.WriteLine (item.Item1 +"ms\t: " + item.Item2);
}
#endif
return result;
}
}
}
| mono/linux-packaging-monodevelop | src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs | C# | lgpl-2.1 | 4,774 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** 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 The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qtoptionspage.h"
#include "qtconfigwidget.h"
#include "ui_showbuildlog.h"
#include "ui_qtversionmanager.h"
#include "ui_qtversioninfo.h"
#include "ui_debugginghelper.h"
#include "qtsupportconstants.h"
#include "qtversionmanager.h"
#include "qtversionfactory.h"
#include "qmldumptool.h"
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/variablechooser.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <utils/runextensions.h>
#include <utils/algorithm.h>
#include <QDir>
#include <QMessageBox>
#include <QFileDialog>
#include <QTextBrowser>
#include <QDesktopServices>
using namespace ProjectExplorer;
using namespace Utils;
namespace QtSupport {
namespace Internal {
enum ModelRoles { VersionIdRole = Qt::UserRole, ToolChainIdRole, BuildLogRole, BuildRunningRole};
///
// QtOptionsPage
///
QtOptionsPage::QtOptionsPage()
: m_widget(0)
{
setId(Constants::QTVERSION_SETTINGS_PAGE_ID);
setDisplayName(QCoreApplication::translate("Qt4ProjectManager", Constants::QTVERSION_SETTINGS_PAGE_NAME));
setCategory(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
}
QWidget *QtOptionsPage::widget()
{
if (!m_widget)
m_widget = new QtOptionsPageWidget;
return m_widget;
}
void QtOptionsPage::apply()
{
if (!m_widget) // page was never shown
return;
m_widget->apply();
}
void QtOptionsPage::finish()
{
delete m_widget;
}
//-----------------------------------------------------
QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent)
: QWidget(parent)
, m_specifyNameString(tr("<specify a name>"))
, m_ui(new Internal::Ui::QtVersionManager())
, m_versionUi(new Internal::Ui::QtVersionInfo())
, m_debuggingHelperUi(new Internal::Ui::DebuggingHelper())
, m_infoBrowser(new QTextBrowser)
, m_invalidVersionIcon(QLatin1String(Core::Constants::ICON_ERROR))
, m_warningVersionIcon(QLatin1String(Core::Constants::ICON_WARNING))
, m_configurationWidget(0)
, m_autoItem(0)
, m_manualItem(0)
{
QWidget *versionInfoWidget = new QWidget();
m_versionUi->setupUi(versionInfoWidget);
m_versionUi->editPathPushButton->setText(PathChooser::browseButtonLabel());
QWidget *debuggingHelperDetailsWidget = new QWidget();
m_debuggingHelperUi->setupUi(debuggingHelperDetailsWidget);
m_ui->setupUi(this);
m_infoBrowser->setOpenLinks(false);
m_infoBrowser->setTextInteractionFlags(Qt::TextBrowserInteraction);
connect(m_infoBrowser, &QTextBrowser::anchorClicked,
this, &QtOptionsPageWidget::infoAnchorClicked);
m_ui->infoWidget->setWidget(m_infoBrowser);
connect(m_ui->infoWidget, &DetailsWidget::expanded,
this, &QtOptionsPageWidget::setInfoWidgetVisibility);
m_ui->versionInfoWidget->setWidget(versionInfoWidget);
m_ui->versionInfoWidget->setState(DetailsWidget::NoSummary);
m_ui->debuggingHelperWidget->setWidget(debuggingHelperDetailsWidget);
connect(m_ui->debuggingHelperWidget, &DetailsWidget::expanded,
this, &QtOptionsPageWidget::setInfoWidgetVisibility);
// setup parent items for auto-detected and manual versions
m_ui->qtdirList->header()->setStretchLastSection(false);
m_ui->qtdirList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
m_ui->qtdirList->header()->setSectionResizeMode(1, QHeaderView::Stretch);
m_ui->qtdirList->setTextElideMode(Qt::ElideNone);
m_autoItem = new QTreeWidgetItem(m_ui->qtdirList);
m_autoItem->setText(0, tr("Auto-detected"));
m_autoItem->setFirstColumnSpanned(true);
m_autoItem->setFlags(Qt::ItemIsEnabled);
m_manualItem = new QTreeWidgetItem(m_ui->qtdirList);
m_manualItem->setText(0, tr("Manual"));
m_manualItem->setFirstColumnSpanned(true);
m_manualItem->setFlags(Qt::ItemIsEnabled);
QList<int> additions = transform(QtVersionManager::versions(), &BaseQtVersion::uniqueId);
updateQtVersions(additions, QList<int>(), QList<int>());
m_ui->qtdirList->expandAll();
connect(m_versionUi->nameEdit, &QLineEdit::textEdited,
this, &QtOptionsPageWidget::updateCurrentQtName);
connect(m_versionUi->editPathPushButton, &QAbstractButton::clicked,
this, &QtOptionsPageWidget::editPath);
connect(m_ui->addButton, &QAbstractButton::clicked,
this, &QtOptionsPageWidget::addQtDir);
connect(m_ui->delButton, &QAbstractButton::clicked,
this, &QtOptionsPageWidget::removeQtDir);
connect(m_ui->qtdirList, &QTreeWidget::currentItemChanged,
this, &QtOptionsPageWidget::versionChanged);
connect(m_debuggingHelperUi->rebuildButton, &QAbstractButton::clicked,
this, [this]() { buildDebuggingHelper(); });
connect(m_debuggingHelperUi->qmlDumpBuildButton, &QAbstractButton::clicked,
this, &QtOptionsPageWidget::buildQmlDump);
connect(m_debuggingHelperUi->showLogButton, &QAbstractButton::clicked,
this, &QtOptionsPageWidget::slotShowDebuggingBuildLog);
connect(m_debuggingHelperUi->toolChainComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
this, &QtOptionsPageWidget::selectedToolChainChanged);
connect(m_ui->cleanUpButton, &QAbstractButton::clicked,
this, &QtOptionsPageWidget::cleanUpQtVersions);
userChangedCurrentVersion();
updateCleanUpButton();
connect(QtVersionManager::instance(), &QtVersionManager::dumpUpdatedFor,
this, &QtOptionsPageWidget::qtVersionsDumpUpdated);
connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged,
this, &QtOptionsPageWidget::updateQtVersions);
connect(ProjectExplorer::ToolChainManager::instance(), &ToolChainManager::toolChainsChanged,
this, &QtOptionsPageWidget::toolChainsUpdated);
auto chooser = new Core::VariableChooser(this);
chooser->addSupportedWidget(m_versionUi->nameEdit, "Qt:Name");
chooser->addMacroExpanderProvider(
[this]() -> Utils::MacroExpander * {
BaseQtVersion *version = currentVersion();
return version ? version->macroExpander() : 0;
});
}
int QtOptionsPageWidget::currentIndex() const
{
if (QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem())
return indexForTreeItem(currentItem);
return -1;
}
BaseQtVersion *QtOptionsPageWidget::currentVersion() const
{
const int currentItemIndex = currentIndex();
if (currentItemIndex >= 0 && currentItemIndex < m_versions.size())
return m_versions.at(currentItemIndex);
return 0;
}
static inline int findVersionById(const QList<BaseQtVersion *> &l, int id)
{
const int size = l.size();
for (int i = 0; i < size; i++)
if (l.at(i)->uniqueId() == id)
return i;
return -1;
}
// Update with results of terminated helper build
void QtOptionsPageWidget::debuggingHelperBuildFinished(int qtVersionId, const QString &output, DebuggingHelperBuildTask::Tools tools)
{
const int index = findVersionById(m_versions, qtVersionId);
if (index == -1)
return; // Oops, somebody managed to delete the version
BaseQtVersion *version = m_versions.at(index);
// Update item view
QTreeWidgetItem *item = treeItemForIndex(index);
QTC_ASSERT(item, return);
DebuggingHelperBuildTask::Tools buildFlags
= item->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>();
buildFlags &= ~tools;
item->setData(0, BuildRunningRole, QVariant::fromValue(buildFlags));
item->setData(0, BuildLogRole, output);
bool success = true;
if (tools & DebuggingHelperBuildTask::QmlDump)
success &= version->hasQmlDump();
if (!success)
showDebuggingBuildLog(item);
updateDebuggingHelperUi();
}
void QtOptionsPageWidget::cleanUpQtVersions()
{
QStringList toRemove;
foreach (const BaseQtVersion *v, m_versions) {
if (!v->isValid())
toRemove.append(v->displayName());
}
if (toRemove.isEmpty())
return;
if (QMessageBox::warning(0, tr("Remove Invalid Qt Versions"),
tr("Do you want to remove all invalid Qt Versions?<br>"
"<ul><li>%1</li></ul><br>"
"will be removed.").arg(toRemove.join(QLatin1String("</li><li>"))),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
return;
for (int i = m_versions.count() - 1; i >= 0; --i) {
if (!m_versions.at(i)->isValid()) {
QTreeWidgetItem *item = treeItemForIndex(i);
delete item;
delete m_versions.at(i);
m_versions.removeAt(i);
}
}
updateCleanUpButton();
}
void QtOptionsPageWidget::toolChainsUpdated()
{
for (int i = 0; i < m_versions.count(); ++i) {
QTreeWidgetItem *item = treeItemForIndex(i);
if (item == m_ui->qtdirList->currentItem()) {
updateDescriptionLabel();
updateDebuggingHelperUi();
} else {
updateVersionItem(m_versions.at(i));
}
}
}
void QtOptionsPageWidget::selectedToolChainChanged(int comboIndex)
{
const int index = currentIndex();
if (index < 0)
return;
QTreeWidgetItem *item = treeItemForIndex(index);
QTC_ASSERT(item, return);
QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData(comboIndex).toString();
item->setData(0, ToolChainIdRole, toolChainId);
}
void QtOptionsPageWidget::qtVersionsDumpUpdated(const FileName &qmakeCommand)
{
foreach (BaseQtVersion *version, m_versions) {
if (version->qmakeCommand() == qmakeCommand)
version->recheckDumper();
}
if (currentVersion()
&& currentVersion()->qmakeCommand() == qmakeCommand) {
updateWidgets();
updateDescriptionLabel();
updateDebuggingHelperUi();
}
}
void QtOptionsPageWidget::setInfoWidgetVisibility()
{
m_ui->versionInfoWidget->setVisible((m_ui->infoWidget->state() == DetailsWidget::Collapsed)
&& (m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed));
m_ui->infoWidget->setVisible(m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed);
m_ui->debuggingHelperWidget->setVisible(m_ui->infoWidget->state() == DetailsWidget::Collapsed);
}
void QtOptionsPageWidget::infoAnchorClicked(const QUrl &url)
{
QDesktopServices::openUrl(url);
}
QtOptionsPageWidget::ValidityInfo QtOptionsPageWidget::validInformation(const BaseQtVersion *version)
{
ValidityInfo info;
info.icon = m_validVersionIcon;
if (!version)
return info;
info.description = tr("Qt version %1 for %2").arg(version->qtVersionString(), version->description());
if (!version->isValid()) {
info.icon = m_invalidVersionIcon;
info.message = version->invalidReason();
return info;
}
// Do we have tool chain issues?
QStringList missingToolChains;
int abiCount = 0;
foreach (const Abi &abi, version->qtAbis()) {
if (ToolChainManager::findToolChains(abi).isEmpty())
missingToolChains.append(abi.toString());
++abiCount;
}
bool useable = true;
QStringList warnings;
if (!isNameUnique(version))
warnings << tr("Display Name is not unique.");
if (!missingToolChains.isEmpty()) {
if (missingToolChains.count() == abiCount) {
// Yes, this Qt version can't be used at all!
info.message = tr("No compiler can produce code for this Qt version. Please define one or more compilers.");
info.icon = m_invalidVersionIcon;
useable = false;
} else {
// Yes, some ABIs are unsupported
warnings << tr("Not all possible target environments can be supported due to missing compilers.");
info.toolTip = tr("The following ABIs are currently not supported:<ul><li>%1</li></ul>")
.arg(missingToolChains.join(QLatin1String("</li><li>")));
info.icon = m_warningVersionIcon;
}
}
if (useable) {
warnings += version->warningReason();
if (!warnings.isEmpty()) {
info.message = warnings.join(QLatin1Char('\n'));
info.icon = m_warningVersionIcon;
}
}
return info;
}
QList<ToolChain*> QtOptionsPageWidget::toolChains(const BaseQtVersion *version)
{
QList<ToolChain*> toolChains;
if (!version)
return toolChains;
QSet<QString> ids;
foreach (const Abi &a, version->qtAbis()) {
foreach (ToolChain *tc, ToolChainManager::findToolChains(a)) {
if (ids.contains(tc->id()))
continue;
ids.insert(tc->id());
toolChains.append(tc);
}
}
return toolChains;
}
QString QtOptionsPageWidget::defaultToolChainId(const BaseQtVersion *version)
{
QList<ToolChain*> possibleToolChains = toolChains(version);
if (!possibleToolChains.isEmpty())
return possibleToolChains.first()->id();
return QString();
}
bool QtOptionsPageWidget::isNameUnique(const BaseQtVersion *version)
{
const QString name = version->displayName().trimmed();
foreach (const BaseQtVersion *i, m_versions) {
if (i == version)
continue;
if (i->displayName().trimmed() == name)
return false;
}
return true;
}
void QtOptionsPageWidget::updateVersionItem(BaseQtVersion *version)
{
const ValidityInfo info = validInformation(version);
QTreeWidgetItem *item = treeItemForIndex(m_versions.indexOf(version));
item->setText(0, version->displayName());
item->setText(1, version->qmakeCommand().toUserOutput());
item->setIcon(0, info.icon);
}
void QtOptionsPageWidget::buildDebuggingHelper(DebuggingHelperBuildTask::Tools tools)
{
const int index = currentIndex();
if (index < 0)
return;
// remove tools that cannot be build
tools &= DebuggingHelperBuildTask::availableTools(currentVersion());
QTreeWidgetItem *item = treeItemForIndex(index);
QTC_ASSERT(item, return);
DebuggingHelperBuildTask::Tools buildFlags
= item->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>();
buildFlags |= tools;
item->setData(0, BuildRunningRole, QVariant::fromValue(buildFlags));
BaseQtVersion *version = m_versions.at(index);
if (!version)
return;
updateDebuggingHelperUi();
// Run a debugging helper build task in the background.
QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData(
m_debuggingHelperUi->toolChainComboBox->currentIndex()).toString();
ToolChain *toolChain = ToolChainManager::findToolChain(toolChainId);
if (!toolChain)
return;
DebuggingHelperBuildTask *buildTask = new DebuggingHelperBuildTask(version, toolChain, tools);
// Don't open General Messages pane with errors
buildTask->showOutputOnError(false);
connect(buildTask, SIGNAL(finished(int,QString,DebuggingHelperBuildTask::Tools)),
this, SLOT(debuggingHelperBuildFinished(int,QString,DebuggingHelperBuildTask::Tools)),
Qt::QueuedConnection);
QFuture<void> task = QtConcurrent::run(&DebuggingHelperBuildTask::run, buildTask);
const QString taskName = tr("Building Helpers");
Core::ProgressManager::addTask(task, taskName, "QmakeProjectManager::BuildHelpers");
}
void QtOptionsPageWidget::buildQmlDump()
{
buildDebuggingHelper(DebuggingHelperBuildTask::QmlDump);
}
// Non-modal dialog
class BuildLogDialog : public QDialog {
public:
explicit BuildLogDialog(QWidget *parent = 0);
void setText(const QString &text);
private:
Ui_ShowBuildLog m_ui;
};
BuildLogDialog::BuildLogDialog(QWidget *parent) : QDialog(parent)
{
m_ui.setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, true);
}
void BuildLogDialog::setText(const QString &text)
{
m_ui.log->setPlainText(text); // Show and scroll to bottom
m_ui.log->moveCursor(QTextCursor::End);
m_ui.log->ensureCursorVisible();
}
void QtOptionsPageWidget::slotShowDebuggingBuildLog()
{
if (const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem())
showDebuggingBuildLog(currentItem);
}
void QtOptionsPageWidget::showDebuggingBuildLog(const QTreeWidgetItem *currentItem)
{
const int currentItemIndex = indexForTreeItem(currentItem);
if (currentItemIndex < 0)
return;
BuildLogDialog *dialog = new BuildLogDialog(this->window());
dialog->setWindowTitle(tr("Debugging Helper Build Log for \"%1\"").arg(currentItem->text(0)));
dialog->setText(currentItem->data(0, BuildLogRole).toString());
dialog->show();
}
void QtOptionsPageWidget::updateQtVersions(const QList<int> &additions, const QList<int> &removals,
const QList<int> &changes)
{
QList<QTreeWidgetItem *> toRemove;
QList<int> toAdd = additions;
// Generate list of all existing items:
QList<QTreeWidgetItem *> itemList;
for (int i = 0; i < m_autoItem->childCount(); ++i)
itemList.append(m_autoItem->child(i));
for (int i = 0; i < m_manualItem->childCount(); ++i)
itemList.append(m_manualItem->child(i));
// Find existing items to remove/change:
foreach (QTreeWidgetItem *item, itemList) {
int id = item->data(0, VersionIdRole).toInt();
if (removals.contains(id)) {
toRemove.append(item);
continue;
}
if (changes.contains(id)) {
toAdd.append(id);
toRemove.append(item);
continue;
}
}
// Remove changed/removed items:
foreach (QTreeWidgetItem *item, toRemove) {
int index = indexForTreeItem(item);
delete m_versions.at(index);
m_versions.removeAt(index);
delete item;
}
// Add changed/added items:
foreach (int a, toAdd) {
BaseQtVersion *version = QtVersionManager::version(a)->clone();
m_versions.append(version);
QTreeWidgetItem *item = new QTreeWidgetItem;
item->setData(0, VersionIdRole, version->uniqueId());
item->setData(0, ToolChainIdRole, defaultToolChainId(version));
// Insert in the right place:
QTreeWidgetItem *parent = version->isAutodetected()? m_autoItem : m_manualItem;
for (int i = 0; i < parent->childCount(); ++i) {
BaseQtVersion *currentVersion = m_versions.at(indexForTreeItem(parent->child(i)));
if (currentVersion->qtVersion() > version->qtVersion())
continue;
parent->insertChild(i, item);
parent = 0;
break;
}
if (parent)
parent->addChild(item);
}
// Only set the icon after all versions are there to make sure all names are known:
foreach (BaseQtVersion *i, m_versions)
updateVersionItem(i);
}
QtOptionsPageWidget::~QtOptionsPageWidget()
{
delete m_ui;
delete m_versionUi;
delete m_debuggingHelperUi;
delete m_configurationWidget;
qDeleteAll(m_versions);
}
void QtOptionsPageWidget::addQtDir()
{
FileName qtVersion = FileName::fromString(
QFileDialog::getOpenFileName(this,
tr("Select a qmake Executable"),
QString(),
BuildableHelperLibrary::filterForQmakeFileDialog(),
0,
QFileDialog::DontResolveSymlinks));
if (qtVersion.isNull())
return;
QFileInfo fi(qtVersion.toString());
// should add all qt versions here ?
if (BuildableHelperLibrary::isQtChooser(fi))
qtVersion = FileName::fromString(BuildableHelperLibrary::qtChooserToQmakePath(fi.symLinkTarget()));
BaseQtVersion *version = Utils::findOrDefault(m_versions,
Utils::equal(&BaseQtVersion::qmakeCommand, qtVersion));
if (version) {
// Already exist
QMessageBox::warning(this, tr("Qt Version Already Known"),
tr("This Qt version was already registered as \"%1\".")
.arg(version->displayName()));
return;
}
QString error;
version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion, false, QString(), &error);
if (version) {
m_versions.append(version);
QTreeWidgetItem *item = new QTreeWidgetItem(m_ui->qtdirList->topLevelItem(1));
item->setText(0, version->displayName());
item->setText(1, version->qmakeCommand().toUserOutput());
item->setData(0, VersionIdRole, version->uniqueId());
item->setData(0, ToolChainIdRole, defaultToolChainId(version));
item->setIcon(0, version->isValid()? m_validVersionIcon : m_invalidVersionIcon);
m_ui->qtdirList->setCurrentItem(item); // should update the rest of the ui
m_versionUi->nameEdit->setFocus();
m_versionUi->nameEdit->selectAll();
} else {
QMessageBox::warning(this, tr("Qmake Not Executable"),
tr("The qmake executable %1 could not be added: %2").arg(qtVersion.toUserOutput()).arg(error));
return;
}
updateCleanUpButton();
}
void QtOptionsPageWidget::removeQtDir()
{
QTreeWidgetItem *item = m_ui->qtdirList->currentItem();
int index = indexForTreeItem(item);
if (index < 0)
return;
delete item;
BaseQtVersion *version = m_versions.at(index);
m_versions.removeAt(index);
delete version;
updateCleanUpButton();
}
void QtOptionsPageWidget::editPath()
{
BaseQtVersion *current = currentVersion();
QString dir = currentVersion()->qmakeCommand().toFileInfo().absolutePath();
FileName qtVersion = FileName::fromString(
QFileDialog::getOpenFileName(this,
tr("Select a qmake Executable"),
dir,
BuildableHelperLibrary::filterForQmakeFileDialog(),
0,
QFileDialog::DontResolveSymlinks));
if (qtVersion.isNull())
return;
BaseQtVersion *version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion);
if (!version)
return;
// Same type? then replace!
if (current->type() != version->type()) {
// not the same type, error out
QMessageBox::critical(this, tr("Incompatible Qt Versions"),
tr("The Qt version selected must match the device type."),
QMessageBox::Ok);
delete version;
return;
}
// same type, replace
version->setId(current->uniqueId());
if (current->unexpandedDisplayName() != current->defaultUnexpandedDisplayName(current->qmakeCommand()))
version->setUnexpandedDisplayName(current->displayName());
m_versions.replace(m_versions.indexOf(current), version);
delete current;
// Update ui
userChangedCurrentVersion();
QTreeWidgetItem *item = m_ui->qtdirList->currentItem();
item->setText(0, version->displayName());
item->setText(1, version->qmakeCommand().toUserOutput());
item->setData(0, VersionIdRole, version->uniqueId());
item->setData(0, ToolChainIdRole, defaultToolChainId(version));
item->setIcon(0, version->isValid()? m_validVersionIcon : m_invalidVersionIcon);
}
void QtOptionsPageWidget::updateDebuggingHelperUi()
{
BaseQtVersion *version = currentVersion();
const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem();
QList<ToolChain*> toolchains = toolChains(currentVersion());
if (!version || !version->isValid() || toolchains.isEmpty()) {
m_ui->debuggingHelperWidget->setVisible(false);
} else {
const DebuggingHelperBuildTask::Tools availableTools = DebuggingHelperBuildTask::availableTools(version);
const bool canBuildQmlDumper = availableTools & DebuggingHelperBuildTask::QmlDump;
const bool hasQmlDumper = version->hasQmlDump();
const bool needsQmlDumper = version->needsQmlDump();
bool isBuildingQmlDumper = false;
if (currentItem) {
DebuggingHelperBuildTask::Tools buildingTools
= currentItem->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>();
isBuildingQmlDumper = buildingTools & DebuggingHelperBuildTask::QmlDump;
}
// get names of tools from labels
QStringList helperNames;
const QChar colon = QLatin1Char(':');
if (hasQmlDumper)
helperNames << m_debuggingHelperUi->qmlDumpLabel->text().remove(colon);
QString status;
if (helperNames.isEmpty()) {
status = tr("Helpers: None available");
} else {
//: %1 is list of tool names.
status = tr("Helpers: %1.").arg(helperNames.join(QLatin1String(", ")));
}
m_ui->debuggingHelperWidget->setSummaryText(status);
QString qmlDumpStatusText, qmlDumpStatusToolTip;
Qt::TextInteractionFlags qmlDumpStatusTextFlags = Qt::NoTextInteraction;
if (hasQmlDumper) {
qmlDumpStatusText = QDir::toNativeSeparators(version->qmlDumpTool(false));
const QString debugQmlDumpPath = QDir::toNativeSeparators(version->qmlDumpTool(true));
if (qmlDumpStatusText != debugQmlDumpPath) {
if (!qmlDumpStatusText.isEmpty()
&& !debugQmlDumpPath.isEmpty())
qmlDumpStatusText += QLatin1String("\n");
qmlDumpStatusText += debugQmlDumpPath;
}
qmlDumpStatusTextFlags = Qt::TextSelectableByMouse;
} else {
if (!needsQmlDumper) {
qmlDumpStatusText = tr("<i>Not needed.</i>");
} else if (canBuildQmlDumper) {
qmlDumpStatusText = tr("<i>Not yet built.</i>");
} else {
qmlDumpStatusText = tr("<i>Cannot be compiled.</i>");
QmlDumpTool::canBuild(version, &qmlDumpStatusToolTip);
}
}
m_debuggingHelperUi->qmlDumpStatus->setText(qmlDumpStatusText);
m_debuggingHelperUi->qmlDumpStatus->setTextInteractionFlags(qmlDumpStatusTextFlags);
m_debuggingHelperUi->qmlDumpStatus->setToolTip(qmlDumpStatusToolTip);
m_debuggingHelperUi->qmlDumpBuildButton->setEnabled(canBuildQmlDumper & !isBuildingQmlDumper);
QList<ToolChain*> toolchains = toolChains(currentVersion());
QString selectedToolChainId = currentItem->data(0, ToolChainIdRole).toString();
m_debuggingHelperUi->toolChainComboBox->clear();
for (int i = 0; i < toolchains.size(); ++i) {
if (!toolchains.at(i)->isValid())
continue;
if (i >= m_debuggingHelperUi->toolChainComboBox->count()) {
m_debuggingHelperUi->toolChainComboBox->insertItem(i, toolchains.at(i)->displayName(),
toolchains.at(i)->id());
}
if (toolchains.at(i)->id() == selectedToolChainId)
m_debuggingHelperUi->toolChainComboBox->setCurrentIndex(i);
}
const bool hasLog = currentItem && !currentItem->data(0, BuildLogRole).toString().isEmpty();
m_debuggingHelperUi->showLogButton->setEnabled(hasLog);
const bool canBuild = canBuildQmlDumper;
const bool isBuilding = isBuildingQmlDumper;
m_debuggingHelperUi->rebuildButton->setEnabled(canBuild && !isBuilding);
m_debuggingHelperUi->toolChainComboBox->setEnabled(canBuild && !isBuilding);
setInfoWidgetVisibility();
}
}
// To be called if a Qt version was removed or added
void QtOptionsPageWidget::updateCleanUpButton()
{
bool hasInvalidVersion = false;
for (int i = 0; i < m_versions.count(); ++i) {
if (!m_versions.at(i)->isValid()) {
hasInvalidVersion = true;
break;
}
}
m_ui->cleanUpButton->setEnabled(hasInvalidVersion);
}
void QtOptionsPageWidget::userChangedCurrentVersion()
{
updateWidgets();
updateDescriptionLabel();
updateDebuggingHelperUi();
}
void QtOptionsPageWidget::qtVersionChanged()
{
updateDescriptionLabel();
updateDebuggingHelperUi();
}
void QtOptionsPageWidget::updateDescriptionLabel()
{
QTreeWidgetItem *item = m_ui->qtdirList->currentItem();
const BaseQtVersion *version = currentVersion();
const ValidityInfo info = validInformation(version);
if (info.message.isEmpty()) {
m_versionUi->errorLabel->setVisible(false);
} else {
m_versionUi->errorLabel->setVisible(true);
m_versionUi->errorLabel->setText(info.message);
m_versionUi->errorLabel->setToolTip(info.toolTip);
}
m_ui->infoWidget->setSummaryText(info.description);
if (item)
item->setIcon(0, info.icon);
if (version) {
m_infoBrowser->setHtml(version->toHtml(true));
setInfoWidgetVisibility();
} else {
m_infoBrowser->clear();
m_ui->versionInfoWidget->setVisible(false);
m_ui->infoWidget->setVisible(false);
m_ui->debuggingHelperWidget->setVisible(false);
}
}
int QtOptionsPageWidget::indexForTreeItem(const QTreeWidgetItem *item) const
{
if (!item || !item->parent())
return -1;
const int uniqueId = item->data(0, VersionIdRole).toInt();
for (int index = 0; index < m_versions.size(); ++index) {
if (m_versions.at(index)->uniqueId() == uniqueId)
return index;
}
return -1;
}
QTreeWidgetItem *QtOptionsPageWidget::treeItemForIndex(int index) const
{
const int uniqueId = m_versions.at(index)->uniqueId();
for (int i = 0; i < m_ui->qtdirList->topLevelItemCount(); ++i) {
QTreeWidgetItem *toplevelItem = m_ui->qtdirList->topLevelItem(i);
for (int j = 0; j < toplevelItem->childCount(); ++j) {
QTreeWidgetItem *item = toplevelItem->child(j);
if (item->data(0, VersionIdRole).toInt() == uniqueId)
return item;
}
}
return 0;
}
void QtOptionsPageWidget::versionChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *old)
{
Q_UNUSED(newItem);
Q_UNUSED(old);
userChangedCurrentVersion();
}
void QtOptionsPageWidget::updateWidgets()
{
delete m_configurationWidget;
m_configurationWidget = 0;
BaseQtVersion *version = currentVersion();
if (version) {
m_versionUi->nameEdit->setText(version->unexpandedDisplayName());
m_versionUi->qmakePath->setText(version->qmakeCommand().toUserOutput());
m_configurationWidget = version->createConfigurationWidget();
if (m_configurationWidget) {
m_versionUi->formLayout->addRow(m_configurationWidget);
m_configurationWidget->setEnabled(!version->isAutodetected());
connect(m_configurationWidget, SIGNAL(changed()),
this, SLOT(qtVersionChanged()));
}
} else {
m_versionUi->nameEdit->clear();
m_versionUi->qmakePath->clear();
}
const bool enabled = version != 0;
const bool isAutodetected = enabled && version->isAutodetected();
m_ui->delButton->setEnabled(enabled && !isAutodetected);
m_versionUi->nameEdit->setEnabled(enabled);
m_versionUi->editPathPushButton->setEnabled(enabled && !isAutodetected);
}
void QtOptionsPageWidget::updateCurrentQtName()
{
QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem();
Q_ASSERT(currentItem);
int currentItemIndex = indexForTreeItem(currentItem);
if (currentItemIndex < 0)
return;
BaseQtVersion *version = m_versions[currentItemIndex];
version->setUnexpandedDisplayName(m_versionUi->nameEdit->text());
updateDescriptionLabel();
foreach (BaseQtVersion *i, m_versions)
updateVersionItem(i);
}
void QtOptionsPageWidget::apply()
{
disconnect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged,
this, &QtOptionsPageWidget::updateQtVersions);
QtVersionManager::setNewQtVersions(versions());
connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged,
this, &QtOptionsPageWidget::updateQtVersions);
}
QList<BaseQtVersion *> QtOptionsPageWidget::versions() const
{
QList<BaseQtVersion *> result;
for (int i = 0; i < m_versions.count(); ++i)
result.append(m_versions.at(i)->clone());
return result;
}
} // namespace Internal
} // namespace QtSupport
| martyone/sailfish-qtcreator | src/plugins/qtsupport/qtoptionspage.cpp | C++ | lgpl-2.1 | 34,775 |
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\DBAL\Schema;
/**
* Configuration for a Schema
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class SchemaConfig
{
/**
* @var bool
*/
protected $hasExplicitForeignKeyIndexes = false;
/**
* @var int
*/
protected $maxIdentifierLength = 63;
/**
* @var string
*/
protected $name;
/**
* @var array
*/
protected $defaultTableOptions = array();
/**
* @return bool
*/
public function hasExplicitForeignKeyIndexes()
{
return $this->hasExplicitForeignKeyIndexes;
}
/**
* @param bool $flag
*/
public function setExplicitForeignKeyIndexes($flag)
{
$this->hasExplicitForeignKeyIndexes = (bool)$flag;
}
/**
* @param int $length
*/
public function setMaxIdentifierLength($length)
{
$this->maxIdentifierLength = (int)$length;
}
/**
* @return int
*/
public function getMaxIdentifierLength()
{
return $this->maxIdentifierLength;
}
/**
* Get default namespace of schema objects.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* set default namespace name of schema objects.
*
* @param string $name the value to set.
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get the default options that are passed to Table instances created with
* Schema#createTable().
*
* @return array
*/
public function getDefaultTableOptions()
{
return $this->defaultTableOptions;
}
public function setDefaultTableOptions(array $defaultTableOptions)
{
$this->defaultTableOptions = $defaultTableOptions;
}
}
| PureBilling/dbal | lib/Doctrine/DBAL/Schema/SchemaConfig.php | PHP | lgpl-2.1 | 2,923 |
/*
* Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGTextContentElement.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "RenderObject.h"
#include "RenderSVGResource.h"
#include "RenderSVGText.h"
#include "SVGDocumentExtensions.h"
#include "SVGElementInstance.h"
#include "SVGNames.h"
#include "SVGTextQuery.h"
#include "XMLNames.h"
namespace WebCore {
// Define custom animated property 'textLength'.
const SVGPropertyInfo* SVGTextContentElement::textLengthPropertyInfo()
{
static const SVGPropertyInfo* s_propertyInfo = 0;
if (!s_propertyInfo) {
s_propertyInfo = new SVGPropertyInfo(AnimatedLength,
PropertyIsReadWrite,
SVGNames::textLengthAttr,
SVGNames::textLengthAttr.localName(),
&SVGTextContentElement::synchronizeTextLength,
&SVGTextContentElement::lookupOrCreateTextLengthWrapper);
}
return s_propertyInfo;
}
// Animated property definitions
DEFINE_ANIMATED_ENUMERATION(SVGTextContentElement, SVGNames::lengthAdjustAttr, LengthAdjust, lengthAdjust, SVGLengthAdjustType)
DEFINE_ANIMATED_BOOLEAN(SVGTextContentElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextContentElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(textLength)
REGISTER_LOCAL_ANIMATED_PROPERTY(lengthAdjust)
REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document* document)
: SVGGraphicsElement(tagName, document)
, m_textLength(LengthModeOther)
, m_specifiedTextLength(LengthModeOther)
, m_lengthAdjust(SVGLengthAdjustSpacing)
{
registerAnimatedPropertiesForSVGTextContentElement();
}
void SVGTextContentElement::synchronizeTextLength(SVGElement* contextElement)
{
ASSERT(contextElement);
SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement);
if (!ownerType->m_textLength.shouldSynchronize)
return;
AtomicString value(SVGPropertyTraits<SVGLength>::toString(ownerType->m_specifiedTextLength));
ownerType->m_textLength.synchronize(ownerType, textLengthPropertyInfo()->attributeName, value);
}
PassRefPtr<SVGAnimatedProperty> SVGTextContentElement::lookupOrCreateTextLengthWrapper(SVGElement* contextElement)
{
ASSERT(contextElement);
SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement);
return SVGAnimatedProperty::lookupOrCreateWrapper<SVGTextContentElement, SVGAnimatedLength, SVGLength>
(ownerType, textLengthPropertyInfo(), ownerType->m_textLength.value);
}
PassRefPtr<SVGAnimatedLength> SVGTextContentElement::textLengthAnimated()
{
DEFINE_STATIC_LOCAL(SVGLength, defaultTextLength, (LengthModeOther));
if (m_specifiedTextLength == defaultTextLength)
m_textLength.value.newValueSpecifiedUnits(LengthTypeNumber, getComputedTextLength(), ASSERT_NO_EXCEPTION);
m_textLength.shouldSynchronize = true;
return static_pointer_cast<SVGAnimatedLength>(lookupOrCreateTextLengthWrapper(this));
}
unsigned SVGTextContentElement::getNumberOfChars()
{
document()->updateLayoutIgnorePendingStylesheets();
return SVGTextQuery(renderer()).numberOfCharacters();
}
float SVGTextContentElement::getComputedTextLength()
{
document()->updateLayoutIgnorePendingStylesheets();
return SVGTextQuery(renderer()).textLength();
}
float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionCode& ec)
{
document()->updateLayoutIgnorePendingStylesheets();
unsigned numberOfChars = getNumberOfChars();
if (charnum >= numberOfChars) {
ec = INDEX_SIZE_ERR;
return 0.0f;
}
return SVGTextQuery(renderer()).subStringLength(charnum, nchars);
}
SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionCode& ec)
{
document()->updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
ec = INDEX_SIZE_ERR;
return SVGPoint();
}
return SVGTextQuery(renderer()).startPositionOfCharacter(charnum);
}
SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionCode& ec)
{
document()->updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
ec = INDEX_SIZE_ERR;
return SVGPoint();
}
return SVGTextQuery(renderer()).endPositionOfCharacter(charnum);
}
FloatRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionCode& ec)
{
document()->updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
ec = INDEX_SIZE_ERR;
return FloatRect();
}
return SVGTextQuery(renderer()).extentOfCharacter(charnum);
}
float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionCode& ec)
{
document()->updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
ec = INDEX_SIZE_ERR;
return 0.0f;
}
return SVGTextQuery(renderer()).rotationOfCharacter(charnum);
}
int SVGTextContentElement::getCharNumAtPosition(const SVGPoint& point)
{
document()->updateLayoutIgnorePendingStylesheets();
return SVGTextQuery(renderer()).characterNumberAtPosition(point);
}
void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionCode& ec)
{
unsigned numberOfChars = getNumberOfChars();
if (charnum >= numberOfChars) {
ec = INDEX_SIZE_ERR;
return;
}
if (nchars > numberOfChars - charnum)
nchars = numberOfChars - charnum;
ASSERT(document());
ASSERT(document()->frame());
FrameSelection& selection = document()->frame()->selection();
// Find selection start
VisiblePosition start(firstPositionInNode(const_cast<SVGTextContentElement*>(this)));
for (unsigned i = 0; i < charnum; ++i)
start = start.next();
// Find selection end
VisiblePosition end(start);
for (unsigned i = 0; i < nchars; ++i)
end = end.next();
selection.setSelection(VisibleSelection(start, end));
}
bool SVGTextContentElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::lengthAdjustAttr);
supportedAttributes.add(SVGNames::textLengthAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
bool SVGTextContentElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name.matches(XMLNames::spaceAttr))
return true;
return SVGGraphicsElement::isPresentationAttribute(name);
}
void SVGTextContentElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (!isSupportedAttribute(name))
SVGGraphicsElement::collectStyleForPresentationAttribute(name, value, style);
else if (name.matches(XMLNames::spaceAttr)) {
DEFINE_STATIC_LOCAL(const AtomicString, preserveString, ("preserve", AtomicString::ConstructFromLiteral));
if (value == preserveString)
addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre);
else
addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValueNowrap);
}
}
void SVGTextContentElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
SVGParsingError parseError = NoError;
if (!isSupportedAttribute(name))
SVGGraphicsElement::parseAttribute(name, value);
else if (name == SVGNames::lengthAdjustAttr) {
SVGLengthAdjustType propertyValue = SVGPropertyTraits<SVGLengthAdjustType>::fromString(value);
if (propertyValue > 0)
setLengthAdjustBaseValue(propertyValue);
} else if (name == SVGNames::textLengthAttr) {
m_textLength.value = SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths);
} else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
} else if (SVGLangSpace::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
reportAttributeParsingError(parseError, name, value);
}
void SVGTextContentElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
SVGGraphicsElement::svgAttributeChanged(attrName);
return;
}
SVGElementInstance::InvalidationGuard invalidationGuard(this);
if (attrName == SVGNames::textLengthAttr)
m_specifiedTextLength = m_textLength.value;
if (RenderObject* renderer = this->renderer())
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
}
bool SVGTextContentElement::selfHasRelativeLengths() const
{
// Any element of the <text> subtree is advertized as using relative lengths.
// On any window size change, we have to relayout the text subtree, as the
// effective 'on-screen' font size may change.
return true;
}
SVGTextContentElement* SVGTextContentElement::elementFromRenderer(RenderObject* renderer)
{
if (!renderer)
return 0;
if (!renderer->isSVGText() && !renderer->isSVGInline())
return 0;
SVGElement* element = toSVGElement(renderer->node());
ASSERT(element);
if (!element->isTextContent())
return 0;
return toSVGTextContentElement(element);
}
}
#endif // ENABLE(SVG)
| KnightSwarm/WebKitTi | Source/WebCore/svg/SVGTextContentElement.cpp | C++ | lgpl-2.1 | 10,922 |
package pl.grmdev.narutocraft.items.weapons;
import net.minecraft.item.Item;
import pl.grmdev.narutocraft.NarutoCraft;
public class SmokeBomb extends Item {
public SmokeBomb(){
this.setUnlocalizedName("SmokeBomb");
this.setCreativeTab(NarutoCraft.mTabNarutoCraft);
this.maxStackSize = 64;
}
}
| GRM-dev/Narutocraft-PL_Mod | src/main/java/pl/grmdev/narutocraft/items/weapons/SmokeBomb.java | Java | lgpl-2.1 | 318 |
package com.prowritingaid.client;
public class TagAnalysisResponse {
public String url;
public int wordCount;
public DocTag[] tags;
public int numReports;
public long requestId ;
public String onreportsidebar;
}
| prowritingaid/openoffice-extension | src/main/java/com/prowritingaid/client/TagAnalysisResponse.java | Java | lgpl-2.1 | 261 |
package betteragriculture.client.render.mobs;
import betteragriculture.entity.entitymob.EntityMobPig8;
import net.minecraft.client.model.ModelPig;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.layers.LayerHeldItem;
import net.minecraft.util.ResourceLocation;
public class RenderEntityMobPig8 extends RenderLiving<EntityMobPig8>
{
private final ResourceLocation textures = new ResourceLocation("betteragriculture:textures/models/pig8.png");
public RenderEntityMobPig8(RenderManager renderManager)
{
super(renderManager, new ModelPig(), 0);
this.addLayer(new LayerHeldItem(this));
}
@Override
protected ResourceLocation getEntityTexture(EntityMobPig8 entity)
{
return textures;
}
} | nfinit-gaming/BetterAgriculture | src/main/java/betteragriculture/client/render/mobs/RenderEntityMobPig8.java | Java | lgpl-2.1 | 815 |
/*
* IronJacamar, a Java EE Connector Architecture implementation
* Copyright 2012, Red Hat Inc, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jca.sjc.maven;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* A deploy mojo
* @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a>
*/
public class Deploy extends AbstractHostPortMojo
{
/** The file */
private File file;
/**
* Constructor
*/
public Deploy()
{
this.file = null;
}
/**
* Set the file
* @param v The value
*/
public void setFile(File v)
{
file = v;
}
/**
* {@inheritDoc}
*/
public void execute() throws MojoExecutionException, MojoFailureException
{
if (file == null)
throw new MojoFailureException("File not defined");
if (!file.exists())
throw new MojoFailureException("File doesn't exists: " + file);
FileInputStream fis = null;
try
{
Boolean result = null;
if (isLocal())
{
Object value = executeCommand("local-deploy", new Serializable[] {file.toURI().toURL()});
if (value instanceof Boolean)
{
result = (Boolean)value;
}
else
{
throw (Throwable)value;
}
}
else
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
fis = new FileInputStream(file);
int i = fis.read();
while (i != -1)
{
baos.write(i);
i = fis.read();
}
byte[] bytes = baos.toByteArray();
Object value = executeCommand("remote-deploy", new Serializable[] {file.getName(), bytes});
if (value instanceof Boolean)
{
result = (Boolean)value;
}
else
{
throw (Throwable)value;
}
}
if (result.booleanValue())
{
getLog().info("Deployed: " + file.getName());
}
else
{
getLog().info(file.getName() + " wasn't deployed");
}
}
catch (Throwable t)
{
throw new MojoFailureException("Unable to deploy to " + getHost() + ":" + getPort() +
" (" + t.getMessage() + ")", t);
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (IOException ioe)
{
// Ignore
}
}
}
}
}
| ironjacamar/ironjacamar | sjc/src/main/java/org/jboss/jca/sjc/maven/Deploy.java | Java | lgpl-2.1 | 3,793 |
<?php
namespace wcf\system\option\user\group;
use wcf\system\option\TextOptionType;
use wcf\util\StringUtil;
/**
* User group option type implementation for textual input fields.
*
* The merge of option values returns merge of all text values.
*
* @author Marcel Werk
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Option\User\Group
*/
class TextUserGroupOptionType extends TextOptionType implements IUserGroupOptionType {
/**
* @inheritDoc
*/
public function merge($defaultValue, $groupValue) {
$defaultValue = empty($defaultValue) ? [] : explode("\n", StringUtil::unifyNewlines($defaultValue));
$groupValue = empty($groupValue) ? [] : explode("\n", StringUtil::unifyNewlines($groupValue));
return implode("\n", array_unique(array_merge($defaultValue, $groupValue)));
}
}
| MenesesEvandro/WCF | wcfsetup/install/files/lib/system/option/user/group/TextUserGroupOptionType.class.php | PHP | lgpl-2.1 | 921 |
/*
* Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "shapes.h"
#include <iostream>
#include <stdexcept>
namespace p2t {
Triangle::Triangle(Point& a, Point& b, Point& c)
{
points_[0] = &a; points_[1] = &b; points_[2] = &c;
neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL;
constrained_edge[0] = constrained_edge[1] = constrained_edge[2] = false;
delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false;
interior_ = false;
}
// Update neighbor pointers
void Triangle::MarkNeighbor(Point* p1, Point* p2, Triangle* t)
{
if ((p1 == points_[2] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[2]))
neighbors_[0] = t;
else if ((p1 == points_[0] && p2 == points_[2]) || (p1 == points_[2] && p2 == points_[0]))
neighbors_[1] = t;
else if ((p1 == points_[0] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[0]))
neighbors_[2] = t;
else
throw std::runtime_error("failed to MarkNeighbor");
}
// Exhaustive search to update neighbor pointers
void Triangle::MarkNeighbor(Triangle& t)
{
if (t.Contains(points_[1], points_[2])) {
neighbors_[0] = &t;
t.MarkNeighbor(points_[1], points_[2], this);
} else if (t.Contains(points_[0], points_[2])) {
neighbors_[1] = &t;
t.MarkNeighbor(points_[0], points_[2], this);
} else if (t.Contains(points_[0], points_[1])) {
neighbors_[2] = &t;
t.MarkNeighbor(points_[0], points_[1], this);
}
}
/**
* Clears all references to all other triangles and points
*/
void Triangle::Clear()
{
Triangle *t;
for( int i=0; i<3; i++ )
{
t = neighbors_[i];
if( t != NULL )
{
t->ClearNeighbor( this );
}
}
ClearNeighbors();
points_[0]=points_[1]=points_[2] = NULL;
}
void Triangle::ClearNeighbor(Triangle *triangle )
{
if( neighbors_[0] == triangle )
{
neighbors_[0] = NULL;
}
else if( neighbors_[1] == triangle )
{
neighbors_[1] = NULL;
}
else
{
neighbors_[2] = NULL;
}
}
void Triangle::ClearNeighbors()
{
neighbors_[0] = NULL;
neighbors_[1] = NULL;
neighbors_[2] = NULL;
}
void Triangle::ClearDelunayEdges()
{
delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false;
}
Point* Triangle::OppositePoint(Triangle& t, Point& p)
{
Point *cw = t.PointCW(p);
//double x = cw->x;
//double y = cw->y;
//x = p.x;
//y = p.y;
assert(cw);
return PointCW(*cw);
}
// Legalized triangle by rotating clockwise around point(0)
void Triangle::Legalize(Point& point)
{
points_[1] = points_[0];
points_[0] = points_[2];
points_[2] = &point;
}
// Legalize triagnle by rotating clockwise around oPoint
void Triangle::Legalize(Point& opoint, Point& npoint)
{
if (&opoint == points_[0]) {
points_[1] = points_[0];
points_[0] = points_[2];
points_[2] = &npoint;
} else if (&opoint == points_[1]) {
points_[2] = points_[1];
points_[1] = points_[0];
points_[0] = &npoint;
} else if (&opoint == points_[2]) {
points_[0] = points_[2];
points_[2] = points_[1];
points_[1] = &npoint;
} else {
throw std::runtime_error("failed to Legalize");
}
}
int Triangle::Index(const Point* p)
{
if (p == points_[0]) {
return 0;
} else if (p == points_[1]) {
return 1;
} else if (p == points_[2]) {
return 2;
}
throw std::runtime_error("failed to Index");
}
int Triangle::EdgeIndex(const Point* p1, const Point* p2)
{
if (points_[0] == p1) {
if (points_[1] == p2) {
return 2;
} else if (points_[2] == p2) {
return 1;
}
} else if (points_[1] == p1) {
if (points_[2] == p2) {
return 0;
} else if (points_[0] == p2) {
return 2;
}
} else if (points_[2] == p1) {
if (points_[0] == p2) {
return 1;
} else if (points_[1] == p2) {
return 0;
}
}
return -1;
}
void Triangle::MarkConstrainedEdge(const int index)
{
constrained_edge[index] = true;
}
void Triangle::MarkConstrainedEdge(Edge& edge)
{
MarkConstrainedEdge(edge.p, edge.q);
}
// Mark edge as constrained
void Triangle::MarkConstrainedEdge(Point* p, Point* q)
{
if ((q == points_[0] && p == points_[1]) || (q == points_[1] && p == points_[0])) {
constrained_edge[2] = true;
} else if ((q == points_[0] && p == points_[2]) || (q == points_[2] && p == points_[0])) {
constrained_edge[1] = true;
} else if ((q == points_[1] && p == points_[2]) || (q == points_[2] && p == points_[1])) {
constrained_edge[0] = true;
}
}
// The point counter-clockwise to given point
Point* Triangle::PointCW(Point& point)
{
if (&point == points_[0]) {
return points_[2];
} else if (&point == points_[1]) {
return points_[0];
} else if (&point == points_[2]) {
return points_[1];
}
throw std::runtime_error("failed in PointCW");
}
// The point counter-clockwise to given point
Point* Triangle::PointCCW(Point& point)
{
if (&point == points_[0]) {
return points_[1];
} else if (&point == points_[1]) {
return points_[2];
} else if (&point == points_[2]) {
return points_[0];
}
throw std::runtime_error("failed in PointCCW");
}
// The neighbor clockwise to given point
Triangle* Triangle::NeighborCW(Point& point)
{
if (&point == points_[0]) {
return neighbors_[1];
} else if (&point == points_[1]) {
return neighbors_[2];
}
return neighbors_[0];
}
// The neighbor counter-clockwise to given point
Triangle* Triangle::NeighborCCW(Point& point)
{
if (&point == points_[0]) {
return neighbors_[2];
} else if (&point == points_[1]) {
return neighbors_[0];
}
return neighbors_[1];
}
bool Triangle::GetConstrainedEdgeCCW(Point& p)
{
if (&p == points_[0]) {
return constrained_edge[2];
} else if (&p == points_[1]) {
return constrained_edge[0];
}
return constrained_edge[1];
}
bool Triangle::GetConstrainedEdgeCW(Point& p)
{
if (&p == points_[0]) {
return constrained_edge[1];
} else if (&p == points_[1]) {
return constrained_edge[2];
}
return constrained_edge[0];
}
void Triangle::SetConstrainedEdgeCCW(Point& p, bool ce)
{
if (&p == points_[0]) {
constrained_edge[2] = ce;
} else if (&p == points_[1]) {
constrained_edge[0] = ce;
} else {
constrained_edge[1] = ce;
}
}
void Triangle::SetConstrainedEdgeCW(Point& p, bool ce)
{
if (&p == points_[0]) {
constrained_edge[1] = ce;
} else if (&p == points_[1]) {
constrained_edge[2] = ce;
} else {
constrained_edge[0] = ce;
}
}
bool Triangle::GetDelunayEdgeCCW(Point& p)
{
if (&p == points_[0]) {
return delaunay_edge[2];
} else if (&p == points_[1]) {
return delaunay_edge[0];
}
return delaunay_edge[1];
}
bool Triangle::GetDelunayEdgeCW(Point& p)
{
if (&p == points_[0]) {
return delaunay_edge[1];
} else if (&p == points_[1]) {
return delaunay_edge[2];
}
return delaunay_edge[0];
}
void Triangle::SetDelunayEdgeCCW(Point& p, bool e)
{
if (&p == points_[0]) {
delaunay_edge[2] = e;
} else if (&p == points_[1]) {
delaunay_edge[0] = e;
} else {
delaunay_edge[1] = e;
}
}
void Triangle::SetDelunayEdgeCW(Point& p, bool e)
{
if (&p == points_[0]) {
delaunay_edge[1] = e;
} else if (&p == points_[1]) {
delaunay_edge[2] = e;
} else {
delaunay_edge[0] = e;
}
}
// The neighbor across to given point
Triangle& Triangle::NeighborAcross(Point& opoint)
{
if (&opoint == points_[0]) {
return *neighbors_[0];
} else if (&opoint == points_[1]) {
return *neighbors_[1];
}
return *neighbors_[2];
}
void Triangle::DebugPrint()
{
using namespace std;
cout << points_[0]->x << "," << points_[0]->y << " ";
cout << points_[1]->x << "," << points_[1]->y << " ";
cout << points_[2]->x << "," << points_[2]->y << endl;
}
}
| Oslandia/horao | src/poly2tri/common/shapes.cc | C++ | lgpl-2.1 | 9,354 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("15fcb70e-9a51-4d36-a2bc-51541204eebe")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| spaghettidba/ExtendedTSQLCollector | ExtendedTSQLCollector/Common/Properties/AssemblyInfo.cs | C# | lgpl-2.1 | 1,388 |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#define QT_NO_CAST_FROM_ASCII
#include "lldbenginehost.h"
#include "debuggerstartparameters.h"
#include "debuggeractions.h"
#include "debuggerconstants.h"
#include "debuggerdialogs.h"
#include "debuggerplugin.h"
#include "debuggerstringutils.h"
#include "breakhandler.h"
#include "breakpoint.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"
#include "threadshandler.h"
#include "disassembleragent.h"
#include "memoryagent.h"
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
#include <QDebug>
#include <QProcess>
#include <QFileInfo>
#include <QThread>
#include <QCoreApplication>
namespace Debugger {
namespace Internal {
SshIODevice::SshIODevice(QSsh::SshRemoteProcessRunner *r)
: runner(r)
, buckethead(0)
{
setOpenMode(QIODevice::ReadWrite | QIODevice::Unbuffered);
connect (runner, SIGNAL(processStarted()), this, SLOT(processStarted()));
connect(runner, SIGNAL(readyReadStandardOutput()), this, SLOT(outputAvailable()));
connect(runner, SIGNAL(readyReadStandardError()), this, SLOT(errorOutputAvailable()));
}
SshIODevice::~SshIODevice()
{
delete runner;
}
qint64 SshIODevice::bytesAvailable () const
{
qint64 r = QIODevice::bytesAvailable();
foreach (const QByteArray &bucket, buckets)
r += bucket.size();
r-= buckethead;
return r;
}
qint64 SshIODevice::writeData (const char * data, qint64 maxSize)
{
if (proc == 0) {
startupbuffer += QByteArray::fromRawData(data, maxSize);
return maxSize;
}
proc->write(data, maxSize);
return maxSize;
}
qint64 SshIODevice::readData (char * data, qint64 maxSize)
{
if (proc == 0)
return 0;
qint64 size = maxSize;
while (size > 0) {
if (!buckets.size()) {
return maxSize - size;
}
QByteArray &bucket = buckets.head();
if ((size + buckethead) >= bucket.size()) {
int d = bucket.size() - buckethead;
memcpy(data, bucket.data() + buckethead, d);
data += d;
size -= d;
buckets.dequeue();
buckethead = 0;
} else {
memcpy(data, bucket.data() + buckethead, size);
data += size;
buckethead += size;
size = 0;
}
}
return maxSize - size;
}
void SshIODevice::processStarted()
{
runner->writeDataToProcess(startupbuffer);
}
void SshIODevice::outputAvailable()
{
buckets.enqueue(runner->readAllStandardOutput());
emit readyRead();
}
void SshIODevice::errorOutputAvailable()
{
fprintf(stderr, "%s", runner->readAllStandardError().data());
}
LldbEngineHost::LldbEngineHost(const DebuggerStartParameters &startParameters)
:IPCEngineHost(startParameters), m_ssh(0)
{
showMessage(QLatin1String("setting up coms"));
if (startParameters.startMode == StartRemoteEngine)
{
m_guestProcess = 0;
QSsh::SshRemoteProcessRunner * const runner = new QSsh::SshRemoteProcessRunner;
connect (runner, SIGNAL(connectionError(QSsh::SshError)),
this, SLOT(sshConnectionError(QSsh::SshError)));
runner->run(startParameters.serverStartScript.toUtf8(), startParameters.connParams);
setGuestDevice(new SshIODevice(runner));
} else {
m_guestProcess = new QProcess(this);
connect(m_guestProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
this, SLOT(finished(int,QProcess::ExitStatus)));
connect(m_guestProcess, SIGNAL(readyReadStandardError()), this,
SLOT(stderrReady()));
QString a = Core::ICore::resourcePath() + QLatin1String("/qtcreator-lldb");
if(getenv("QTC_LLDB_GUEST") != 0)
a = QString::fromLocal8Bit(getenv("QTC_LLDB_GUEST"));
showStatusMessage(QString(QLatin1String("starting %1")).arg(a));
m_guestProcess->start(a, QStringList(), QIODevice::ReadWrite | QIODevice::Unbuffered);
m_guestProcess->setReadChannel(QProcess::StandardOutput);
if (!m_guestProcess->waitForStarted()) {
showStatusMessage(tr("qtcreator-lldb failed to start: %1").arg(m_guestProcess->errorString()));
notifyEngineSpontaneousShutdown();
return;
}
setGuestDevice(m_guestProcess);
}
}
LldbEngineHost::~LldbEngineHost()
{
showMessage(QLatin1String("tear down qtcreator-lldb"));
if (m_guestProcess) {
disconnect(m_guestProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
this, SLOT(finished(int,QProcess::ExitStatus)));
m_guestProcess->terminate();
m_guestProcess->kill();
}
if (m_ssh && m_ssh->isProcessRunning()) {
// TODO: openssh doesn't do that
m_ssh->sendSignalToProcess(QSsh::SshRemoteProcess::KillSignal);
}
}
void LldbEngineHost::nuke()
{
stderrReady();
showMessage(QLatin1String("Nuke engaged. Bug in Engine/IPC or incompatible IPC versions. "), LogError);
showStatusMessage(tr("Fatal engine shutdown. Consult debugger log for details."));
m_guestProcess->terminate();
m_guestProcess->kill();
notifyEngineSpontaneousShutdown();
}
void LldbEngineHost::sshConnectionError(QSsh::SshError e)
{
showStatusMessage(tr("SSH connection error: %1").arg(e));
}
void LldbEngineHost::finished(int, QProcess::ExitStatus status)
{
showMessage(QString(QLatin1String("guest went bye bye. exit status: %1 and code: %2"))
.arg(status).arg(m_guestProcess->exitCode()), LogError);
nuke();
}
void LldbEngineHost::stderrReady()
{
fprintf(stderr,"%s", m_guestProcess->readAllStandardError().data());
}
DebuggerEngine *createLldbEngine(const DebuggerStartParameters &startParameters)
{
return new LldbEngineHost(startParameters);
}
} // namespace Internal
} // namespace Debugger
| KDE/android-qt-creator | src/plugins/debugger/lldb/lldbenginehost.cpp | C++ | lgpl-2.1 | 7,149 |
/*
* Copyright 2014 The Solmix Project
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.gnu.org/licenses/
* or see the FSF site: http://www.fsf.org.
*/
package org.solmix.datax.support;
import org.solmix.datax.RequestContext;
import org.solmix.runtime.resource.support.ResourceResolverAdaptor;
/**
*
* @author solmix.f@gmail.com
* @version $Id$ 2015年7月26日
*/
public class RequestContextResourceResolver extends ResourceResolverAdaptor
{
private final RequestContext context;
public RequestContextResourceResolver(RequestContext context){
this.context=context;
}
@SuppressWarnings("unchecked")
@Override
public <T> T resolve(String resourceName, Class<T> resourceType) {
if (resourceType == RequestContext.class) {
return (T) context;
} else if (context != null) {
return context.get(resourceType);
}
return null;
}
}
| solmix/datax | core/src/main/java/org/solmix/datax/support/RequestContextResourceResolver.java | Java | lgpl-2.1 | 1,570 |
<?php
namespace phplug\plugins\phplug_core\annotations;
class ReflectionAnnotatedClass extends \ReflectionClass {
private $annotations;
public function __construct($class) {
parent::__construct($class);
$this->annotations = $this->createAnnotationBuilder()->build($this);
}
public function hasAnnotation($class) {
$class = AnnotationMap::getInstance()->getClass($class);
return $this->annotations->hasAnnotation($class);
}
public function getAnnotation($annotation) {
$class = AnnotationMap::getInstance()->getClass($annotation);
return $this->annotations->getAnnotation($class);
}
public function getAnnotations() {
return $this->annotations->getAnnotations();
}
public function getAllAnnotations($restriction = false) {
return $this->annotations->getAllAnnotations($restriction);
}
public function getConstructor() {
return $this->createReflectionAnnotatedMethod(parent::getConstructor());
}
public function getMethod($name) {
return $this->createReflectionAnnotatedMethod(parent::getMethod($name));
}
public function getMethods($filter = -1) {
$result = array();
foreach(parent::getMethods($filter) as $method) {
$result[] = $this->createReflectionAnnotatedMethod($method);
}
return $result;
}
public function getProperty($name) {
return $this->createReflectionAnnotatedProperty(parent::getProperty($name));
}
public function getProperties($filter = -1) {
$result = array();
foreach(parent::getProperties($filter) as $property) {
$result[] = $this->createReflectionAnnotatedProperty($property);
}
return $result;
}
public function getInterfaces() {
$result = array();
foreach(parent::getInterfaces() as $interface) {
$result[] = $this->createReflectionAnnotatedClass($interface);
}
return $result;
}
public function getParentClass() {
$class = parent::getParentClass();
return $this->createReflectionAnnotatedClass($class);
}
protected function createAnnotationBuilder() {
return new AnnotationsBuilder();
}
private function createReflectionAnnotatedClass($class) {
return ($class !== false) ? new ReflectionAnnotatedClass($class->getName()) : false;
}
private function createReflectionAnnotatedMethod($method) {
return ($method !== null) ? new ReflectionAnnotatedMethod($this->getName(), $method->getName()) : null;
}
private function createReflectionAnnotatedProperty($property) {
return ($property !== null) ? new ReflectionAnnotatedProperty($this->getName(), $property->getName()) : null;
}
} | thobens/PHPlug | plugins/phplug_core/annotations/ReflectionAnnotatedClass.php | PHP | lgpl-2.1 | 2,601 |
# Copyright (c) 2002 Zooko, blanu
# This file is licensed under the
# GNU Lesser General Public License v2.1.
# See the file COPYING or visit http://www.gnu.org/ for details.
__revision__ = "$Id: tristero.py,v 1.2 2002/12/02 19:58:54 myers_carpenter Exp $"
nodeSchema='http://tristero.sourceforge.net/mnet/MetaTracker#'
commSchema='http://tristero.sourceforge.net/mnet/CommStrategies#'
lowerSchema='http://tristero.sourceforge.net/mnet/LowerStrategy#'
pubkeySchema='http://tristero.sourceforge.net/mnet/Pubkey#'
keyHeaderSchema='http://tristero.sourceforge.net/mnet/PubkeyHeader#'
keyValueSchema='http://tristero.sourceforge.net/mnet/PubkeyValue#'
LITERAL=0
RESOURCE=1
NODE=2
| zooko/egtp_new | egtp/tristero.py | Python | lgpl-2.1 | 687 |
<?php
class Article_Model extends CI_Model
{
function getArticleById($id)
{
$data=array();
$this->db->where('article_id',$id);
$query=$this->db->get('article');
$row=$query->row();
if(isset($row))
{
$data['article_id']=$row->article_id;
$data['article_author_id']=$row->article_author_id;
$data['article_type_id']=$row->article_type_id;
$data['article_title']=$row->article_title;
$data['article_introduction']=$row->article_introduction;
$data['article_content']=$row->article_content;
$data['article_posttime']=$row->article_posttime;
$data['article_comment_nums']=$row->article_comment_nums;
$data['article_view_nums']=$row->article_view_nums;
$data['article_tags']=$row->article_tags;
}
return $data;
}
} | zhangbailong945/LoachBlog | application/models/loachblog/Article_Model.php | PHP | lgpl-2.1 | 882 |
/**
* Copyright (C) 2010 Orbeon, Inc.
*
* 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.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor.impl;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.Processor;
import org.orbeon.oxf.processor.ProcessorImpl;
import org.orbeon.oxf.processor.ProcessorInput;
import org.orbeon.oxf.processor.ProcessorOutput;
import org.orbeon.datatypes.LocationData;
public class DelegatingProcessorInput implements ProcessorInput {
private final String originalName;
private ProcessorInput delegateInput;
private ProcessorOutput delegateOutput;
private ProcessorImpl processor;
public DelegatingProcessorInput(ProcessorImpl processor, String originalName, ProcessorInput delegateInput, ProcessorOutput delegateOutput) {
this.processor = processor;
this.originalName = originalName;
this.delegateInput = delegateInput;
this.delegateOutput = delegateOutput;
}
DelegatingProcessorInput(ProcessorImpl processor, String originalName) {
this.processor = processor;
this.originalName = originalName;
}
public Processor getProcessor(PipelineContext pipelineContext) {
return processor;
}
public void setDelegateInput(ProcessorInput delegateInput) {
this.delegateInput = delegateInput;
}
public void setDelegateOutput(ProcessorOutput delegateOutput) {
this.delegateOutput = delegateOutput;
}
public void setOutput(ProcessorOutput output) {
delegateInput.setOutput(output);
}
public ProcessorOutput getOutput() {
// Not sure why the input validation stuff expects another output here. For now, allow caller to specify
// which output is returned. Once we are confident, switch to delegateInput.getOutput().
return delegateOutput;
// return delegateInput.getOutput();
}
public String getSchema() {
return delegateInput.getSchema();
}
public void setSchema(String schema) {
delegateInput.setSchema(schema);
}
public Class getProcessorClass() {
return processor.getClass();
}
public String getName() {
return originalName;
}
public void setDebug(String debugMessage) {
delegateInput.setDebug(debugMessage);
}
public void setLocationData(LocationData locationData) {
delegateInput.setLocationData(locationData);
}
public String getDebugMessage() {
return delegateInput.getDebugMessage();
}
public LocationData getLocationData() {
return delegateInput.getLocationData();
}
}
| orbeon/orbeon-forms | src/main/java/org/orbeon/oxf/processor/impl/DelegatingProcessorInput.java | Java | lgpl-2.1 | 3,194 |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "openeditorswindow.h"
#include "openeditorsmodel.h"
#include "editormanager.h"
#include "editorview.h"
#include "idocument.h"
#include <utils/qtcassert.h>
#include <QFocusEvent>
#include <QHeaderView>
#include <QTreeWidget>
#include <QVBoxLayout>
Q_DECLARE_METATYPE(Core::Internal::EditorView*)
Q_DECLARE_METATYPE(Core::IDocument*)
using namespace Core;
using namespace Core::Internal;
const int WIDTH = 300;
const int HEIGHT = 200;
OpenEditorsWindow::OpenEditorsWindow(QWidget *parent) :
QFrame(parent, Qt::Popup),
m_emptyIcon(QLatin1String(":/core/images/empty14.png")),
m_editorList(new QTreeWidget(this))
{
resize(QSize(WIDTH, HEIGHT));
m_editorList->setColumnCount(1);
m_editorList->header()->hide();
m_editorList->setIndentation(0);
m_editorList->setSelectionMode(QAbstractItemView::SingleSelection);
m_editorList->setTextElideMode(Qt::ElideMiddle);
#ifdef Q_OS_MAC
m_editorList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
#endif
m_editorList->installEventFilter(this);
// We disable the frame on this list view and use a QFrame around it instead.
// This improves the look with QGTKStyle.
#ifndef Q_OS_MAC
setFrameStyle(m_editorList->frameStyle());
#endif
m_editorList->setFrameStyle(QFrame::NoFrame);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->addWidget(m_editorList);
connect(m_editorList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this, SLOT(editorClicked(QTreeWidgetItem*)));
}
void OpenEditorsWindow::selectAndHide()
{
setVisible(false);
selectEditor(m_editorList->currentItem());
}
void OpenEditorsWindow::setVisible(bool visible)
{
QWidget::setVisible(visible);
if (visible) {
setFocus();
}
}
bool OpenEditorsWindow::isCentering()
{
int internalMargin = m_editorList->viewport()->mapTo(m_editorList, QPoint(0,0)).y();
QRect rect0 = m_editorList->visualItemRect(m_editorList->topLevelItem(0));
QRect rect1 = m_editorList->visualItemRect(m_editorList->topLevelItem(m_editorList->topLevelItemCount()-1));
int height = rect1.y() + rect1.height() - rect0.y();
height += 2 * internalMargin;
if (height > HEIGHT)
return true;
return false;
}
bool OpenEditorsWindow::eventFilter(QObject *obj, QEvent *e)
{
if (obj == m_editorList) {
if (e->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if (ke->key() == Qt::Key_Escape) {
setVisible(false);
return true;
}
if (ke->key() == Qt::Key_Return) {
selectEditor(m_editorList->currentItem());
return true;
}
} else if (e->type() == QEvent::KeyRelease) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if (ke->modifiers() == 0
/*HACK this is to overcome some event inconsistencies between platforms*/
|| (ke->modifiers() == Qt::AltModifier
&& (ke->key() == Qt::Key_Alt || ke->key() == -1))) {
selectAndHide();
}
}
}
return QWidget::eventFilter(obj, e);
}
void OpenEditorsWindow::focusInEvent(QFocusEvent *)
{
m_editorList->setFocus();
}
void OpenEditorsWindow::selectUpDown(bool up)
{
int itemCount = m_editorList->topLevelItemCount();
if (itemCount < 2)
return;
int index = m_editorList->indexOfTopLevelItem(m_editorList->currentItem());
if (index < 0)
return;
QTreeWidgetItem *editor = 0;
int count = 0;
while (!editor && count < itemCount) {
if (up) {
index--;
if (index < 0)
index = itemCount-1;
} else {
index++;
if (index >= itemCount)
index = 0;
}
editor = m_editorList->topLevelItem(index);
count++;
}
if (editor) {
m_editorList->setCurrentItem(editor);
ensureCurrentVisible();
}
}
void OpenEditorsWindow::selectPreviousEditor()
{
selectUpDown(false);
}
void OpenEditorsWindow::selectNextEditor()
{
selectUpDown(true);
}
void OpenEditorsWindow::centerOnItem(int selectedIndex)
{
if (selectedIndex >= 0) {
QTreeWidgetItem *item;
int num = m_editorList->topLevelItemCount();
int rotate = selectedIndex-(num-1)/2;
for (int i = 0; i < rotate; ++i) {
item = m_editorList->takeTopLevelItem(0);
m_editorList->addTopLevelItem(item);
}
rotate = -rotate;
for (int i = 0; i < rotate; ++i) {
item = m_editorList->takeTopLevelItem(num-1);
m_editorList->insertTopLevelItem(0, item);
}
}
}
void OpenEditorsWindow::setEditors(EditorView *mainView, EditorView *view, OpenEditorsModel *model)
{
m_editorList->clear();
bool first = true;
QSet<IDocument*> documentsDone;
foreach (const EditLocation &hi, view->editorHistory()) {
if (hi.document.isNull() || documentsDone.contains(hi.document))
continue;
QString title = model->displayNameForDocument(hi.document);
QTC_ASSERT(!title.isEmpty(), continue);
documentsDone.insert(hi.document.data());
QTreeWidgetItem *item = new QTreeWidgetItem();
if (hi.document->isModified())
title += tr("*");
item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly()
? model->lockedIcon() : m_emptyIcon);
item->setText(0, title);
item->setToolTip(0, hi.document->fileName());
item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data()));
item->setData(0, Qt::UserRole+1, QVariant::fromValue(view));
item->setTextAlignment(0, Qt::AlignLeft);
m_editorList->addTopLevelItem(item);
if (first){
m_editorList->setCurrentItem(item);
first = false;
}
}
// add missing editors from the main view
if (mainView != view) {
foreach (const EditLocation &hi, mainView->editorHistory()) {
if (hi.document.isNull() || documentsDone.contains(hi.document))
continue;
documentsDone.insert(hi.document.data());
QTreeWidgetItem *item = new QTreeWidgetItem();
QString title = model->displayNameForDocument(hi.document);
if (hi.document->isModified())
title += tr("*");
item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly()
? model->lockedIcon() : m_emptyIcon);
item->setText(0, title);
item->setToolTip(0, hi.document->fileName());
item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data()));
item->setData(0, Qt::UserRole+1, QVariant::fromValue(view));
item->setData(0, Qt::UserRole+2, QVariant::fromValue(hi.id));
item->setTextAlignment(0, Qt::AlignLeft);
m_editorList->addTopLevelItem(item);
if (first){
m_editorList->setCurrentItem(item);
first = false;
}
}
}
// add purely restored editors which are not initialised yet
foreach (const OpenEditorsModel::Entry &entry, model->entries()) {
if (entry.editor)
continue;
QTreeWidgetItem *item = new QTreeWidgetItem();
QString title = entry.displayName();
item->setIcon(0, m_emptyIcon);
item->setText(0, title);
item->setToolTip(0, entry.fileName());
item->setData(0, Qt::UserRole+2, QVariant::fromValue(entry.id()));
item->setTextAlignment(0, Qt::AlignLeft);
m_editorList->addTopLevelItem(item);
}
}
void OpenEditorsWindow::selectEditor(QTreeWidgetItem *item)
{
if (!item)
return;
if (IDocument *document = item->data(0, Qt::UserRole).value<IDocument*>()) {
EditorView *view = item->data(0, Qt::UserRole+1).value<EditorView*>();
EditorManager::instance()->activateEditorForDocument(view, document, EditorManager::ModeSwitch);
} else {
if (!EditorManager::openEditor(
item->toolTip(0), item->data(0, Qt::UserRole+2).value<Core::Id>(),
Core::EditorManager::ModeSwitch)) {
EditorManager::instance()->openedEditorsModel()->removeEditor(item->toolTip(0));
delete item;
}
}
}
void OpenEditorsWindow::editorClicked(QTreeWidgetItem *item)
{
selectEditor(item);
setFocus();
}
void OpenEditorsWindow::ensureCurrentVisible()
{
m_editorList->scrollTo(m_editorList->currentIndex(), QAbstractItemView::PositionAtCenter);
}
| KDE/android-qt-creator | src/plugins/coreplugin/editormanager/openeditorswindow.cpp | C++ | lgpl-2.1 | 10,060 |
/*
* Copyright © 2012 Intel Corporation
*
* 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 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, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <benjamin.segovia@intel.com>
*/
#include "utest_helper.hpp"
static void compiler_local_memory_two_ptr(void)
{
const size_t n = 1024;
// Setup kernel and buffers
OCL_CREATE_KERNEL("compiler_local_memory_two_ptr");
OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(uint32_t), NULL);
OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]);
OCL_SET_ARG(1, 64, NULL); // 16 x int
OCL_SET_ARG(2, 64, NULL); // 16 x int
// Run the kernel
globals[0] = n;
locals[0] = 16;
OCL_NDRANGE(1);
OCL_MAP_BUFFER(0);
// Check results
int32_t *dst = (int32_t*)buf_data[0];
for (int32_t i = 0; i < (int) n; i+=16)
for (int32_t j = 0; j < 16; ++j) {
const int gid = i + j;
const int tid = j;
OCL_ASSERT(dst[i+j] == (gid&~0xf) + 15-tid + 15-tid);
}
}
MAKE_UTEST_FROM_FUNCTION(compiler_local_memory_two_ptr);
| ignatenkobrain/beignet | utests/compiler_local_memory_two_ptr.cpp | C++ | lgpl-2.1 | 1,557 |
#ifndef __femus_enums_MarkerTypeEnum_hpp__
#define __femus_enums_MarkerTypeEnum_hpp__
enum MarkerType {
VOLUME = 0,
INTERSECTION,
FIXED,
BOUNDARY,
INTERIOR
};
#endif
| eaulisa/MyFEMuS | src/enums/MarkerTypeEnum.hpp | C++ | lgpl-2.1 | 180 |
/*
* Part of the ROBOID project
* Copyright (C) 2016 Kwang-Hyun Park (akaii@kw.ac.kr) and Kyoung Jin Kim
* https://github.com/roboidstudio/embedded
*
* 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
*/
package org.roboid.studio.timeline.impl;
import java.util.Arrays;
import java.util.List;
import javax.sound.sampled.AudioFormat;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.PropertyDescriptor;
import org.roboid.audio.AudioUtil;
import org.roboid.robot.AudioMode;
import org.roboid.robot.DataType;
import org.roboid.robot.Device;
import org.roboid.studio.timeline.AudioPoint;
import org.roboid.studio.timeline.AudioTrack;
import org.roboid.studio.timeline.ChannelTrack;
import org.roboid.studio.timeline.ControlPoint;
import org.roboid.studio.timeline.TimelineFactory;
import org.roboid.studio.timeline.TimelinePackage;
import org.roboid.studio.timeline.VoicePoint;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Audio Track</b></em>'.
* @author Kyoung Jin Kim
* @author Kwang-Hyun Park
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.roboid.studio.timeline.impl.AudioTrackImpl#getMode <em>Mode</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class AudioTrackImpl extends ChannelTrackImpl implements AudioTrack
{
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AudioTrackImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return TimelinePackage.Literals.AUDIO_TRACK;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMode(AudioMode newMode)
{
AudioMode oldMode = mode;
mode = newMode == null ? MODE_EDEFAULT : newMode;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.AUDIO_TRACK__MODE, oldMode, mode));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID) {
case TimelinePackage.AUDIO_TRACK__MODE:
return getMode();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID) {
case TimelinePackage.AUDIO_TRACK__MODE:
setMode((AudioMode)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID) {
case TimelinePackage.AUDIO_TRACK__MODE:
setMode(MODE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID) {
case TimelinePackage.AUDIO_TRACK__MODE:
return mode != MODE_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (mode: ");
result.append(mode);
result.append(')');
return result.toString();
}
/*=====================================================================================
*=====================================================================================
* MODIFIED
*=====================================================================================
*=====================================================================================
*/
/**
* The default value of the '{@link #getMode() <em>Mode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMode()
* @generated NOT
* @ordered
*/
protected static final AudioMode MODE_EDEFAULT = null;
/**
* The cached value of the '{@link #getMode() <em>Mode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMode()
* @generated
* @ordered
*/
protected AudioMode mode = MODE_EDEFAULT;
private static final String P_MODE = "_mode";
int[] wave; // temporary wave data for one frame
private AudioFormat audioFormat;
@Override
protected void getPropertyDescriptors(List<IPropertyDescriptor> propertyDescriptors)
{
super.getPropertyDescriptors(propertyDescriptors);
propertyDescriptors.add(new PropertyDescriptor(P_MODE, "Mode"));
}
@Override
public Object getPropertyValue(Object id)
{
if(id.equals(P_CHANNEL)) return "Audio Channel";
if(id.equals(P_MODE)) return getMode().getLiteral();
if(id.equals(P_TARGET_DEVICE))
{
Device left = getTargetDevice(0);
if(left == null) return "";
Device right = getTargetDevice(1);
if(right == null)
return left.getName();
else
return left.getName() + ", " + right.getName();
}
return super.getPropertyValue(id);
}
@Override
public ChannelTrack deepCopy()
{
AudioTrack newTrack = TimelineFactory.eINSTANCE.createAudioTrack();
copyTo(newTrack);
return newTrack;
}
@Override
public boolean canCopy(ControlPoint cp)
{
if(cp instanceof AudioPoint)
return true;
return false;
}
@Override
public AudioPoint deepCopy(ControlPoint cp)
{
if(cp instanceof VoicePoint)
{
AudioPoint newPoint = TimelineFactory.eINSTANCE.createAudioPoint();
((AudioPointImpl)cp).copyTo(newPoint);
return newPoint;
}
else if(cp instanceof AudioPoint)
return (AudioPoint)cp.deepCopy();
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public AudioMode getMode()
{
if(mode == null)
{
if(getTargetDevices().size() == 1)
mode = AudioMode.MONO;
else
mode = AudioMode.STEREO;
}
return mode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void setMode(int newMode)
{
AudioMode mode = AudioMode.get(newMode);
if(mode != null) setMode(mode);
}
@Override
public int getTotalFrames()
{
int maxFrame = 0;
for(ControlPoint cp : getPoints())
{
int frame = cp.getFrame() + ((AudioPoint)cp).getLength(); // start frame + length of frames
if(maxFrame < frame) maxFrame = frame;
}
return maxFrame;
}
private AudioFormat getAudioFormatOfChannel(Device device)
{
// exception
// support only BYTE, SHORT, INTEGER types
if(!(device.getDataType().equals(DataType.BYTE) || device.getDataType().equals(DataType.SHORT) || device.getDataType().equals(DataType.INTEGER)))
throw new IllegalArgumentException("The datatype of target device should be BYTE, SHORT or INTEGER only.");
// format
int sampleSizeInBits = device.getDataType().getValue();
int channels = (getMode() == AudioMode.STEREO) ? 2 : 1;
int frameSize = ((sampleSizeInBits + 7) / 8) * channels;
float sampleRate = 50 * device.getDataSize();
AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sampleRate,
sampleSizeInBits,
channels,
frameSize,
sampleRate,
false);
return targetFormat;
}
public void preLoad()
{
Device leftDevice = getTargetDevice(0);
audioFormat = getAudioFormatOfChannel(leftDevice);
for(ControlPoint cp : getPoints())
{
((AudioPoint)cp).getPcm(audioFormat);
}
}
@Override
public void dump(int frame)
{
if(getPoints().size() == 0) return; // no control points
Device leftDevice = getTargetDevice(0);
Device rightDevice = getTargetDevice(1);
dump(frame, leftDevice, rightDevice);
}
/**
* writes audio data at current frame to the corresponding device
*
* @param frame
* @param leftDevice
* @param rightDevice
*/
protected void dump(int frame, Device leftDevice, Device rightDevice)
{
if(leftDevice == null) return;
// device format
if(audioFormat == null)
audioFormat = getAudioFormatOfChannel(leftDevice);
// obtain audio data at current frame
wave = getAudioData(frame, leftDevice, audioFormat);
if(getMode() == AudioMode.MONO)
{
leftDevice.write(wave);
}
else
{
if(rightDevice == null) return;
// stereo case
AudioFormat rightDeviceFormat = getAudioFormatOfChannel(rightDevice);
// exception
// audio formats of two target devices should be same
if(!AudioUtil.isEqual(audioFormat, rightDeviceFormat))
{
throw new IllegalArgumentException("The type of two target audio devices should be the same: " + audioFormat + " and " + rightDeviceFormat);
}
// divide two channels into seperate arrays
int stereo[][] = AudioUtil.splitChannel(wave, audioFormat.getChannels());
// write to each device
leftDevice.write(stereo[1]); // IMPORTANT: exchange left and right
rightDevice.write(stereo[0]);
}
}
/**
* returns audio data at current frame in target format
*
* @param frame
* @param targetFormat
* @return
*/
private int[] getAudioData(int frame, Device device, AudioFormat targetFormat)
{
int dataSize = device.getDataSize() * targetFormat.getChannels();
int maxValue = device.getMax();;
int minValue = device.getMin();
if(wave == null) wave = new int[dataSize];
Arrays.fill(wave, 0);
for(ControlPoint cp : getPoints())
{
AudioPoint ap = (AudioPoint)cp;
if(frame < ap.getFrame()) break;
else if(frame >= ap.getFrame() + ap.getLength()) continue;
int[] pcm = ap.getPcm(targetFormat);
if(pcm == null) continue;
// calculate offset of current frame in whole audio data
int offset = (frame - ap.getFrame()) * dataSize;
int len = pcm.length > offset + dataSize ? dataSize : pcm.length - offset;
// apply volume to audio data
AudioUtil.multiplyAndSum(pcm, offset, ap.getVolume()/100.0f, wave, 0, len, minValue, maxValue);
}
return wave;
}
} //AudioTrackImpl
| roboidstudio/embedded | org.roboid.studio.timeline.model/src/org/roboid/studio/timeline/impl/AudioTrackImpl.java | Java | lgpl-2.1 | 10,917 |
// nextweb - modern web framework for Python and C++
// Copyright (C) 2011 Oleg Obolenskiy <highpower@yandex-team.ru>
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifndef NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED
#define NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED
#include <iterator>
#include "nextweb/Config.hpp"
namespace nextweb { namespace utils {
template <typename Derived, typename Type, typename Dist, typename Pointer,
typename Reference, typename Tag> struct IteratorBase;
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference>
struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag> {
Pointer operator -> ();
Reference operator * ();
Derived& operator ++ ();
Derived operator ++ (int);
bool operator == (Derived const &other) const;
bool operator != (Derived const &other) const;
};
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference>
struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag> :
public IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>
{
Derived& operator -- ();
Derived operator -- (int);
};
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference>
struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag> :
public IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>
{
Derived operator + (Dist dist) const;
Derived& operator += (Dist dist);
Derived operator - (Dist dist) const;
Derived& operator -= (Dist dist);
Type operator [] (Dist dist) const;
Dist operator - (Derived const &other) const;
bool operator < (Derived const &other) const;
bool operator > (Derived const &other) const;
bool operator <= (Derived const &other) const;
bool operator >= (Derived const &other) const;
};
template <typename Derived, typename Tag, typename Type, typename Dist = std::ptrdiff_t, typename Pointer = Type*, typename Reference = Type&>
struct Iterator : public IteratorBase<Derived, Type, Dist, Pointer, Reference, Tag>, public std::iterator<Tag, Type, Dist, Pointer, Reference> {
};
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived&
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator ++ () {
Derived &object = static_cast<Derived&>(*this);
object.increment();
return object;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator ++ (int) {
Derived copy(static_cast<Derived const&>(*this));
++(*this);
return copy;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Pointer
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator -> () {
Reference ref = static_cast<Derived*>(this)->dereference();
return &ref;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Reference
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator * () {
return static_cast<Derived*>(this)->dereference();
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator == (Derived const &other) const {
return static_cast<Derived const*>(this)->equal(other);
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator != (Derived const &other) const {
return !static_cast<Derived const*>(this)->equal(other);
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived&
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>::operator -- () {
Derived &object = static_cast<Derived&>(*this);
object.decrement();
return object;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>::operator -- (int) {
Derived copy(static_cast<Derived const&>(*this));
--(*this);
return copy;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator + (Dist dist) const {
Derived copy(static_cast<Derived const&>(*this));
copy += dist;
return copy;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived&
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator += (Dist dist) {
Derived &object = static_cast<Derived&>(*this);
object.advance(dist);
return object;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator - (Dist dist) const {
Derived copy(static_cast<Derived const&>(*this));
copy -= dist;
return copy;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived&
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator -= (Dist dist) {
Derived &object = static_cast<Derived&>(*this);
object.advance(-dist);
return object;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Type
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator [] (Dist dist) const {
Derived copy(static_cast<Derived const&>(*this));
copy += dist;
return copy.dereference();
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Dist
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator - (Derived const &other) const {
return other.distance(static_cast<Derived const&>(*this));
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator < (Derived const &other) const {
return (static_cast<Derived const&>(*this) - other) < 0;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator > (Derived const &other) const {
return (static_cast<Derived const&>(*this) - other) > 0;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator <= (Derived const &other) const {
return (static_cast<Derived const&>(*this) - other) <= 0;
}
template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool
IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator >= (Derived const &other) const {
return (static_cast<Derived const&>(*this) - other) >= 0;
}
}} // namespaces
#endif // NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED
| tinybit/nextweb | include/nextweb/utils/Iterator.hpp | C++ | lgpl-2.1 | 8,530 |
#include "libavoid/libavoid.h"
using namespace Avoid;
int main(void) {
Router *router = new Router(OrthogonalRouting);
router->setRoutingParameter((RoutingParameter)0, 10);
router->setRoutingParameter((RoutingParameter)1, 0);
router->setRoutingParameter((RoutingParameter)2, 1000);
router->setRoutingParameter((RoutingParameter)3, 4000);
router->setRoutingParameter((RoutingParameter)4, 0);
router->setRoutingParameter((RoutingParameter)5, 100);
router->setRoutingParameter((RoutingParameter)6, 1);
router->setRoutingParameter((RoutingParameter)7, 10);
router->setRoutingParameter(reverseDirectionPenalty, 500);
router->setRoutingOption((RoutingOption)0, false);
router->setRoutingOption((RoutingOption)1, true);
router->setRoutingOption((RoutingOption)2, false);
router->setRoutingOption((RoutingOption)3, false);
router->setRoutingOption((RoutingOption)4, true);
router->setRoutingOption((RoutingOption)5, true);
Polygon polygon;
ConnRef *connRef = NULL;
ConnEnd srcPt;
ConnEnd dstPt;
PolyLine newRoute;
// shapeRef1
polygon = Polygon(4);
polygon.ps[0] = Point(0, 0);
polygon.ps[1] = Point(0, 0);
polygon.ps[2] = Point(0, 0);
polygon.ps[3] = Point(0, 0);
new ShapeRef(router, polygon, 1);
// shapeRef2
polygon = Polygon(4);
polygon.ps[0] = Point(0, 0);
polygon.ps[1] = Point(0, 0);
polygon.ps[2] = Point(0, 0);
polygon.ps[3] = Point(0, 0);
new ShapeRef(router, polygon, 2);
// shapeRef3
polygon = Polygon(4);
polygon.ps[0] = Point(0, 0);
polygon.ps[1] = Point(0, 0);
polygon.ps[2] = Point(0, 0);
polygon.ps[3] = Point(0, 0);
new ShapeRef(router, polygon, 3);
// shapeRef4
polygon = Polygon(4);
polygon.ps[0] = Point(0, 0);
polygon.ps[1] = Point(0, 0);
polygon.ps[2] = Point(0, 0);
polygon.ps[3] = Point(0, 0);
new ShapeRef(router, polygon, 4);
// shapeRef5
polygon = Polygon(4);
polygon.ps[0] = Point(501, 345);
polygon.ps[1] = Point(501, 404);
polygon.ps[2] = Point(421, 404);
polygon.ps[3] = Point(421, 345);
ShapeRef *shapeRef5 = new ShapeRef(router, polygon, 5);
new ShapeConnectionPin(shapeRef5, 5, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef5, 6, 0, 0.79096, true, 0, (ConnDirFlags) 4);
new ShapeConnectionPin(shapeRef5, 7, 0, 0.514124, true, 0, (ConnDirFlags) 4);
// shapeRef6
polygon = Polygon(4);
polygon.ps[0] = Point(94, 251.5);
polygon.ps[1] = Point(94, 315.5);
polygon.ps[2] = Point(12, 315.5);
polygon.ps[3] = Point(12, 251.5);
ShapeRef *shapeRef6 = new ShapeRef(router, polygon, 6);
new ShapeConnectionPin(shapeRef6, 8, 1, 0.640625, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef6, 9, 0, 0.640625, true, 0, (ConnDirFlags) 4);
// shapeRef7
polygon = Polygon(4);
polygon.ps[0] = Point(634.366, 262);
polygon.ps[1] = Point(634.366, 305);
polygon.ps[2] = Point(416.366, 305);
polygon.ps[3] = Point(416.366, 262);
ShapeRef *shapeRef7 = new ShapeRef(router, polygon, 7);
new ShapeConnectionPin(shapeRef7, 10, 1, 0.709302, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef7, 11, 0, 0.709302, true, 0, (ConnDirFlags) 4);
// shapeRef8
polygon = Polygon(4);
polygon.ps[0] = Point(324, 147.167);
polygon.ps[1] = Point(324, 206.167);
polygon.ps[2] = Point(236, 206.167);
polygon.ps[3] = Point(236, 147.167);
ShapeRef *shapeRef8 = new ShapeRef(router, polygon, 8);
new ShapeConnectionPin(shapeRef8, 12, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef8, 13, 0, 0.79096, true, 0, (ConnDirFlags) 4);
new ShapeConnectionPin(shapeRef8, 14, 0, 0.514124, true, 0, (ConnDirFlags) 4);
// shapeRef9
polygon = Polygon(4);
polygon.ps[0] = Point(816, 353.167);
polygon.ps[1] = Point(816, 412.167);
polygon.ps[2] = Point(735, 412.167);
polygon.ps[3] = Point(735, 353.167);
ShapeRef *shapeRef9 = new ShapeRef(router, polygon, 9);
new ShapeConnectionPin(shapeRef9, 15, 1, 0.514124, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef9, 16, 1, 0.79096, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef9, 17, 0, 0.79096, true, 0, (ConnDirFlags) 4);
new ShapeConnectionPin(shapeRef9, 18, 0, 0.514124, true, 0, (ConnDirFlags) 4);
// shapeRef10
polygon = Polygon(4);
polygon.ps[0] = Point(981, 263.833);
polygon.ps[1] = Point(981, 321.833);
polygon.ps[2] = Point(828, 321.833);
polygon.ps[3] = Point(828, 263.833);
ShapeRef *shapeRef10 = new ShapeRef(router, polygon, 10);
new ShapeConnectionPin(shapeRef10, 19, 0, 0.655172, true, 0, (ConnDirFlags) 4);
// shapeRef11
polygon = Polygon(4);
polygon.ps[0] = Point(1011.49, 361.833);
polygon.ps[1] = Point(1011.49, 419.833);
polygon.ps[2] = Point(834.489, 419.833);
polygon.ps[3] = Point(834.489, 361.833);
ShapeRef *shapeRef11 = new ShapeRef(router, polygon, 11);
new ShapeConnectionPin(shapeRef11, 20, 0, 0.655172, true, 0, (ConnDirFlags) 4);
// shapeRef12
polygon = Polygon(4);
polygon.ps[0] = Point(511, 155.333);
polygon.ps[1] = Point(511, 214.333);
polygon.ps[2] = Point(422, 214.333);
polygon.ps[3] = Point(422, 155.333);
ShapeRef *shapeRef12 = new ShapeRef(router, polygon, 12);
new ShapeConnectionPin(shapeRef12, 21, 1, 0.514124, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef12, 22, 1, 0.79096, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef12, 23, 0, 0.79096, true, 0, (ConnDirFlags) 4);
new ShapeConnectionPin(shapeRef12, 24, 0, 0.514124, true, 0, (ConnDirFlags) 4);
// shapeRef13
polygon = Polygon(4);
polygon.ps[0] = Point(690, 66);
polygon.ps[1] = Point(690, 124);
polygon.ps[2] = Point(523, 124);
polygon.ps[3] = Point(523, 66);
ShapeRef *shapeRef13 = new ShapeRef(router, polygon, 13);
new ShapeConnectionPin(shapeRef13, 25, 0, 0.655172, true, 0, (ConnDirFlags) 4);
// shapeRef14
polygon = Polygon(4);
polygon.ps[0] = Point(720.212, 164);
polygon.ps[1] = Point(720.212, 222);
polygon.ps[2] = Point(529.212, 222);
polygon.ps[3] = Point(529.212, 164);
ShapeRef *shapeRef14 = new ShapeRef(router, polygon, 14);
new ShapeConnectionPin(shapeRef14, 26, 0, 0.655172, true, 0, (ConnDirFlags) 4);
// shapeRef15
polygon = Polygon(4);
polygon.ps[0] = Point(217, 336.833);
polygon.ps[1] = Point(217, 395.833);
polygon.ps[2] = Point(98, 395.833);
polygon.ps[3] = Point(98, 336.833);
ShapeRef *shapeRef15 = new ShapeRef(router, polygon, 15);
new ShapeConnectionPin(shapeRef15, 27, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef15, 28, 0, 0.652542, true, 0, (ConnDirFlags) 4);
// shapeRef16
polygon = Polygon(4);
polygon.ps[0] = Point(413, 147.167);
polygon.ps[1] = Point(413, 206.167);
polygon.ps[2] = Point(336, 206.167);
polygon.ps[3] = Point(336, 147.167);
ShapeRef *shapeRef16 = new ShapeRef(router, polygon, 16);
new ShapeConnectionPin(shapeRef16, 29, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef16, 30, 0, 0.652542, true, 0, (ConnDirFlags) 4);
// shapeRef17
polygon = Polygon(4);
polygon.ps[0] = Point(306, 336.833);
polygon.ps[1] = Point(306, 395.833);
polygon.ps[2] = Point(229, 395.833);
polygon.ps[3] = Point(229, 336.833);
ShapeRef *shapeRef17 = new ShapeRef(router, polygon, 17);
new ShapeConnectionPin(shapeRef17, 31, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef17, 32, 0, 0.652542, true, 0, (ConnDirFlags) 4);
// shapeRef18
polygon = Polygon(4);
polygon.ps[0] = Point(175, 139);
polygon.ps[1] = Point(175, 198);
polygon.ps[2] = Point(98, 198);
polygon.ps[3] = Point(98, 139);
ShapeRef *shapeRef18 = new ShapeRef(router, polygon, 18);
new ShapeConnectionPin(shapeRef18, 33, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef18, 34, 0, 0.652542, true, 0, (ConnDirFlags) 4);
// shapeRef19
polygon = Polygon(4);
polygon.ps[0] = Point(409, 399.333);
polygon.ps[1] = Point(409, 458.333);
polygon.ps[2] = Point(298, 458.333);
polygon.ps[3] = Point(298, 399.333);
ShapeRef *shapeRef19 = new ShapeRef(router, polygon, 19);
new ShapeConnectionPin(shapeRef19, 35, 1, 0.652542, true, 0, (ConnDirFlags) 8);
// shapeRef20
polygon = Polygon(4);
polygon.ps[0] = Point(224, 40);
polygon.ps[1] = Point(224, 99);
polygon.ps[2] = Point(106, 99);
polygon.ps[3] = Point(106, 40);
ShapeRef *shapeRef20 = new ShapeRef(router, polygon, 20);
new ShapeConnectionPin(shapeRef20, 36, 1, 0.652542, true, 0, (ConnDirFlags) 8);
// shapeRef21
polygon = Polygon(4);
polygon.ps[0] = Point(604, 345);
polygon.ps[1] = Point(604, 404);
polygon.ps[2] = Point(513, 404);
polygon.ps[3] = Point(513, 345);
ShapeRef *shapeRef21 = new ShapeRef(router, polygon, 21);
new ShapeConnectionPin(shapeRef21, 37, 1, 0.652542, true, 0, (ConnDirFlags) 8);
new ShapeConnectionPin(shapeRef21, 38, 0, 0.652542, true, 0, (ConnDirFlags) 4);
// connRef1
connRef = new ConnRef(router, 1);
srcPt = ConnEnd(shapeRef5, 5);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef21, 38);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef2
connRef = new ConnRef(router, 2);
srcPt = ConnEnd(shapeRef6, 8);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef18, 34);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef3
connRef = new ConnRef(router, 3);
srcPt = ConnEnd(shapeRef6, 8);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef15, 28);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef4
connRef = new ConnRef(router, 4);
srcPt = ConnEnd(shapeRef6, 8);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef12, 23);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef5
connRef = new ConnRef(router, 5);
srcPt = ConnEnd(shapeRef6, 8);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef7, 11);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef6
connRef = new ConnRef(router, 6);
srcPt = ConnEnd(shapeRef7, 10);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef9, 17);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
ConnRef *connector6 = connRef;
// connRef7
connRef = new ConnRef(router, 7);
srcPt = ConnEnd(shapeRef8, 12);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef16, 30);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef8
connRef = new ConnRef(router, 8);
srcPt = ConnEnd(shapeRef9, 15);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef10, 19);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef9
connRef = new ConnRef(router, 9);
srcPt = ConnEnd(shapeRef9, 16);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef11, 20);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef10
connRef = new ConnRef(router, 10);
srcPt = ConnEnd(shapeRef12, 21);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef13, 25);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef11
connRef = new ConnRef(router, 11);
srcPt = ConnEnd(shapeRef12, 22);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef14, 26);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef12
connRef = new ConnRef(router, 12);
srcPt = ConnEnd(shapeRef15, 27);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef17, 32);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef13
connRef = new ConnRef(router, 13);
srcPt = ConnEnd(shapeRef16, 29);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef12, 24);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef14
connRef = new ConnRef(router, 14);
srcPt = ConnEnd(shapeRef17, 31);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef5, 7);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef15
connRef = new ConnRef(router, 15);
srcPt = ConnEnd(shapeRef18, 33);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef8, 14);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef16
connRef = new ConnRef(router, 16);
srcPt = ConnEnd(shapeRef19, 35);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef5, 7);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef17
connRef = new ConnRef(router, 17);
srcPt = ConnEnd(shapeRef20, 36);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef8, 14);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
// connRef18
connRef = new ConnRef(router, 18);
srcPt = ConnEnd(shapeRef21, 37);
connRef->setSourceEndpoint(srcPt);
dstPt = ConnEnd(shapeRef9, 18);
connRef->setDestEndpoint(dstPt);
connRef->setRoutingType((ConnType)2);
router->processTransaction();
// Test that connector 6 has three segments and doesnt loop right
// around the shapes on the right due to the crossing penalty.
bool suceeds = (connector6->displayRoute().size() == 4);
//router->outputInstanceToSVG("output/forwardFlowingConnectors01");
delete router;
return (suceeds ? 0 : 1);
};
| oliverchang/libavoid | tests/forwardFlowingConnectors01.cpp | C++ | lgpl-2.1 | 14,496 |
export function convertRawMessage(rawMessage, currentThreadID) {
return {
...rawMessage,
date: new Date(rawMessage.timestamp),
isRead: rawMessage.threadID === currentThreadID
};
};
export function getCreatedMessageData(text, currentThreadID) {
var timestamp = Date.now();
return {
id: 'm_' + timestamp,
threadID: currentThreadID,
authorName: 'You',
date: new Date(timestamp),
text: text,
isRead: true,
type: 'message'
};
};
export function getSUSIMessageData(message, currentThreadID) {
var timestamp = Date.now();
let receivedMessage = {
id: 'm_' + timestamp,
threadID: currentThreadID,
authorName: 'SUSI', // hard coded for the example
text: message.text,
response: message.response,
actions: message.actions,
websearchresults: message.websearchresults,
date: new Date(timestamp),
isRead: true,
responseTime: message.responseTime,
type: 'message'
};
return receivedMessage;
}
| DravitLochan/accounts.susi.ai | src/utils/ChatMessageUtils.js | JavaScript | lgpl-2.1 | 986 |
package soot.coffi;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 Clark Verbrugge
* %%
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Instruction subclasses are used to represent parsed bytecode; each bytecode operation has a corresponding subclass of
* Instruction.
* <p>
* Each subclass is derived from one of
* <ul>
* <li>Instruction</li>
* <li>Instruction_noargs (an Instruction with no embedded arguments)</li>
* <li>Instruction_byte (an Instruction with a single byte data argument)</li>
* <li>Instruction_bytevar (a byte argument specifying a local variable)</li>
* <li>Instruction_byteindex (a byte argument specifying a constant pool index)</li>
* <li>Instruction_int (an Instruction with a single short data argument)</li>
* <li>Instruction_intvar (a short argument specifying a local variable)</li>
* <li>Instruction_intindex (a short argument specifying a constant pool index)</li>
* <li>Instruction_intbranch (a short argument specifying a code offset)</li>
* <li>Instruction_longbranch (an int argument specifying a code offset)</li>
* </ul>
*
* @author Clark Verbrugge
* @see Instruction
* @see Instruction_noargs
* @see Instruction_byte
* @see Instruction_bytevar
* @see Instruction_byteindex
* @see Instruction_int
* @see Instruction_intvar
* @see Instruction_intindex
* @see Instruction_intbranch
* @see Instruction_longbranch
* @see Instruction_Unknown
*/
class Instruction_If_icmpge extends Instruction_intbranch {
public Instruction_If_icmpge() {
super((byte) ByteCode.IF_ICMPGE);
name = "if_icmpge";
}
}
| plast-lab/soot | src/main/java/soot/coffi/Instruction_If_icmpge.java | Java | lgpl-2.1 | 2,261 |
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\class QGraphicsSceneIndex
\brief The QGraphicsSceneIndex class provides a base class to implement
a custom indexing algorithm for discovering items in QGraphicsScene.
\since 4.6
\ingroup graphicsview-api
\internal
The QGraphicsSceneIndex class provides a base class to implement
a custom indexing algorithm for discovering items in QGraphicsScene. You
need to subclass it and reimplement addItem, removeItem, estimateItems
and items in order to have an functional indexing.
\sa QGraphicsScene, QGraphicsView
*/
#include "qdebug.h"
#include "qgraphicsscene.h"
#include "qgraphicsitem_p.h"
#include "qgraphicsscene_p.h"
#include "qgraphicswidget.h"
#include "qgraphicssceneindex_p.h"
#include "qgraphicsscenebsptreeindex_p.h"
#ifndef QT_NO_GRAPHICSVIEW
QT_BEGIN_NAMESPACE
class QGraphicsSceneIndexRectIntersector : public QGraphicsSceneIndexIntersector
{
public:
bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
const QTransform &deviceTransform) const
{
QRectF brect = item->boundingRect();
_q_adjustRect(&brect);
// ### Add test for this (without making things slower?)
Q_UNUSED(exposeRect);
bool keep = true;
const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item);
if (itemd->itemIsUntransformable()) {
// Untransformable items; map the scene rect to item coordinates.
const QTransform transform = item->deviceTransform(deviceTransform);
QRectF itemRect = (deviceTransform * transform.inverted()).mapRect(sceneRect);
if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
keep = itemRect.contains(brect) && itemRect != brect;
else
keep = itemRect.intersects(brect);
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
QPainterPath itemPath;
itemPath.addRect(itemRect);
keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode);
}
} else {
Q_ASSERT(!itemd->dirtySceneTransform);
const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly
? brect.translated(itemd->sceneTransform.dx(),
itemd->sceneTransform.dy())
: itemd->sceneTransform.mapRect(brect);
if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
keep = sceneRect != brect && sceneRect.contains(itemSceneBoundingRect);
else
keep = sceneRect.intersects(itemSceneBoundingRect);
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
QPainterPath rectPath;
rectPath.addRect(sceneRect);
if (itemd->sceneTransformTranslateOnly)
rectPath.translate(-itemd->sceneTransform.dx(), -itemd->sceneTransform.dy());
else
rectPath = itemd->sceneTransform.inverted().map(rectPath);
keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, rectPath, mode);
}
}
return keep;
}
QRectF sceneRect;
};
class QGraphicsSceneIndexPointIntersector : public QGraphicsSceneIndexIntersector
{
public:
bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
const QTransform &deviceTransform) const
{
QRectF brect = item->boundingRect();
_q_adjustRect(&brect);
// ### Add test for this (without making things slower?)
Q_UNUSED(exposeRect);
bool keep = false;
const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item);
if (itemd->itemIsUntransformable()) {
// Untransformable items; map the scene point to item coordinates.
const QTransform transform = item->deviceTransform(deviceTransform);
QPointF itemPoint = (deviceTransform * transform.inverted()).map(scenePoint);
keep = brect.contains(itemPoint);
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
QPainterPath pointPath;
pointPath.addRect(QRectF(itemPoint, QSizeF(1, 1)));
keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, pointPath, mode);
}
} else {
Q_ASSERT(!itemd->dirtySceneTransform);
QRectF sceneBoundingRect = itemd->sceneTransformTranslateOnly
? brect.translated(itemd->sceneTransform.dx(),
itemd->sceneTransform.dy())
: itemd->sceneTransform.mapRect(brect);
keep = sceneBoundingRect.intersects(QRectF(scenePoint, QSizeF(1, 1)));
if (keep) {
QPointF p = itemd->sceneTransformTranslateOnly
? QPointF(scenePoint.x() - itemd->sceneTransform.dx(),
scenePoint.y() - itemd->sceneTransform.dy())
: itemd->sceneTransform.inverted().map(scenePoint);
keep = item->contains(p);
}
}
return keep;
}
QPointF scenePoint;
};
class QGraphicsSceneIndexPathIntersector : public QGraphicsSceneIndexIntersector
{
public:
bool intersect(const QGraphicsItem *item, const QRectF &exposeRect, Qt::ItemSelectionMode mode,
const QTransform &deviceTransform) const
{
QRectF brect = item->boundingRect();
_q_adjustRect(&brect);
// ### Add test for this (without making things slower?)
Q_UNUSED(exposeRect);
bool keep = true;
const QGraphicsItemPrivate *itemd = QGraphicsItemPrivate::get(item);
if (itemd->itemIsUntransformable()) {
// Untransformable items; map the scene rect to item coordinates.
const QTransform transform = item->deviceTransform(deviceTransform);
QPainterPath itemPath = (deviceTransform * transform.inverted()).map(scenePath);
if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
keep = itemPath.contains(brect);
else
keep = itemPath.intersects(brect);
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape))
keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode);
} else {
Q_ASSERT(!itemd->dirtySceneTransform);
const QRectF itemSceneBoundingRect = itemd->sceneTransformTranslateOnly
? brect.translated(itemd->sceneTransform.dx(),
itemd->sceneTransform.dy())
: itemd->sceneTransform.mapRect(brect);
if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect)
keep = scenePath.contains(itemSceneBoundingRect);
else
keep = scenePath.intersects(itemSceneBoundingRect);
if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) {
QPainterPath itemPath = itemd->sceneTransformTranslateOnly
? scenePath.translated(-itemd->sceneTransform.dx(),
-itemd->sceneTransform.dy())
: itemd->sceneTransform.inverted().map(scenePath);
keep = QGraphicsSceneIndexPrivate::itemCollidesWithPath(item, itemPath, mode);
}
}
return keep;
}
QPainterPath scenePath;
};
/*!
Constructs a private scene index.
*/
QGraphicsSceneIndexPrivate::QGraphicsSceneIndexPrivate(QGraphicsScene *scene) : scene(scene)
{
pointIntersector = new QGraphicsSceneIndexPointIntersector;
rectIntersector = new QGraphicsSceneIndexRectIntersector;
pathIntersector = new QGraphicsSceneIndexPathIntersector;
}
/*!
Destructor of private scene index.
*/
QGraphicsSceneIndexPrivate::~QGraphicsSceneIndexPrivate()
{
delete pointIntersector;
delete rectIntersector;
delete pathIntersector;
}
/*!
\internal
Checks if item collides with the path and mode, but also checks that if it
doesn't collide, maybe its frame rect will.
*/
bool QGraphicsSceneIndexPrivate::itemCollidesWithPath(const QGraphicsItem *item,
const QPainterPath &path,
Qt::ItemSelectionMode mode)
{
if (item->collidesWithPath(path, mode))
return true;
if (item->isWidget()) {
// Check if this is a window, and if its frame rect collides.
const QGraphicsWidget *widget = static_cast<const QGraphicsWidget *>(item);
if (widget->isWindow()) {
QRectF frameRect = widget->windowFrameRect();
QPainterPath framePath;
framePath.addRect(frameRect);
bool intersects = path.intersects(frameRect);
if (mode == Qt::IntersectsItemShape || mode == Qt::IntersectsItemBoundingRect)
return intersects || path.contains(frameRect.topLeft())
|| framePath.contains(path.elementAt(0));
return !intersects && path.contains(frameRect.topLeft());
}
}
return false;
}
/*!
\internal
This function returns the items in ascending order.
*/
void QGraphicsSceneIndexPrivate::recursive_items_helper(QGraphicsItem *item, QRectF exposeRect,
QGraphicsSceneIndexIntersector *intersector,
QList<QGraphicsItem *> *items,
const QTransform &viewTransform,
Qt::ItemSelectionMode mode,
qreal parentOpacity) const
{
Q_ASSERT(item);
if (!item->d_ptr->visible)
return;
const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
const bool itemIsFullyTransparent = (opacity < 0.0001);
const bool itemHasChildren = !item->d_ptr->children.isEmpty();
if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity()))
return;
// Update the item's scene transform if dirty.
const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable();
const bool wasDirtyParentSceneTransform = item->d_ptr->dirtySceneTransform && !itemIsUntransformable;
if (wasDirtyParentSceneTransform) {
item->d_ptr->updateSceneTransformFromParent();
Q_ASSERT(!item->d_ptr->dirtySceneTransform);
}
const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
bool processItem = !itemIsFullyTransparent;
if (processItem) {
processItem = intersector->intersect(item, exposeRect, mode, viewTransform);
if (!processItem && (!itemHasChildren || itemClipsChildrenToShape)) {
if (wasDirtyParentSceneTransform)
item->d_ptr->invalidateChildrenSceneTransform();
return;
}
} // else we know for sure this item has children we must process.
int i = 0;
if (itemHasChildren) {
// Sort children.
item->d_ptr->ensureSortedChildren();
// Clip to shape.
if (itemClipsChildrenToShape && !itemIsUntransformable) {
QPainterPath mappedShape = item->d_ptr->sceneTransformTranslateOnly
? item->shape().translated(item->d_ptr->sceneTransform.dx(),
item->d_ptr->sceneTransform.dy())
: item->d_ptr->sceneTransform.map(item->shape());
exposeRect &= mappedShape.controlPointRect();
}
// Process children behind
for (i = 0; i < item->d_ptr->children.size(); ++i) {
QGraphicsItem *child = item->d_ptr->children.at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
break;
if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
continue;
recursive_items_helper(child, exposeRect, intersector, items, viewTransform,
mode, opacity);
}
}
// Process item
if (processItem)
items->append(item);
// Process children in front
if (itemHasChildren) {
for (; i < item->d_ptr->children.size(); ++i) {
QGraphicsItem *child = item->d_ptr->children.at(i);
if (wasDirtyParentSceneTransform)
child->d_ptr->dirtySceneTransform = 1;
if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
continue;
recursive_items_helper(child, exposeRect, intersector, items, viewTransform,
mode, opacity);
}
}
}
void QGraphicsSceneIndexPrivate::init()
{
if (!scene)
return;
QObject::connect(scene, SIGNAL(sceneRectChanged(QRectF)),
q_func(), SLOT(updateSceneRect(QRectF)));
}
/*!
Constructs an abstract scene index for a given \a scene.
*/
QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsScene *scene)
: QObject(*new QGraphicsSceneIndexPrivate(scene), scene)
{
d_func()->init();
}
/*!
\internal
*/
QGraphicsSceneIndex::QGraphicsSceneIndex(QGraphicsSceneIndexPrivate &dd, QGraphicsScene *scene)
: QObject(dd, scene)
{
d_func()->init();
}
/*!
Destroys the scene index.
*/
QGraphicsSceneIndex::~QGraphicsSceneIndex()
{
}
/*!
Returns the scene of this index.
*/
QGraphicsScene* QGraphicsSceneIndex::scene() const
{
Q_D(const QGraphicsSceneIndex);
return d->scene;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos,
Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform
&deviceTransform) const
Returns all visible items that, depending on \a mode, are at the specified
\a pos and return a list sorted using \a order.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with \a pos are returned.
\a deviceTransform is the transformation apply to the view.
This method use the estimation of the index (estimateItems) and refine the
list to get an exact result. If you want to implement your own refinement
algorithm you can reimplement this method.
\sa estimateItems()
*/
QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPointF &pos, Qt::ItemSelectionMode mode,
Qt::SortOrder order, const QTransform &deviceTransform) const
{
Q_D(const QGraphicsSceneIndex);
QList<QGraphicsItem *> itemList;
d->pointIntersector->scenePoint = pos;
d->items_helper(QRectF(pos, QSizeF(1, 1)), d->pointIntersector, &itemList, deviceTransform, mode, order);
return itemList;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect,
Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform
&deviceTransform) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a rect and return a list sorted using \a order.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a rect are returned.
\a deviceTransform is the transformation apply to the view.
This method use the estimation of the index (estimateItems) and refine
the list to get an exact result. If you want to implement your own
refinement algorithm you can reimplement this method.
\sa estimateItems()
*/
QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QRectF &rect, Qt::ItemSelectionMode mode,
Qt::SortOrder order, const QTransform &deviceTransform) const
{
Q_D(const QGraphicsSceneIndex);
QRectF exposeRect = rect;
_q_adjustRect(&exposeRect);
QList<QGraphicsItem *> itemList;
d->rectIntersector->sceneRect = rect;
d->items_helper(exposeRect, d->rectIntersector, &itemList, deviceTransform, mode, order);
return itemList;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF
&polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const
QTransform &deviceTransform) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a polygon and return a list sorted using \a order.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a polygon are returned.
\a deviceTransform is the transformation apply to the view.
This method use the estimation of the index (estimateItems) and refine
the list to get an exact result. If you want to implement your own
refinement algorithm you can reimplement this method.
\sa estimateItems()
*/
QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode,
Qt::SortOrder order, const QTransform &deviceTransform) const
{
Q_D(const QGraphicsSceneIndex);
QList<QGraphicsItem *> itemList;
QRectF exposeRect = polygon.boundingRect();
_q_adjustRect(&exposeRect);
QPainterPath path;
path.addPolygon(polygon);
d->pathIntersector->scenePath = path;
d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order);
return itemList;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath
&path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform
&deviceTransform) const
\overload
Returns all visible items that, depending on \a mode, are either inside or
intersect with the specified \a path and return a list sorted using \a order.
The default value for \a mode is Qt::IntersectsItemShape; all items whose
exact shape intersects with or is contained by \a path are returned.
\a deviceTransform is the transformation apply to the view.
This method use the estimation of the index (estimateItems) and refine
the list to get an exact result. If you want to implement your own
refinement algorithm you can reimplement this method.
\sa estimateItems()
*/
QList<QGraphicsItem *> QGraphicsSceneIndex::items(const QPainterPath &path, Qt::ItemSelectionMode mode,
Qt::SortOrder order, const QTransform &deviceTransform) const
{
Q_D(const QGraphicsSceneIndex);
QList<QGraphicsItem *> itemList;
QRectF exposeRect = path.controlPointRect();
_q_adjustRect(&exposeRect);
d->pathIntersector->scenePath = path;
d->items_helper(exposeRect, d->pathIntersector, &itemList, deviceTransform, mode, order);
return itemList;
}
/*!
This virtual function return an estimation of items at position \a point.
This method return a list sorted using \a order.
*/
QList<QGraphicsItem *> QGraphicsSceneIndex::estimateItems(const QPointF &point, Qt::SortOrder order) const
{
return estimateItems(QRectF(point, QSize(1, 1)), order);
}
QList<QGraphicsItem *> QGraphicsSceneIndex::estimateTopLevelItems(const QRectF &rect, Qt::SortOrder order) const
{
Q_D(const QGraphicsSceneIndex);
Q_UNUSED(rect);
QGraphicsScenePrivate *scened = d->scene->d_func();
scened->ensureSortedTopLevelItems();
if (order == Qt::DescendingOrder) {
QList<QGraphicsItem *> sorted;
for (int i = scened->topLevelItems.size() - 1; i >= 0; --i)
sorted << scened->topLevelItems.at(i);
return sorted;
}
return scened->topLevelItems;
}
/*!
\fn QList<QGraphicsItem *> QGraphicsSceneIndex::items(Qt::SortOrder order = Qt::DescendingOrder) const
This pure virtual function all items in the index and sort them using
\a order.
*/
/*!
Notifies the index that the scene's scene rect has changed. \a rect
is thew new scene rect.
\sa QGraphicsScene::sceneRect()
*/
void QGraphicsSceneIndex::updateSceneRect(const QRectF &rect)
{
Q_UNUSED(rect);
}
/*!
This virtual function removes all items in the scene index.
*/
void QGraphicsSceneIndex::clear()
{
const QList<QGraphicsItem *> allItems = items();
for (int i = 0 ; i < allItems.size(); ++i)
removeItem(allItems.at(i));
}
/*!
\fn virtual void QGraphicsSceneIndex::addItem(QGraphicsItem *item) = 0
This pure virtual function inserts an \a item to the scene index.
\sa removeItem(), deleteItem()
*/
/*!
\fn virtual void QGraphicsSceneIndex::removeItem(QGraphicsItem *item) = 0
This pure virtual function removes an \a item to the scene index.
\sa addItem(), deleteItem()
*/
/*!
This method is called when an \a item has been deleted.
The default implementation call removeItem. Be carefull,
if your implementation of removeItem use pure virtual method
of QGraphicsItem like boundingRect(), then you should reimplement
this method.
\sa addItem(), removeItem()
*/
void QGraphicsSceneIndex::deleteItem(QGraphicsItem *item)
{
removeItem(item);
}
/*!
This virtual function is called by QGraphicsItem to notify the index
that some part of the \a item 's state changes. By reimplementing this
function, your can react to a change, and in some cases, (depending on \a
change,) adjustments in the index can be made.
\a change is the parameter of the item that is changing. \a value is the
value that changed; the type of the value depends on \a change.
The default implementation does nothing.
\sa QGraphicsItem::GraphicsItemChange
*/
void QGraphicsSceneIndex::itemChange(const QGraphicsItem *item, QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
Q_UNUSED(item);
Q_UNUSED(change);
Q_UNUSED(value);
}
/*!
Notify the index for a geometry change of an \a item.
\sa QGraphicsItem::prepareGeometryChange()
*/
void QGraphicsSceneIndex::prepareBoundingRectChange(const QGraphicsItem *item)
{
Q_UNUSED(item);
}
QT_END_NAMESPACE
#include "moc_qgraphicssceneindex_p.cpp"
#endif // QT_NO_GRAPHICSVIEW
| radekp/qt | src/gui/graphicsview/qgraphicssceneindex.cpp | C++ | lgpl-2.1 | 24,608 |
package train.client.render.models;
import net.minecraft.client.model.ModelBase;
import net.minecraft.entity.Entity;
import train.client.render.CustomModelRenderer;
import train.common.core.handlers.ConfigHandler;
public class ModelFreightWagenDB extends ModelBase {
public ModelFreightWagenDB() {
box = new CustomModelRenderer(70, 25, 256, 128);
box.addBox(0F, 0F, 0F, 8, 4, 4);
box.setPosition(-5F, 2F, 0F);
box0 = new CustomModelRenderer(3, 27, 256, 128);
box0.addBox(0F, 0F, 0F, 14, 5, 1);
box0.setPosition(-23F, 1F, -6F);
box1 = new CustomModelRenderer(189, 12, 256, 128);
box1.addBox(0F, 0F, 0F, 8, 7, 0);
box1.setPosition(-20F, 0F, 5F);
box10 = new CustomModelRenderer(213, 80, 256, 128);
box10.addBox(0F, 0F, 0F, 1, 5, 16);
box10.setPosition(27F, 6F, -8F);
box11 = new CustomModelRenderer(158, 77, 256, 128);
box11.addBox(0F, 0F, 0F, 2, 3, 4);
box11.setPosition(28F, 6F, -2F);
box12 = new CustomModelRenderer(159, 87, 256, 128);
box12.addBox(0F, 0F, 0F, 14, 17, 24);
box12.setPosition(-7F, 8F, -12F);
box13 = new CustomModelRenderer(0, 46, 256, 128);
box13.addBox(0F, -2F, 0F, 54, 2, 6);
box13.setPosition(-27F, 32F, -3F);
box14 = new CustomModelRenderer(73, 69, 256, 128);
box14.addBox(0F, 0F, 0F, 28, 2, 1);
box14.setPosition(-19F, 25F, 11F);
box15 = new CustomModelRenderer(0, 0, 256, 128);
box15.addBox(0F, 0F, 0F, 1, 8, 1);
box15.setPosition(5F, 2F, -8F);
box15.rotateAngleX = -6.1086523819801535F;
box16 = new CustomModelRenderer(1, 55, 256, 128);
box16.addBox(0F, -2F, 0F, 54, 2, 5);
box16.setPosition(-27F, 32F, 3F);
box16.rotateAngleX = -6.09119908946021F;
box17 = new CustomModelRenderer(1, 38, 256, 128);
box17.addBox(0F, -2F, 0F, 54, 2, 5);
box17.setPosition(-27F, 31F, 8F);
box17.rotateAngleX = -5.480333851262195F;
box18 = new CustomModelRenderer(1, 55, 256, 128);
box18.addBox(0F, -2F, 0F, 54, 2, 5);
box18.setPosition(27F, 32F, -3F);
box18.rotateAngleX = -6.09119908946021F;
box18.rotateAngleY = -3.141592653589793F;
box19 = new CustomModelRenderer(1, 38, 256, 128);
box19.addBox(0F, -2F, 0F, 54, 2, 5);
box19.setPosition(27F, 31F, -8F);
box19.rotateAngleX = -5.480333851262195F;
box19.rotateAngleY = -3.141592653589793F;
box2 = new CustomModelRenderer(96, 1, 256, 128);
box2.addBox(0F, 0F, 0F, 2, 2, 14);
box2.setPosition(15F, 2F, -7F);
box20 = new CustomModelRenderer(187, 66, 256, 128);
box20.addBox(0F, 0F, 0F, 1, 5, 16);
box20.setPosition(-28F, 6F, -8F);
box21 = new CustomModelRenderer(73, 69, 256, 128);
box21.addBox(0F, 0F, 0F, 28, 2, 1);
box21.setPosition(-9F, 25F, -12F);
box22 = new CustomModelRenderer(0, 65, 256, 128);
box22.addBox(0F, 0F, 0F, 1, 20, 1);
box22.setPosition(-28F, 11F, -4F);
box23 = new CustomModelRenderer(0, 65, 256, 128);
box23.addBox(0F, 0F, 0F, 1, 20, 1);
box23.setPosition(-28F, 11F, 3F);
box24 = new CustomModelRenderer(0, 83, 256, 128);
box24.addBox(0F, 0F, 0F, 54, 23, 22);
box24.setPosition(-27F, 8F, -11F);
box25 = new CustomModelRenderer(146, 80, 256, 128);
box25.addBox(0F, 0F, 0F, 1, 3, 3);
box25.setPosition(28F, 7F, -7F);
box26 = new CustomModelRenderer(104, 42, 256, 128);
box26.addBox(0F, 0F, 0F, 54, 2, 22);
box26.setPosition(-27F, 6F, -11F);
box27 = new CustomModelRenderer(134, 92, 256, 128);
box27.addBox(0F, 0F, 0F, 14, 1, 3);
box27.setPosition(-7F, 2F, -10F);
box28 = new CustomModelRenderer(0, 65, 256, 128);
box28.addBox(0F, 0F, 0F, 1, 20, 1);
box28.setPosition(27F, 11F, -4F);
box29 = new CustomModelRenderer(0, 65, 256, 128);
box29.addBox(0F, 0F, 0F, 1, 20, 1);
box29.setPosition(27F, 11F, 3F);
box3 = new CustomModelRenderer(96, 1, 256, 128);
box3.addBox(0F, 0F, 0F, 2, 2, 14);
box3.setPosition(-17F, 2F, -7F);
box30 = new CustomModelRenderer(73, 74, 256, 128);
box30.addBox(0F, 0F, 0F, 12, 1, 1);
box30.setPosition(7F, 8F, -12F);
box31 = new CustomModelRenderer(73, 74, 256, 128);
box31.addBox(0F, 0F, 0F, 12, 1, 1);
box31.setPosition(-19F, 8F, 11F);
box35 = new CustomModelRenderer(189, 12, 256, 128);
box35.addBox(0F, 0F, 0F, 8, 7, 0);
box35.setPosition(12F, 0F, 5F);
box36 = new CustomModelRenderer(134, 92, 256, 128);
box36.addBox(0F, 0F, 0F, 14, 1, 3);
box36.setPosition(-7F, 2F, 7F);
box38 = new CustomModelRenderer(146, 80, 256, 128);
box38.addBox(0F, 0F, 0F, 1, 3, 3);
box38.setPosition(28F, 7F, 4F);
box4 = new CustomModelRenderer(36, 27, 256, 128);
box4.addBox(0F, 0F, 0F, 14, 5, 1);
box4.setPosition(-23F, 1F, 5F);
box40 = new CustomModelRenderer(138, 80, 256, 128);
box40.addBox(0F, 0F, 0F, 1, 3, 3);
box40.setPosition(-29F, 7F, -7F);
box42 = new CustomModelRenderer(138, 80, 256, 128);
box42.addBox(0F, 0F, 0F, 1, 3, 3);
box42.setPosition(-29F, 7F, 4F);
box44 = new CustomModelRenderer(158, 77, 256, 128);
box44.addBox(0F, 0F, 0F, 2, 3, 4);
box44.setPosition(-30F, 6F, -2F);
box46 = new CustomModelRenderer(0, 0, 256, 128);
box46.addBox(0F, 0F, 0F, 1, 8, 1);
box46.setPosition(-5F, 2F, 8F);
box46.rotateAngleX = -6.1086523819801535F;
box46.rotateAngleY = -3.141592653589793F;
box5 = new CustomModelRenderer(189, 12, 256, 128);
box5.addBox(0F, 0F, 0F, 8, 7, 0);
box5.setPosition(12F, 0F, -5F);
box55 = new CustomModelRenderer(0, 0, 256, 128);
box55.addBox(0F, 0F, 0F, 1, 8, 1);
box55.setPosition(6F, 2F, 8F);
box55.rotateAngleX = -6.1086523819801535F;
box55.rotateAngleY = -3.141592653589793F;
box6 = new CustomModelRenderer(36, 27, 256, 128);
box6.addBox(0F, 0F, 0F, 14, 5, 1);
box6.setPosition(9F, 1F, 5F);
box63 = new CustomModelRenderer(189, 12, 256, 128);
box63.addBox(0F, 0F, 0F, 8, 7, 0);
box63.setPosition(-20F, 0F, -5F);
box7 = new CustomModelRenderer(0, 0, 256, 128);
box7.addBox(0F, 0F, 0F, 1, 8, 1);
box7.setPosition(-6F, 2F, -8F);
box7.rotateAngleX = -6.1086523819801535F;
box8 = new CustomModelRenderer(3, 27, 256, 128);
box8.addBox(0F, 0F, 0F, 14, 5, 1);
box8.setPosition(9F, 1F, -6F);
box9 = new CustomModelRenderer(118, 21, 256, 128);
box9.addBox(0F, 0F, 0F, 54, 3, 14);
box9.setPosition(-27F, 6F, -7F);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
if (ConfigHandler.FLICKERING) {
super.render(entity, f, f1, f2, f3, f4, f5);
}
box.render(f5);
box0.render(f5);
box1.render(f5);
box10.render(f5);
box11.render(f5);
box12.render(f5);
box13.render(f5);
box14.render(f5);
box15.render(f5);
box16.render(f5);
box17.render(f5);
box18.render(f5);
box19.render(f5);
box2.render(f5);
box20.render(f5);
box21.render(f5);
box22.render(f5);
box23.render(f5);
box24.render(f5);
box25.render(f5);
box26.render(f5);
box27.render(f5);
box28.render(f5);
box29.render(f5);
box3.render(f5);
box30.render(f5);
box31.render(f5);
box35.render(f5);
box36.render(f5);
box38.render(f5);
box4.render(f5);
box40.render(f5);
box42.render(f5);
box44.render(f5);
box46.render(f5);
box5.render(f5);
box55.render(f5);
box6.render(f5);
box63.render(f5);
box7.render(f5);
box8.render(f5);
box9.render(f5);
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5) {}
public CustomModelRenderer box;
public CustomModelRenderer box0;
public CustomModelRenderer box1;
public CustomModelRenderer box10;
public CustomModelRenderer box11;
public CustomModelRenderer box12;
public CustomModelRenderer box13;
public CustomModelRenderer box14;
public CustomModelRenderer box15;
public CustomModelRenderer box16;
public CustomModelRenderer box17;
public CustomModelRenderer box18;
public CustomModelRenderer box19;
public CustomModelRenderer box2;
public CustomModelRenderer box20;
public CustomModelRenderer box21;
public CustomModelRenderer box22;
public CustomModelRenderer box23;
public CustomModelRenderer box24;
public CustomModelRenderer box25;
public CustomModelRenderer box26;
public CustomModelRenderer box27;
public CustomModelRenderer box28;
public CustomModelRenderer box29;
public CustomModelRenderer box3;
public CustomModelRenderer box30;
public CustomModelRenderer box31;
public CustomModelRenderer box35;
public CustomModelRenderer box36;
public CustomModelRenderer box38;
public CustomModelRenderer box4;
public CustomModelRenderer box40;
public CustomModelRenderer box42;
public CustomModelRenderer box44;
public CustomModelRenderer box46;
public CustomModelRenderer box5;
public CustomModelRenderer box55;
public CustomModelRenderer box6;
public CustomModelRenderer box63;
public CustomModelRenderer box7;
public CustomModelRenderer box8;
public CustomModelRenderer box9;
}
| BlesseNtumble/Traincraft-5 | src/main/java/train/client/render/models/ModelFreightWagenDB.java | Java | lgpl-2.1 | 8,722 |
/*
TerraLib - a library for developing GIS applications.
Copyright 2001, 2002, 2003 INPE and Tecgraf/PUC-Rio.
This code is part of the TerraLib library.
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.
You should have received a copy of the GNU Lesser General Public
License along with this library.
The authors reassure the license terms regarding the warranties.
They specifically disclaim any warranties, including, but not limited to,
the implied warranties of merchantability and fitness for a particular
purpose. The library provided hereunder is on an "as is" basis, and the
authors have no obligation to provide maintenance, support, updates,
enhancements, or modifications.
In no event shall INPE be held liable to any party
for direct, indirect, special, incidental, or consequential damages arising
out of the use of this library and its documentation.
*/
#ifndef TEPDIPRINCIPALCOMPONENTSFUSION_HPP
#define TEPDIPRINCIPALCOMPONENTSFUSION_HPP
#include "TePDIAlgorithm.hpp"
/**
* @brief This is the class for principal components generation.
* @author Felipe Castro da Silva <felipe@dpi.inpe.br>
* @ingroup PDIFusionAlgorithms
*
* @note The required parameters are:
*
* @param input_rasters (TePDITypes::TePDIRasterVectorType) - Low resolution rasters.
* @param bands (std::vector< int >) - The bands from each low resolution raster.
* @param output_raster (TePDITypes::TePDIRasterPtrType) - High resolution fused raster.
* @param reference_raster (TePDITypes::TePDIRasterPtrType) - High resolution raster.
* @param reference_raster_band (int) - Reference raster band number.
* @param resampling_type (TePDIInterpolator::InterpMethod) -
* Resampling type.
* @param fit_histogram (bool) - Fit the reference histogram to the
* low resolution rasters histograms (better collor quality).
*
* @note The optional parameters are:
*
* @param output_rasters (TePDITypes::TePDIRasterVectorType) - High resolution fused rasters, each one represents one band/channel, if this parameter is set the output_raster parameter will be ignored.
*
*/
class PDI_DLL TePDIPrincipalComponentsFusion : public TePDIAlgorithm {
public :
/**
* @brief Default Constructor.
*
*/
TePDIPrincipalComponentsFusion();
/**
* @brief Default Destructor
*/
~TePDIPrincipalComponentsFusion();
/**
* @brief Checks if the supplied parameters fits the requirements of each
* PDI algorithm implementation.
*
* @note Error log messages must be generated. No exceptions generated.
*
* @param parameters The parameters to be checked.
* @return true if the parameters are OK. false if not.
*/
bool CheckParameters( const TePDIParameters& parameters ) const;
protected :
/**
* @brief Decide the direction of the analysis based on the analysis_type parameter.
*
* @return true if OK. false on error.
*/
bool RunImplementation();
/**
* @brief Reset the internal state to the initial state.
*
* @param params The new parameters referente at initial state.
*/
void ResetState( const TePDIParameters& params );
};
/** @example TePDIFusion_test.cpp
* Fusion algorithms test.
*/
#endif //TEPDIPRINCIPALCOMPONENTS_HPP
| Universefei/Terralib-analysis | src/terralib/image_processing/TePDIPrincipalComponentsFusion.hpp | C++ | lgpl-2.1 | 3,696 |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaTestNoGcWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Utils.BeginObjectRegister(typeof(XLuaTest.NoGc), L, translator, 0, 5, 5, 5);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "FloatParamMethod", _m_FloatParamMethod);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "Vector3ParamMethod", _m_Vector3ParamMethod);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "StructParamMethod", _m_StructParamMethod);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "EnumParamMethod", _m_EnumParamMethod);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "DecimalParamMethod", _m_DecimalParamMethod);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "a1", _g_get_a1);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "a2", _g_get_a2);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "a3", _g_get_a3);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "a4", _g_get_a4);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "a5", _g_get_a5);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "a1", _s_set_a1);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "a2", _s_set_a2);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "a3", _s_set_a3);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "a4", _s_set_a4);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "a5", _s_set_a5);
Utils.EndObjectRegister(typeof(XLuaTest.NoGc), L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(typeof(XLuaTest.NoGc), L, __CreateInstance, 1, 0, 0);
Utils.RegisterObject(L, translator, Utils.CLS_IDX, "UnderlyingSystemType", typeof(XLuaTest.NoGc));
Utils.EndClassRegister(typeof(XLuaTest.NoGc), L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
if(LuaAPI.lua_gettop(L) == 1)
{
XLuaTest.NoGc __cl_gen_ret = new XLuaTest.NoGc();
translator.Push(L, __cl_gen_ret);
return 1;
}
}
catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLuaTest.NoGc constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_FloatParamMethod(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
try {
{
float p = (float)LuaAPI.lua_tonumber(L, 2);
float __cl_gen_ret = __cl_gen_to_be_invoked.FloatParamMethod( p );
LuaAPI.lua_pushnumber(L, __cl_gen_ret);
return 1;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_Vector3ParamMethod(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
try {
{
UnityEngine.Vector3 p;translator.Get(L, 2, out p);
UnityEngine.Vector3 __cl_gen_ret = __cl_gen_to_be_invoked.Vector3ParamMethod( p );
translator.PushUnityEngineVector3(L, __cl_gen_ret);
return 1;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_StructParamMethod(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
try {
{
XLuaTest.MyStruct p;translator.Get(L, 2, out p);
XLuaTest.MyStruct __cl_gen_ret = __cl_gen_to_be_invoked.StructParamMethod( p );
translator.PushXLuaTestMyStruct(L, __cl_gen_ret);
return 1;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_EnumParamMethod(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
try {
{
XLuaTest.MyEnum p;translator.Get(L, 2, out p);
XLuaTest.MyEnum __cl_gen_ret = __cl_gen_to_be_invoked.EnumParamMethod( p );
translator.PushXLuaTestMyEnum(L, __cl_gen_ret);
return 1;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_DecimalParamMethod(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
try {
{
decimal p;translator.Get(L, 2, out p);
decimal __cl_gen_ret = __cl_gen_to_be_invoked.DecimalParamMethod( p );
translator.PushDecimal(L, __cl_gen_ret);
return 1;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_a1(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
translator.Push(L, __cl_gen_to_be_invoked.a1);
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_a2(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
translator.Push(L, __cl_gen_to_be_invoked.a2);
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_a3(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
translator.Push(L, __cl_gen_to_be_invoked.a3);
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_a4(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
translator.Push(L, __cl_gen_to_be_invoked.a4);
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_a5(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
translator.Push(L, __cl_gen_to_be_invoked.a5);
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_a1(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
__cl_gen_to_be_invoked.a1 = (double[])translator.GetObject(L, 2, typeof(double[]));
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_a2(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
__cl_gen_to_be_invoked.a2 = (UnityEngine.Vector3[])translator.GetObject(L, 2, typeof(UnityEngine.Vector3[]));
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_a3(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
__cl_gen_to_be_invoked.a3 = (XLuaTest.MyStruct[])translator.GetObject(L, 2, typeof(XLuaTest.MyStruct[]));
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_a4(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
__cl_gen_to_be_invoked.a4 = (XLuaTest.MyEnum[])translator.GetObject(L, 2, typeof(XLuaTest.MyEnum[]));
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_a5(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
XLuaTest.NoGc __cl_gen_to_be_invoked = (XLuaTest.NoGc)translator.FastGetCSObj(L, 1);
__cl_gen_to_be_invoked.a5 = (decimal[])translator.GetObject(L, 2, typeof(decimal[]));
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return 0;
}
}
}
| ChangSF/BestSects | Assets/Plugins/XLua/Gen/XLuaTestNoGcWrap.cs | C# | lgpl-3.0 | 13,715 |
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from obspy.core.utcdatetime import UTCDateTime
from matplotlib import gridspec
from pdart.view import stream_from_directory
from obspy import read_inventory
import os
from obspy.core import read
# start_time = UTCDateTime('1971-02-07T00:45:00')
from pdart.diffusion.view_single_seismogram import remove_response
# update 25-08-21
def single_seismogram(title):
# 1969-11-20T22:17:17.7
# onset is 42.4 s Lognonne 2003
onset = UTCDateTime('1969-11-20TT22:17:17.700000Z')
# +42.4
# onset = UTCDateTime('1969-11-20T22:17:700000Z')
start_time = onset - timedelta(minutes=2)
stations = ['S12']
channels = ['MHZ']
end_time = start_time + timedelta(minutes=15)
stream = stream_from_directory(
top_level_dir='/Users/cnunn/lunar_data/PDART_CONTINUOUS_MAIN_TAPES',
start_time=start_time,
stations=stations,
channels=channels,
end_time=end_time)
########
fig = plt.figure(figsize=(15, 4))
gs = gridspec.GridSpec(5, 1, hspace=0.001)
ax0 = plt.subplot(gs[0])
trace_MHZ = stream.select(channel='MHZ')[0]
ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k')
ax0.set_xlim(-2*60, 15*60)
ax0.set_xticks(np.arange(0,15*60,6*50))
ax0.set_xticks(np.arange(-180,15*60,60), minor=True)
ax0.set_title(title, fontsize=20)
ax0.set_yticks(np.arange(480, 560, 20))
# ax0.set_yticks(np.arange(460,580,20), minor=True)
ax0.set_ylim(510-50, 510+50)
ax0.set_ylabel('DU', fontsize=14)
ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"),
fontsize=13, horizontalalignment="left", verticalalignment="top",
xycoords="axes fraction")
xticklabels = (ax0.get_xticklabels())
plt.setp(xticklabels, visible=False)
ax0.tick_params(length=6, width=1, which='minor')
ax0.yaxis.set_label_coords(-0.04, 0.5)
ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16,
xycoords="axes fraction", horizontalalignment='left',
verticalalignment='center')
plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.12)
plt.savefig('Apollo12_LM_impact_XXXX.png')
plt.show()
# def single_seismogram_remove_response_short(title):
#
# # peaked mode
# inv_name = "/Users/cnunn/lunar_data/IRIS_dataless_seed/XA.1969-1977.xml"
# # onset is 42.4 s Lognonne 2003
# onset = UTCDateTime('1969-11-20TT22:17:17.700000Z')
# start_time = onset - timedelta(minutes=2)
# # XXXX
# station = 'S12'
# channel = 'MHZ'
# pre_filt = [0.1, 0.3,0.7,1]
# # end_time = UTCDateTime('1971:02:07T02:35.25')
#
# end_time = onset + timedelta(minutes=60)
#
# # 1969-11-20T22:17:17.7
#
# stream = remove_response_from_seismogram(inv_name=inv_name,
# start_time=start_time,
# station=station,
# channel=channel,
# pre_filt=pre_filt,
# water_level=None,
# end_time=end_time,
# plot=False)
#
# ########
#
# fig = plt.figure(figsize=(15, 4))
# gs = gridspec.GridSpec(1, 1, hspace=0.001)
#
# ax0 = plt.subplot(gs[0])
#
# trace_MHZ = stream.select(channel='MHZ')[0]
# ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k')
# ax0.set_xlim(-2*60, 5*60)
# # print('short')
# ax0.set_xticks(np.arange(0,6*60,6*50),minor=False)
# ax0.set_xticks(np.arange(-180,6*60,60), minor=True)
# ax0.set_title(title, fontsize=20)
#
# # ax0.set_yticks(np.arange(480, 560, 20))
# # ax0.set_yticks(np.arange(460,580,20), minor=True)
# ax0.set_ylim(-1.1e-8, 1.01e-8)
# ax0.set_ylabel('Displacement [m]', fontsize=14)
# ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"),
# fontsize=13, horizontalalignment="left", verticalalignment="top",
# xycoords="axes fraction")
#
# # xticklabels = (ax0.get_xticklabels())
# # plt.setp(xticklabels, visible=False)
#
# ax0.tick_params(length=3, width=1, which='minor')
# ax0.tick_params(length=6, width=1, which='major')
#
# ax0.yaxis.set_label_coords(-0.04, 0.5)
#
# ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16,
# xycoords="axes fraction", horizontalalignment='left',
# verticalalignment='center')
#
# ax0.set_xlabel('Time after impact [s]', fontsize=14)
# ax0.yaxis.set_label_coords(-0.04, 0.5)
#
# plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.12)
# plt.savefig('Apollo12_LM_impact_XXXX.png')
# plt.show()
def single_seismogram_remove_response(title,onset,pick=None):
# peaked mode
inv_name = "/Users/cnunn/lunar_data/IRIS_dataless_seed/XA.1969-1977.xml"
onset = UTCDateTime('1969-11-20TT22:17:17.700000Z')
start_time = onset - timedelta(minutes=2)
# XXXX
station = 'S12'
channel = 'MHZ'
pre_filt = [0.1, 0.3,0.7,1]
# end_time = UTCDateTime('1971:02:07T02:35.25')
end_time = onset + timedelta(minutes=60)
# 1969-11-20T22:17:17.7
# reset the timing
# make a correction
# find actual time of onset
# print(onset.time)
stream = remove_response_from_seismogram(inv_name=inv_name,
start_time=start_time,
station=station,
channel=channel,
pre_filt=pre_filt,
water_level=None,
end_time=end_time,
plot=False)
########
fig = plt.figure(figsize=(15, 4))
gs = gridspec.GridSpec(1, 1, hspace=0.001)
ax0 = plt.subplot(gs[0])
trace_MHZ = stream.select(channel='MHZ')[0]
ax0.plot(times_to_seconds(trace_MHZ.times()), trace_MHZ.data, color='k')
ax0.set_xlim(-2*60, 60*60)
ax0.set_xticks(np.arange(0,61*60,6*50),minor=False)
ax0.set_xticks(np.arange(-180,61*60,60), minor=True)
# pick_markP = pick - onset
# plt.gca().axvline(x=pick_markP,
# color='r', linewidth=2)
ax0.set_title(title, fontsize=20)
# ax0.set_yticks(np.arange(480, 560, 20))
# ax0.set_yticks(np.arange(460,580,20), minor=True)
ax0.set_ylim(-1.1e-8, 1.01e-8)
ax0.set_ylabel('Displacement [m]', fontsize=14)
ax0.annotate(xy=(0.01,0.9), text=onset.strftime("%Y-%m-%d %H:%M:%S"),
fontsize=13, horizontalalignment="left", verticalalignment="top",
xycoords="axes fraction")
# xticklabels = (ax0.get_xticklabels())
# plt.setp(xticklabels, visible=False)
ax0.tick_params(length=3, width=1, which='minor')
ax0.tick_params(length=6, width=1, which='major')
ax0.yaxis.set_label_coords(-0.04, 0.5)
ax0.annotate(xy=(1.01,0.5), text='MHZ', fontsize=16,
xycoords="axes fraction", horizontalalignment='left',
verticalalignment='center')
ax0.set_xlabel('Time after impact [s]', fontsize=14)
ax0.yaxis.set_label_coords(-0.04, 0.5)
ax0.plot(times_to_seconds(trace_MHZ.times()),
times_to_seconds(trace_MHZ.data-trace_MHZ.stats.starttime.timestamp), color='k')
plt.subplots_adjust(left=0.06, right=0.95, top=0.9, bottom=0.13)
plt.savefig('../extra_plots_output/Apollo12_LM_impact_XXXX.png')
plt.show()
# def times_to_minutes(times_in_seconds):
# return ((times_in_seconds / 60) - 2)
# copied from /Users/cnunn/python_packages/pdart/extra_plots/view_response.py
def remove_response_from_seismogram(
inv_name,
start_time,
station,
channel,
pre_filt,
end_time=None,
outfile=None,
output='DISP',
water_level=None,
plot=True):
# read the response file
inv = read_inventory(inv_name)
if end_time is None:
time_interval = timedelta(hours=3)
end_time = start_time + time_interval
# xa.s12..att.1969.324.0.mseed
filename = '%s.%s.*.%s.%s.%03d.0.mseed' % ('xa',station.lower(), channel.lower(),
str(start_time.year), start_time.julday)
filename = os.path.join('/Users/cnunn/lunar_data/PDART_CONTINUOUS_MAIN_TAPES',station.lower(),str(start_time.year),str(start_time.julday),filename)
stream = read(filename)
stream = stream.select(channel=channel)
stream.trim(starttime=start_time, endtime=end_time)
# remove location (ground station)
for tr in stream:
tr.stats.location = ''
# detrend
stream.detrend('linear')
# taper the edges
# if there are gaps in the seismogram - EVERY short trace will be tapered
# this is required to remove the response later
# stream.taper(max_percentage=0.05, type='cosine')
# experiment with tapering? not tapering preserves the overall shape better
# but it may required
# merge the streams
stream.merge()
if stream.count() > 1:
print('Too many streams - exiting')
# find the gaps in the trace
if isinstance(stream[0].data,np.ma.MaskedArray):
mask = np.ma.getmask(stream[0].data)
else:
mask = None
# split the stream, then refill it with zeros on the gaps
stream = stream.split()
stream = stream.merge(fill_value=0)
# for i, n in enumerate(stream[0].times()):
# # print(n)
# stream[0].data[i]=np.sin(2*np.pi*(1/25)*n)
stream.attach_response(inv)
# print('here')
# zero_mean=False - because the trace can be asymmetric - remove the mean ourselves
# do not taper here - it doesn't work well with the masked arrays - often required
# when there are gaps - if necessary taper first
# water level - this probably doesn't have much impact - because we are pre filtering
# stream.remove_response(pre_filt=pre_filt,output="DISP",water_level=30,zero_mean=False,taper=False,plot=True,fig=outfile)
for tr in stream:
remove_response(tr, pre_filt=pre_filt,output=output,water_level=water_level,zero_mean=False,taper=False,plot=plot,fig=outfile)
for tr in stream:
tr.stats.location = 'changed'
if mask is not None:
stream[0].data = np.ma.array(stream[0].data, mask = mask)
print(stream)
return stream
def times_to_seconds(times_in_seconds):
return (times_in_seconds - 120)
if __name__ == "__main__":
# single_seismogram(title='Impact of Apollo 12 Lunar Ascent Module')
onset = UTCDateTime('1969-11-20TT22:17:17.700000Z')
# <pick publicID="smi:nunn19/pick/00001/lognonne03/S12/P">
pick = UTCDateTime('1969-11-20T22:17:42.400000Z')
arrival_time = pick - onset
print(arrival_time)
single_seismogram_remove_response(title='Impact of Apollo 12 Lunar Ascent Module',onset=onset,pick=pick)
# single_seismogram_remove_response_short(title='Impact of Apollo 12 Lunar Ascent Module')
| cerinunn/pdart | extra_plots/plot_seismograms.py | Python | lgpl-3.0 | 10,680 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.application.es;
import com.google.common.net.HostAndPort;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.elasticsearch.core.TimeValue.timeValueSeconds;
public class EsConnectorImpl implements EsConnector {
private static final String ES_USERNAME = "elastic";
private static final Logger LOG = LoggerFactory.getLogger(EsConnectorImpl.class);
private final AtomicReference<RestHighLevelClient> restClient = new AtomicReference<>(null);
private final Set<HostAndPort> hostAndPorts;
private final String searchPassword;
public EsConnectorImpl(Set<HostAndPort> hostAndPorts, @Nullable String searchPassword) {
this.hostAndPorts = hostAndPorts;
this.searchPassword = searchPassword;
}
@Override
public Optional<ClusterHealthStatus> getClusterHealthStatus() {
try {
ClusterHealthResponse healthResponse = getRestHighLevelClient().cluster()
.health(new ClusterHealthRequest().waitForYellowStatus().timeout(timeValueSeconds(30)), RequestOptions.DEFAULT);
return Optional.of(healthResponse.getStatus());
} catch (IOException e) {
LOG.trace("Failed to check health status ", e);
return Optional.empty();
}
}
@Override
public void stop() {
RestHighLevelClient restHighLevelClient = restClient.get();
if (restHighLevelClient != null) {
try {
restHighLevelClient.close();
} catch (IOException e) {
LOG.warn("Error occurred while closing Rest Client", e);
}
}
}
private RestHighLevelClient getRestHighLevelClient() {
RestHighLevelClient res = this.restClient.get();
if (res != null) {
return res;
}
RestHighLevelClient restHighLevelClient = buildRestHighLevelClient();
this.restClient.set(restHighLevelClient);
return restHighLevelClient;
}
private RestHighLevelClient buildRestHighLevelClient() {
HttpHost[] httpHosts = hostAndPorts.stream()
.map(hostAndPort -> new HttpHost(hostAndPort.getHost(), hostAndPort.getPortOrDefault(9001)))
.toArray(HttpHost[]::new);
if (LOG.isDebugEnabled()) {
String addresses = Arrays.stream(httpHosts)
.map(t -> t.getHostName() + ":" + t.getPort())
.collect(Collectors.joining(", "));
LOG.debug("Connected to Elasticsearch node: [{}]", addresses);
}
RestClientBuilder builder = RestClient.builder(httpHosts)
.setHttpClientConfigCallback(httpClientBuilder -> {
if (searchPassword != null) {
BasicCredentialsProvider provider = getBasicCredentialsProvider(searchPassword);
httpClientBuilder.setDefaultCredentialsProvider(provider);
}
return httpClientBuilder;
});
return new RestHighLevelClient(builder);
}
private static BasicCredentialsProvider getBasicCredentialsProvider(String searchPassword) {
BasicCredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ES_USERNAME, searchPassword));
return provider;
}
}
| SonarSource/sonarqube | server/sonar-main/src/main/java/org/sonar/application/es/EsConnectorImpl.java | Java | lgpl-3.0 | 4,727 |
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.wrrl_db_mv.util.gup;
import Sirius.navigator.tools.CacheException;
import Sirius.navigator.tools.MetaObjectCache;
import Sirius.server.middleware.types.MetaClass;
import Sirius.server.middleware.types.MetaObject;
import org.jdesktop.swingx.painter.CompoundPainter;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.painter.RectanglePainter;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import javax.swing.JMenuItem;
import de.cismet.cids.custom.wrrl_db_mv.commons.WRRLUtil;
import de.cismet.cids.custom.wrrl_db_mv.util.CidsBeanSupport;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cids.navigator.utils.ClassCacheMultiple;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class VermeidungsgruppeRWBandMember extends LineBandMember {
//~ Static fields/initializers ---------------------------------------------
private static final MetaClass VERMEIDUNGSGRUPPE = ClassCacheMultiple.getMetaClass(
WRRLUtil.DOMAIN_NAME,
"VERMEIDUNGSGRUPPE");
//~ Instance fields --------------------------------------------------------
private JMenuItem[] menuItems;
//~ Constructors -----------------------------------------------------------
/**
* Creates new form MassnahmenBandMember.
*
* @param parent DOCUMENT ME!
*/
public VermeidungsgruppeRWBandMember(final VermeidungsgruppeRWBand parent) {
super(parent);
lineFieldName = "linie";
}
/**
* Creates new form MassnahmenBandMember.
*
* @param parent DOCUMENT ME!
* @param readOnly DOCUMENT ME!
*/
public VermeidungsgruppeRWBandMember(final VermeidungsgruppeRWBand parent, final boolean readOnly) {
super(parent, readOnly);
lineFieldName = "linie";
}
//~ Methods ----------------------------------------------------------------
@Override
public void setCidsBean(final CidsBean cidsBean) {
super.setCidsBean(cidsBean);
setToolTipText(bean.getProperty("vermeidungsgruppe.name") + "");
}
/**
* DOCUMENT ME!
*/
@Override
protected void determineBackgroundColour() {
if ((bean.getProperty("vermeidungsgruppe") == null) || (bean.getProperty("vermeidungsgruppe.color") == null)) {
setDefaultBackground();
return;
}
final String color = (String)bean.getProperty("vermeidungsgruppe.color");
if (color != null) {
try {
setBackgroundPainter(new MattePainter(Color.decode(color)));
} catch (NumberFormatException e) {
LOG.error("Error while parsing the color.", e);
setDefaultBackground();
}
}
unselectedBackgroundPainter = getBackgroundPainter();
selectedBackgroundPainter = new CompoundPainter(
unselectedBackgroundPainter,
new RectanglePainter(
3,
3,
3,
3,
3,
3,
true,
new Color(100, 100, 100, 100),
2f,
new Color(50, 50, 50, 100)));
setBackgroundPainter(unselectedBackgroundPainter);
}
/**
* DOCUMENT ME!
*
* @param id DOCUMENT ME!
*/
private void setVermeidungsgruppe(final String id) {
try {
final String query = "select " + VERMEIDUNGSGRUPPE.getID() + "," + VERMEIDUNGSGRUPPE.getPrimaryKey()
+ " from "
+ VERMEIDUNGSGRUPPE.getTableName(); // NOI18N
final MetaObject[] metaObjects = MetaObjectCache.getInstance()
.getMetaObjectsByQuery(query, WRRLUtil.DOMAIN_NAME);
CidsBean b = null;
if (metaObjects != null) {
for (final MetaObject tmp : metaObjects) {
if (tmp.getBean().getProperty("id").toString().equals(id)) {
b = tmp.getBean();
break;
}
}
}
bean.setProperty("vermeidungsgruppe", b);
} catch (Exception e) {
LOG.error("Error while setting property massnahme.", e);
}
}
/**
* DOCUMENT ME!
*/
@Override
protected void configurePopupMenu() {
try {
final String query = "select " + VERMEIDUNGSGRUPPE.getID() + "," + VERMEIDUNGSGRUPPE.getPrimaryKey()
+ " from "
+ VERMEIDUNGSGRUPPE.getTableName(); // NOI18N
final MetaObject[] metaObjects = MetaObjectCache.getInstance()
.getMetaObjectsByQuery(query, WRRLUtil.DOMAIN_NAME);
menuItems = new JMenuItem[metaObjects.length];
for (int i = 0; i < metaObjects.length; ++i) {
menuItems[i] = new JMenuItem(metaObjects[i].getBean().toString());
menuItems[i].addActionListener(this);
menuItems[i].setActionCommand(String.valueOf(metaObjects[i].getID()));
popup.add(menuItems[i]);
}
} catch (CacheException e) {
LOG.error("Cache Exception", e);
}
popup.addSeparator();
super.configurePopupMenu();
}
@Override
public void actionPerformed(final ActionEvent e) {
boolean found = false;
for (final JMenuItem tmp : menuItems) {
if (e.getSource() == tmp) {
found = true;
setVermeidungsgruppe(tmp.getActionCommand());
fireBandMemberChanged(false);
break;
}
}
if (!found) {
super.actionPerformed(e);
}
newMode = false;
}
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("vermeidungsgruppe")) {
determineBackgroundColour();
setSelected(isSelected);
setToolTipText(bean.getProperty("vermeidungsgruppe.name") + "");
} else {
super.propertyChange(evt);
}
}
/**
* DOCUMENT ME!
*
* @param bean DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
@Override
protected CidsBean cloneBean(final CidsBean bean) throws Exception {
return CidsBeanSupport.cloneCidsBean(bean, false);
}
}
| cismet/cids-custom-wrrl-db-mv | src/main/java/de/cismet/cids/custom/wrrl_db_mv/util/gup/VermeidungsgruppeRWBandMember.java | Java | lgpl-3.0 | 6,828 |
import {Inject, Injectable} from 'app/app';
import {BootstrapService} from 'services/bootstrap-service';
import {UserService} from 'security/user-service';
import {Eventbus} from 'services/eventbus/eventbus';
import {PersonalMailboxUpdatedEvent} from 'idoc/system-tabs/mailbox/events/personal-mailbox-updated-event';
import {MailboxInfoService} from 'services/rest/mailbox-info-service';
import {PollingUtils} from 'common/polling-utils';
import {Configuration} from 'common/application-config';
@Injectable()
@Inject(Eventbus, MailboxInfoService, UserService, PollingUtils, Configuration)
export class PersonalMailboxInfoObserver extends BootstrapService {
constructor(eventbus, mailboxInfoService, userService, pollingUtils, configuration) {
super();
this.eventbus = eventbus;
this.mailboxInfoService = mailboxInfoService;
this.userService = userService;
this.pollingUtils = pollingUtils;
this.pollingInterval = configuration.get(Configuration.MAILBOX_STATUS_POLL_INTERVAL);
}
initialize() {
this.userService.getCurrentUser().then((response) => {
if (response.mailboxSupportable) {
this.pollingUtils.pollInfinite('personal_mailbox_unread_messages_count', this.handleMessagesStatusUpdate.bind(this), this.pollingInterval, false);
}
});
}
handleMessagesStatusUpdate() {
this.userService.getCurrentUser().then((response) => {
return this.mailboxInfoService.getUnreadMessagesCount(response.emailAddress, {skipInterceptor: true});
}).then((response) => {
this.eventbus.publish(new PersonalMailboxUpdatedEvent(response.data));
});
}
} | SirmaITT/conservation-space-1.7.0 | docker/sep-ui/src/idoc/system-tabs/mailbox/services/personal-mailbox-info-observer/personal-mailbox-info-observer.js | JavaScript | lgpl-3.0 | 1,622 |
/*
* XAdES4j - A Java library for generation and verification of XAdES signatures.
* Copyright (C) 2010 Luis Goncalves.
*
* XAdES4j is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or any later version.
*
* XAdES4j 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 XAdES4j. If not, see <http://www.gnu.org/licenses/>.
*/
package xades4j.production;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.xml.security.signature.*;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Document;
import xades4j.UnsupportedAlgorithmException;
import xades4j.XAdES4jXMLSigException;
import xades4j.algorithms.Algorithm;
import xades4j.properties.DataObjectDesc;
import xades4j.utils.ResolverAnonymous;
import xades4j.utils.TransformUtils;
import xades4j.xml.marshalling.algorithms.AlgorithmsParametersMarshallingProvider;
import javax.inject.Inject;
/**
* Helper class that processes a set of data object descriptions.
*
* @author Luís
*/
final class SignedDataObjectsProcessor
{
static final class Result
{
final Map<DataObjectDesc, Reference> referenceMappings;
final Set<Manifest> manifests;
public Result(Map<DataObjectDesc, Reference> referenceMappings, Set<Manifest> manifests)
{
this.referenceMappings = Collections.unmodifiableMap(referenceMappings);
this.manifests = Collections.unmodifiableSet(manifests);
}
}
private final SignatureAlgorithms signatureAlgorithms;
private final AlgorithmsParametersMarshallingProvider algorithmsParametersMarshaller;
@Inject
SignedDataObjectsProcessor(SignatureAlgorithms signatureAlgorithms, AlgorithmsParametersMarshallingProvider algorithmsParametersMarshaller)
{
this.signatureAlgorithms = signatureAlgorithms;
this.algorithmsParametersMarshaller = algorithmsParametersMarshaller;
}
/**
* Processes the signed data objects and adds the corresponding {@code Reference}s
* and {@code Object}s to the signature. This method must be invoked before
* adding any other {@code Reference}s to the signature.
*
* @return result with reference mappings resulting from the data object descriptions and manifests to be digested
* @throws UnsupportedAlgorithmException if the reference digest algorithm is not supported
* @throws IllegalStateException if the signature already contains {@code Reference}s
* @throws XAdES4jXMLSigException if a Manifest cannot be digested
*/
SignedDataObjectsProcessor.Result process(
SignedDataObjects signedDataObjects,
XMLSignature xmlSignature) throws UnsupportedAlgorithmException, XAdES4jXMLSigException
{
if (xmlSignature.getSignedInfo().getLength() != 0)
{
throw new IllegalStateException("XMLSignature already contains references");
}
return process(
signedDataObjects.getDataObjectsDescs(),
xmlSignature.getSignedInfo(),
xmlSignature.getId(),
signedDataObjects.getResourceResolvers(),
xmlSignature,
false);
}
private SignedDataObjectsProcessor.Result process(
Collection<? extends DataObjectDesc> dataObjects,
Manifest container,
String idPrefix,
List<ResourceResolverSpi> resourceResolvers,
XMLSignature xmlSignature,
boolean hasNullURIReference) throws UnsupportedAlgorithmException, XAdES4jXMLSigException
{
Map<DataObjectDesc, Reference> referenceMappings = new IdentityHashMap<DataObjectDesc, Reference>(dataObjects.size());
Set<Manifest> manifests = new HashSet<Manifest>();
for (ResourceResolverSpi resolver : resourceResolvers)
{
container.addResourceResolver(resolver);
}
String digestMethodUri = this.signatureAlgorithms.getDigestAlgorithmForDataObjectReferences();
/**/
try
{
for (DataObjectDesc dataObjDesc : dataObjects)
{
String refUri, refType;
int index = container.getLength();
if (dataObjDesc instanceof DataObjectReference)
{
// If the data object info is a DataObjectReference, the Reference uri
// and type are the ones specified on the object.
DataObjectReference dataObjRef = (DataObjectReference) dataObjDesc;
refUri = dataObjRef.getUri();
refType = dataObjRef.getType();
}
else if (dataObjDesc instanceof EnvelopedXmlObject)
{
// If the data object info is a EnvelopedXmlObject we need to create a ds:Object to embed it.
// The Reference uri will refer the new ds:Object's id.
EnvelopedXmlObject envXmlObj = (EnvelopedXmlObject) dataObjDesc;
String xmlObjId = String.format("%s-object%d", idPrefix, index);
ObjectContainer xmlObj = new ObjectContainer(container.getDocument());
xmlObj.setId(xmlObjId);
xmlObj.appendChild(envXmlObj.getContent());
xmlObj.setMimeType(envXmlObj.getMimeType());
xmlObj.setEncoding(envXmlObj.getEncoding());
xmlSignature.appendObject(xmlObj);
refUri = '#' + xmlObjId;
refType = Reference.OBJECT_URI;
}
else if (dataObjDesc instanceof AnonymousDataObjectReference)
{
if (hasNullURIReference)
{
// This shouldn't happen because SignedDataObjects does the validation.
throw new IllegalStateException("Multiple AnonymousDataObjectReference detected");
}
hasNullURIReference = true;
refUri = refType = null;
AnonymousDataObjectReference anonymousRef = (AnonymousDataObjectReference) dataObjDesc;
container.addResourceResolver(new ResolverAnonymous(anonymousRef.getDataStream()));
}
else if (dataObjDesc instanceof EnvelopedManifest)
{
// If the data object info is a EnvelopedManifest we need to create a ds:Manifest and a ds:Object
// to embed it. The Reference uri will refer the manifest's id.
EnvelopedManifest envManifest = (EnvelopedManifest) dataObjDesc;
String xmlManifestId = String.format("%s-manifest%d", idPrefix, index);
Manifest xmlManifest = new Manifest(container.getDocument());
xmlManifest.setId(xmlManifestId);
SignedDataObjectsProcessor.Result manifestResult = process(
envManifest.getDataObjects(),
xmlManifest,
xmlManifestId,
resourceResolvers,
xmlSignature,
hasNullURIReference);
ObjectContainer xmlObj = new ObjectContainer(container.getDocument());
xmlObj.appendChild(xmlManifest.getElement());
xmlSignature.appendObject(xmlObj);
manifests.add(xmlManifest);
manifests.addAll(manifestResult.manifests);
refUri = '#' + xmlManifestId;
refType = Reference.MANIFEST_URI;
}
else
{
throw new ClassCastException("Unsupported SignedDataObjectDesc. Must be one of DataObjectReference, EnvelopedXmlObject, EnvelopedManifest and AnonymousDataObjectReference");
}
Transforms transforms = processTransforms(dataObjDesc, container.getDocument());
// Add the Reference. References need an ID because data object properties may refer them.
container.addDocument(
xmlSignature.getBaseURI(),
refUri,
transforms,
digestMethodUri,
String.format("%s-ref%d", idPrefix, index), // id
refType);
// SignedDataObjects and EnvelopedManifest don't allow repeated instances, so there's no
// need to check for duplicate entries on the map.
Reference ref = container.item(index);
referenceMappings.put(dataObjDesc, ref);
}
} catch (XMLSignatureException ex)
{
// -> xmlSignature.appendObject(xmlObj): not thrown when signing.
// -> xmlSignature.addDocument(...): appears to be thrown when the digest
// algorithm is not supported.
throw new UnsupportedAlgorithmException(
"Digest algorithm not supported in the XML Signature provider",
digestMethodUri, ex);
} catch (org.apache.xml.security.exceptions.XMLSecurityException ex)
{
// -> xmlSignature.getSignedInfo().item(...): shouldn't be thrown
// when signing.
throw new IllegalStateException(ex);
}
return new Result(referenceMappings, manifests);
}
private Transforms processTransforms(
DataObjectDesc dataObjDesc,
Document document) throws UnsupportedAlgorithmException
{
Collection<Algorithm> transforms = dataObjDesc.getTransforms();
if (transforms.isEmpty())
{
return null;
}
return TransformUtils.createTransforms(document, this.algorithmsParametersMarshaller, transforms);
}
}
| luisgoncalves/xades4j | src/main/java/xades4j/production/SignedDataObjectsProcessor.java | Java | lgpl-3.0 | 10,850 |
// Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain
import (
"fmt"
)
// DeploymentError identifies an error that indicates a deployment ID was
// specified that does not exist.
type DeploymentError uint32
// Error returns the assertion error as a human-readable string and satisfies
// the error interface.
func (e DeploymentError) Error() string {
return fmt.Sprintf("deployment ID %d does not exist", uint32(e))
}
// AssertError identifies an error that indicates an internal code consistency
// issue and should be treated as a critical and unrecoverable error.
type AssertError string
// Error returns the assertion error as a human-readable string and satisfies
// the error interface.
func (e AssertError) Error() string {
return "assertion failed: " + string(e)
}
// ErrorCode identifies a kind of error.
type ErrorCode int
// These constants are used to identify a specific RuleError.
const (
// ErrDuplicateBlock indicates a block with the same hash already
// exists.
ErrDuplicateBlock ErrorCode = iota
// ErrBlockTooBig indicates the serialized block size exceeds the
// maximum allowed size.
ErrBlockTooBig
// ErrBlockWeightTooHigh indicates that the block's computed weight
// metric exceeds the maximum allowed value.
ErrBlockWeightTooHigh
// ErrBlockVersionTooOld indicates the block version is too old and is
// no longer accepted since the majority of the network has upgraded
// to a newer version.
ErrBlockVersionTooOld
// ErrInvalidTime indicates the time in the passed block has a precision
// that is more than one second. The chain consensus rules require
// timestamps to have a maximum precision of one second.
ErrInvalidTime
// ErrTimeTooOld indicates the time is either before the median time of
// the last several blocks per the chain consensus rules or prior to the
// most recent checkpoint.
ErrTimeTooOld
// ErrTimeTooNew indicates the time is too far in the future as compared
// the current time.
ErrTimeTooNew
// ErrDifficultyTooLow indicates the difficulty for the block is lower
// than the difficulty required by the most recent checkpoint.
ErrDifficultyTooLow
// ErrUnexpectedDifficulty indicates specified bits do not align with
// the expected value either because it doesn't match the calculated
// valued based on difficulty regarted rules or it is out of the valid
// range.
ErrUnexpectedDifficulty
// ErrHighHash indicates the block does not hash to a value which is
// lower than the required target difficultly.
ErrHighHash
// ErrBadMerkleRoot indicates the calculated merkle root does not match
// the expected value.
ErrBadMerkleRoot
// ErrBadCheckpoint indicates a block that is expected to be at a
// checkpoint height does not match the expected one.
ErrBadCheckpoint
// ErrForkTooOld indicates a block is attempting to fork the block chain
// before the most recent checkpoint.
ErrForkTooOld
// ErrCheckpointTimeTooOld indicates a block has a timestamp before the
// most recent checkpoint.
ErrCheckpointTimeTooOld
// ErrNoTransactions indicates the block does not have a least one
// transaction. A valid block must have at least the coinbase
// transaction.
ErrNoTransactions
// ErrTooManyTransactions indicates the block has more transactions than
// are allowed.
ErrTooManyTransactions
// ErrNoTxInputs indicates a transaction does not have any inputs. A
// valid transaction must have at least one input.
ErrNoTxInputs
// ErrNoTxOutputs indicates a transaction does not have any outputs. A
// valid transaction must have at least one output.
ErrNoTxOutputs
// ErrTxTooBig indicates a transaction exceeds the maximum allowed size
// when serialized.
ErrTxTooBig
// ErrBadTxOutValue indicates an output value for a transaction is
// invalid in some way such as being out of range.
ErrBadTxOutValue
// ErrDuplicateTxInputs indicates a transaction references the same
// input more than once.
ErrDuplicateTxInputs
// ErrBadTxInput indicates a transaction input is invalid in some way
// such as referencing a previous transaction outpoint which is out of
// range or not referencing one at all.
ErrBadTxInput
// ErrMissingTxOut indicates a transaction output referenced by an input
// either does not exist or has already been spent.
ErrMissingTxOut
// ErrUnfinalizedTx indicates a transaction has not been finalized.
// A valid block may only contain finalized transactions.
ErrUnfinalizedTx
// ErrDuplicateTx indicates a block contains an identical transaction
// (or at least two transactions which hash to the same value). A
// valid block may only contain unique transactions.
ErrDuplicateTx
// ErrOverwriteTx indicates a block contains a transaction that has
// the same hash as a previous transaction which has not been fully
// spent.
ErrOverwriteTx
// ErrImmatureSpend indicates a transaction is attempting to spend a
// coinbase that has not yet reached the required maturity.
ErrImmatureSpend
// ErrSpendTooHigh indicates a transaction is attempting to spend more
// value than the sum of all of its inputs.
ErrSpendTooHigh
// ErrBadFees indicates the total fees for a block are invalid due to
// exceeding the maximum possible value.
ErrBadFees
// ErrTooManySigOps indicates the total number of signature operations
// for a transaction or block exceed the maximum allowed limits.
ErrTooManySigOps
// ErrFirstTxNotCoinbase indicates the first transaction in a block
// is not a coinbase transaction.
ErrFirstTxNotCoinbase
// ErrMultipleCoinbases indicates a block contains more than one
// coinbase transaction.
ErrMultipleCoinbases
// ErrBadCoinbaseScriptLen indicates the length of the signature script
// for a coinbase transaction is not within the valid range.
ErrBadCoinbaseScriptLen
// ErrBadCoinbaseValue indicates the amount of a coinbase value does
// not match the expected value of the subsidy plus the sum of all fees.
ErrBadCoinbaseValue
// ErrMissingCoinbaseHeight indicates the coinbase transaction for a
// block does not start with the serialized block block height as
// required for version 2 and higher blocks.
ErrMissingCoinbaseHeight
// ErrBadCoinbaseHeight indicates the serialized block height in the
// coinbase transaction for version 2 and higher blocks does not match
// the expected value.
ErrBadCoinbaseHeight
// ErrScriptMalformed indicates a transaction script is malformed in
// some way. For example, it might be longer than the maximum allowed
// length or fail to parse.
ErrScriptMalformed
// ErrScriptValidation indicates the result of executing transaction
// script failed. The error covers any failure when executing scripts
// such signature verification failures and execution past the end of
// the stack.
ErrScriptValidation
// ErrUnexpectedWitness indicates that a block includes transactions
// with witness data, but doesn't also have a witness commitment within
// the coinbase transaction.
ErrUnexpectedWitness
// ErrInvalidWitnessCommitment indicates that a block's witness
// commitment is not well formed.
ErrInvalidWitnessCommitment
// ErrWitnessCommitmentMismatch indicates that the witness commitment
// included in the block's coinbase transaction doesn't match the
// manually computed witness commitment.
ErrWitnessCommitmentMismatch
// ErrPrevBlockNotBest indicates that the block's previous block is not the
// current chain tip. This is not a block validation rule, but is required
// for block proposals submitted via getblocktemplate RPC.
ErrPrevBlockNotBest
)
// Map of ErrorCode values back to their constant names for pretty printing.
var errorCodeStrings = map[ErrorCode]string{
ErrDuplicateBlock: "ErrDuplicateBlock",
ErrBlockTooBig: "ErrBlockTooBig",
ErrBlockVersionTooOld: "ErrBlockVersionTooOld",
ErrBlockWeightTooHigh: "ErrBlockWeightTooHigh",
ErrInvalidTime: "ErrInvalidTime",
ErrTimeTooOld: "ErrTimeTooOld",
ErrTimeTooNew: "ErrTimeTooNew",
ErrDifficultyTooLow: "ErrDifficultyTooLow",
ErrUnexpectedDifficulty: "ErrUnexpectedDifficulty",
ErrHighHash: "ErrHighHash",
ErrBadMerkleRoot: "ErrBadMerkleRoot",
ErrBadCheckpoint: "ErrBadCheckpoint",
ErrForkTooOld: "ErrForkTooOld",
ErrCheckpointTimeTooOld: "ErrCheckpointTimeTooOld",
ErrNoTransactions: "ErrNoTransactions",
ErrTooManyTransactions: "ErrTooManyTransactions",
ErrNoTxInputs: "ErrNoTxInputs",
ErrNoTxOutputs: "ErrNoTxOutputs",
ErrTxTooBig: "ErrTxTooBig",
ErrBadTxOutValue: "ErrBadTxOutValue",
ErrDuplicateTxInputs: "ErrDuplicateTxInputs",
ErrBadTxInput: "ErrBadTxInput",
ErrMissingTxOut: "ErrMissingTxOut",
ErrUnfinalizedTx: "ErrUnfinalizedTx",
ErrDuplicateTx: "ErrDuplicateTx",
ErrOverwriteTx: "ErrOverwriteTx",
ErrImmatureSpend: "ErrImmatureSpend",
ErrSpendTooHigh: "ErrSpendTooHigh",
ErrBadFees: "ErrBadFees",
ErrTooManySigOps: "ErrTooManySigOps",
ErrFirstTxNotCoinbase: "ErrFirstTxNotCoinbase",
ErrMultipleCoinbases: "ErrMultipleCoinbases",
ErrBadCoinbaseScriptLen: "ErrBadCoinbaseScriptLen",
ErrBadCoinbaseValue: "ErrBadCoinbaseValue",
ErrMissingCoinbaseHeight: "ErrMissingCoinbaseHeight",
ErrBadCoinbaseHeight: "ErrBadCoinbaseHeight",
ErrScriptMalformed: "ErrScriptMalformed",
ErrScriptValidation: "ErrScriptValidation",
ErrUnexpectedWitness: "ErrUnexpectedWitness",
ErrInvalidWitnessCommitment: "ErrInvalidWitnessCommitment",
ErrWitnessCommitmentMismatch: "ErrWitnessCommitmentMismatch",
ErrPrevBlockNotBest: "ErrPrevBlockNotBest",
}
// String returns the ErrorCode as a human-readable name.
func (e ErrorCode) String() string {
if s := errorCodeStrings[e]; s != "" {
return s
}
return fmt.Sprintf("Unknown ErrorCode (%d)", int(e))
}
// RuleError identifies a rule violation. It is used to indicate that
// processing of a block or transaction failed due to one of the many validation
// rules. The caller can use type assertions to determine if a failure was
// specifically due to a rule violation and access the ErrorCode field to
// ascertain the specific reason for the rule violation.
type RuleError struct {
ErrorCode ErrorCode // Describes the kind of error
Description string // Human readable description of the issue
}
// Error satisfies the error interface and prints human-readable errors.
func (e RuleError) Error() string {
return e.Description
}
// ruleError creates an RuleError given a set of arguments.
func ruleError(c ErrorCode, desc string) RuleError {
return RuleError{ErrorCode: c, Description: desc}
}
| maichain/listener | vendor/github.com/btcsuite/btcd/blockchain/error.go | GO | lgpl-3.0 | 11,052 |
package net.minecraft.src;
import net.minecraft.server.MinecraftServer;
import java.util.List;
public class CommandServerBanlist extends CommandBase
{
public String getCommandName()
{
return "banlist";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel()
{
return 3;
}
/**
* Returns true if the given command sender is allowed to use this command.
*/
public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender)
{
return (MinecraftServer.getServer().getConfigurationManager().getBannedIPs().isListActive() || MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().isListActive()) && super.canCommandSenderUseCommand(par1ICommandSender);
}
public String getCommandUsage(ICommandSender par1ICommandSender)
{
return "commands.banlist.usage";
}
public void processCommand(ICommandSender par1ICommandSender, String[] par2ArrayOfStr)
{
if (par2ArrayOfStr.length >= 1 && par2ArrayOfStr[0].equalsIgnoreCase("ips"))
{
par1ICommandSender.func_110122_a(ChatMessageComponent.func_111082_b("commands.banlist.ips", new Object[] {Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().getBannedIPs().getBannedList().size())}));
par1ICommandSender.func_110122_a(ChatMessageComponent.func_111066_d(joinNiceString(MinecraftServer.getServer().getConfigurationManager().getBannedIPs().getBannedList().keySet().toArray())));
}
else
{
par1ICommandSender.func_110122_a(ChatMessageComponent.func_111082_b("commands.banlist.players", new Object[] {Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getBannedList().size())}));
par1ICommandSender.func_110122_a(ChatMessageComponent.func_111066_d(joinNiceString(MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getBannedList().keySet().toArray())));
}
}
/**
* Adds the strings available in this command to the given list of tab completion options.
*/
public List addTabCompletionOptions(ICommandSender par1ICommandSender, String[] par2ArrayOfStr)
{
return par2ArrayOfStr.length == 1 ? getListOfStringsMatchingLastWord(par2ArrayOfStr, new String[] {"players", "ips"}): null;
}
}
| Neil5043/Minetweak | src/main/java/net/minecraft/src/CommandServerBanlist.java | Java | lgpl-3.0 | 2,423 |
# Redmine - project management software
# Copyright (C) 2006-2013 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require File.expand_path('../../../test_helper', __FILE__)
class RoutingPreviewsTest < ActionController::IntegrationTest
def test_previews
["get", "post", "put"].each do |method|
assert_routing(
{ :method => method, :path => "/issues/preview/new/123" },
{ :controller => 'previews', :action => 'issue', :project_id => '123' }
)
assert_routing(
{ :method => method, :path => "/issues/preview/edit/321" },
{ :controller => 'previews', :action => 'issue', :id => '321' }
)
end
assert_routing(
{ :method => 'get', :path => "/news/preview" },
{ :controller => 'previews', :action => 'news' }
)
end
end
| HuaiJiang/pjm | test/integration/routing/previews_test.rb | Ruby | lgpl-3.0 | 1,499 |
/*******************************************************************************
* logsniffer, open source tool for viewing, monitoring and analysing log data.
* Copyright (c) 2015 Scaleborn UG, www.scaleborn.com
*
* logsniffer is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* logsniffer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.logsniffer.util;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import com.logsniffer.app.ContextProvider;
import com.logsniffer.app.DataSourceAppConfig.DBInitIndicator;
import com.logsniffer.app.LogSnifferHome;
import com.logsniffer.model.LogSourceProvider;
import com.logsniffer.model.file.RollingLogsSource;
import com.logsniffer.reader.filter.FilteredLogEntryReader;
import com.logsniffer.reader.log4j.Log4jTextReader;
/**
* Registers LogSniffers own logs as source.
*
* @author mbok
*
*/
@Component
public class SniffMePopulator implements ApplicationContextAware {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private LogSnifferHome home;
@Autowired
private LogSourceProvider sourceProvider;
@Autowired
private DBInitIndicator dbInitIndicator;
@Autowired
private ContextProvider dummy;
@SuppressWarnings({ "unchecked", "rawtypes" })
public void populate() {
final RollingLogsSource myLogSource = new RollingLogsSource();
myLogSource.setPattern(new File(home.getHomeDir(), "logs/logsniffer.log").getPath());
myLogSource.setName("logsniffer's own log");
final Log4jTextReader reader = new Log4jTextReader();
reader.setFormatPattern("%d %-5p [%c] %m%n");
final Map<String, String> specifiersFieldMapping = new HashMap<>();
specifiersFieldMapping.put("d", "date");
specifiersFieldMapping.put("p", "priority");
specifiersFieldMapping.put("c", "category");
specifiersFieldMapping.put("m", "message");
reader.setSpecifiersFieldMapping(specifiersFieldMapping);
myLogSource.setReader(new FilteredLogEntryReader(reader, null));
sourceProvider.createSource(myLogSource);
logger.info("Created source for LogSniffer's own log: {}", myLogSource);
}
@Override
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
if (dbInitIndicator.isNewSchema()) {
try {
populate();
} catch (final Exception e) {
logger.error("Failed to create logsniffer's own log", e);
}
}
}
}
| logsniffer/logsniffer | logsniffer-core/src/main/java/com/logsniffer/util/SniffMePopulator.java | Java | lgpl-3.0 | 3,418 |
# -*- coding: utf-8 -*-
__author__ = 'sdukaka'
#只是为了测试一下装饰器的作用 decorator
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def now():
print('2015-3-25')
now()
def logger(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@logger('DEBUG')
def today():
print('2015-3-25')
today()
print(today.__name__)
| sdukaka/sdukakaBlog | test_decorator.py | Python | lgpl-3.0 | 664 |
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* __________________
*
* Copyright 2002 - 2007 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
package flex.management;
import java.util.ArrayList;
import java.util.Iterator;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import flex.messaging.log.Log;
import flex.messaging.log.LogCategories;
/**
* The default implementation of an MBeanServerLocator. This implementation
* returns the first MBeanServer from the list returned by MBeanServerFactory.findMBeanServer(null).
* If no MBeanServers have been instantiated, this class will request the creation
* of an MBeanServer and return a reference to it.
*
* @author shodgson
*/
public class DefaultMBeanServerLocator implements MBeanServerLocator
{
private MBeanServer server;
/** {@inheritDoc} */
public synchronized MBeanServer getMBeanServer()
{
if (server == null)
{
// Use the first MBeanServer we can find.
ArrayList servers = MBeanServerFactory.findMBeanServer(null);
if (servers.size() > 0)
{
Iterator iterator = servers.iterator();
server = (MBeanServer)iterator.next();
}
else
{
// As a last resort, try to create a new MBeanServer.
server = MBeanServerFactory.createMBeanServer();
}
if (Log.isDebug())
Log.getLogger(LogCategories.MANAGEMENT_MBEANSERVER).debug("Using MBeanServer: " + server);
}
return server;
}
}
| SOASTA/BlazeDS | modules/core/src/java/flex/management/DefaultMBeanServerLocator.java | Java | lgpl-3.0 | 2,377 |
# -*- coding: utf-8 -*-
# util.py
# Copyright (C) 2012 Red Hat, Inc.
#
# Authors:
# Akira TAGOH <tagoh@redhat.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 3 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gettext
import gi
import os.path
import string
from collections import OrderedDict
from fontstweak import FontsTweak
from gi.repository import Gtk
def N_(s):
return s
class FontsTweakUtil:
@classmethod
def find_file(self, uifile):
path = os.path.dirname(os.path.realpath(__file__))
f = os.path.join(path, 'data', uifile)
if not os.path.isfile(f):
f = os.path.join(path, '..', 'data', uifile)
if not os.path.isfile(f):
f = os.path.join(FontsTweak.UIPATH, uifile)
return f
@classmethod
def create_builder(self, uifile):
builder = Gtk.Builder()
builder.set_translation_domain(FontsTweak.GETTEXT_PACKAGE)
builder.add_from_file(self.find_file(uifile))
return builder
@classmethod
def translate_text(self, text, lang):
try:
self.translations
except AttributeError:
self.translations = {}
if self.translations.has_key(lang) == False:
self.translations[lang] = gettext.translation(
domain=FontsTweak.GETTEXT_PACKAGE,
localedir=FontsTweak.LOCALEDIR,
languages=[lang.replace('-', '_')],
fallback=True,
codeset="utf8")
return unicode(self.translations[lang].gettext(text), "utf8")
@classmethod
def get_language_list(self, default):
dict = OrderedDict()
if default == True:
dict[''] = N_('Default')
try:
fd = open(self.find_file('locale-list'), 'r')
except:
raise RuntimeError, "Unable to open locale-list"
while True:
line = fd.readline()
if not line:
break
tokens = string.split(line)
lang = str(tokens[0]).split('.')[0].replace('_', '-')
dict[lang] = string.join(tokens[3:], ' ')
return dict
| jamesni/fonts-tweak-tool | fontstweak/util.py | Python | lgpl-3.0 | 2,700 |
/*
* $RCSfile: USB_AI16_Family.java,v $
* $Date: 2009/12/23 22:45:27 $
* $Revision: 1.15 $
* jEdit:tabSize=4:indentSize=4:collapseFolds=1:
*/
package com.acces.aiousb;
// {{{ imports
import java.io.*;
import java.util.*;
// }}}
/**
* Class USB_AI16_Family represents a USB-AI16-family device, which encompasses the following product IDs:<br>
* {@link USBDeviceManager#USB_AI16_16A USB_AI16_16A}, {@link USBDeviceManager#USB_AI16_16E USB_AI16_16E},
* {@link USBDeviceManager#USB_AI12_16A USB_AI12_16A}, {@link USBDeviceManager#USB_AI12_16 USB_AI12_16},
* {@link USBDeviceManager#USB_AI12_16E USB_AI12_16E}, {@link USBDeviceManager#USB_AI16_64MA USB_AI16_64MA},
* {@link USBDeviceManager#USB_AI16_64ME USB_AI16_64ME}, {@link USBDeviceManager#USB_AI12_64MA USB_AI12_64MA},<br>
* {@link USBDeviceManager#USB_AI12_64M USB_AI12_64M}, {@link USBDeviceManager#USB_AI12_64ME USB_AI12_64ME},
* {@link USBDeviceManager#USB_AI16_32A USB_AI16_32A}, {@link USBDeviceManager#USB_AI16_32E USB_AI16_32E},
* {@link USBDeviceManager#USB_AI12_32A USB_AI12_32A}, {@link USBDeviceManager#USB_AI12_32 USB_AI12_32},
* {@link USBDeviceManager#USB_AI12_32E USB_AI12_32E}, {@link USBDeviceManager#USB_AI16_64A USB_AI16_64A},<br>
* {@link USBDeviceManager#USB_AI16_64E USB_AI16_64E}, {@link USBDeviceManager#USB_AI12_64A USB_AI12_64A},
* {@link USBDeviceManager#USB_AI12_64 USB_AI12_64}, {@link USBDeviceManager#USB_AI12_64E USB_AI12_64E},
* {@link USBDeviceManager#USB_AI16_96A USB_AI16_96A}, {@link USBDeviceManager#USB_AI16_96E USB_AI16_96E},
* {@link USBDeviceManager#USB_AI12_96A USB_AI12_96A}, {@link USBDeviceManager#USB_AI12_96 USB_AI12_96},<br>
* {@link USBDeviceManager#USB_AI12_96E USB_AI12_96E}, {@link USBDeviceManager#USB_AI16_128A USB_AI16_128A},
* {@link USBDeviceManager#USB_AI16_128E USB_AI16_128E}, {@link USBDeviceManager#USB_AI12_128A USB_AI12_128A},
* {@link USBDeviceManager#USB_AI12_128 USB_AI12_128}, {@link USBDeviceManager#USB_AI12_128E USB_AI12_128E}.<br><br>
* Instances of class <i>USB_AI16_Family</i> are automatically created by the USB device manager when they are
* detected on the bus. You should use one of the <i>{@link USBDeviceManager}</i> search methods, such as
* <i>{@link USBDeviceManager#getDeviceByProductID( int productID ) USBDeviceManager.getDeviceByProductID()}</i>,
* to obtain a reference to a <i>USB_AI16_Family</i> instance. You can then cast the <i>{@link USBDevice}</i>
* reference obtained from one of those methods to a <i>USB_AI16_Family</i> and make use of this class' methods, like so:
* <pre>USBDevice[] devices = deviceManager.getDeviceByProductID( USBDeviceManager.USB_AI12_32A, USBDeviceManager.USB_AI12_32E );
*if( devices.length > 0 )
* USB_AI16_Family device = ( USB_AI16_Family ) devices[ 0 ];</pre>
*/
public class USB_AI16_Family extends USBDevice {
// {{{ static members
private static int[] supportedProductIDs;
static {
supportedProductIDs = new int[] {
USBDeviceManager.USB_AI16_16A
, USBDeviceManager.USB_AI16_16E
, USBDeviceManager.USB_AI12_16A
, USBDeviceManager.USB_AI12_16
, USBDeviceManager.USB_AI12_16E
, USBDeviceManager.USB_AI16_64MA
, USBDeviceManager.USB_AI16_64ME
, USBDeviceManager.USB_AI12_64MA
, USBDeviceManager.USB_AI12_64M
, USBDeviceManager.USB_AI12_64ME
, USBDeviceManager.USB_AI16_32A
, USBDeviceManager.USB_AI16_32E
, USBDeviceManager.USB_AI12_32A
, USBDeviceManager.USB_AI12_32
, USBDeviceManager.USB_AI12_32E
, USBDeviceManager.USB_AI16_64A
, USBDeviceManager.USB_AI16_64E
, USBDeviceManager.USB_AI12_64A
, USBDeviceManager.USB_AI12_64
, USBDeviceManager.USB_AI12_64E
, USBDeviceManager.USB_AI16_96A
, USBDeviceManager.USB_AI16_96E
, USBDeviceManager.USB_AI12_96A
, USBDeviceManager.USB_AI12_96
, USBDeviceManager.USB_AI12_96E
, USBDeviceManager.USB_AI16_128A
, USBDeviceManager.USB_AI16_128E
, USBDeviceManager.USB_AI12_128A
, USBDeviceManager.USB_AI12_128
, USBDeviceManager.USB_AI12_128E
}; // supportedProductIDs[]
Arrays.sort( supportedProductIDs );
} // static
// }}}
// {{{ protected members
protected AnalogInputSubsystem analogInputSubsystem;
protected DigitalIOSubsystem digitalIOSubsystem;
protected CounterSubsystem counterSubsystem;
// }}}
// {{{ protected methods
protected USB_AI16_Family( int productID, int deviceIndex ) {
super( productID, deviceIndex );
if( ! isSupportedProductID( productID ) )
throw new IllegalArgumentException( "Invalid product ID: " + productID );
analogInputSubsystem = new AnalogInputSubsystem( this );
digitalIOSubsystem = new DigitalIOSubsystem( this );
counterSubsystem = new CounterSubsystem( this );
} // USB_AI16_Family()
// }}}
// {{{ public methods
/*
* properties
*/
/**
* Gets an array of all the product names supported by this USB device family.
* <br><br>Although this method is <i>static</i>, an instance of USBDeviceManager must be created
* and be "open" for use before this method can be used. This stipulation is imposed because the
* underlying library must be initialized in order for product name/ID lookups to succeed, and that
* initialization occurs only when an instance of USBDeviceManager is created and its
* <i>{@link USBDeviceManager#open() open()}</i> method is called.
* @return An array of product names, sorted in ascending order of product ID.
*/
public static String[] getSupportedProductNames() {
return USBDeviceManager.productIDToName( supportedProductIDs );
} // getSupportedProductNames()
/**
* Gets an array of all the product IDs supported by this USB device family.
* @return An array of product IDs, sorted in ascending order.
*/
public static int[] getSupportedProductIDs() {
return supportedProductIDs.clone();
} // getSupportedProductIDs()
/**
* Tells if a given product ID is supported by this USB device family.
* @param productID the product ID to check.
* @return <i>True</i> if the given product ID is supported by this USB device family; otherwise, <i>false</i>.
*/
public static boolean isSupportedProductID( int productID ) {
return Arrays.binarySearch( supportedProductIDs, productID ) >= 0;
} // isSupportedProductID()
/**
* Prints the properties of this device and all of its subsystems. Mainly useful for diagnostic purposes.
* @param stream the print stream where properties will be printed.
* @return The print stream.
*/
public PrintStream print( PrintStream stream ) {
super.print( stream );
analogInputSubsystem.print( stream );
digitalIOSubsystem.print( stream );
counterSubsystem.print( stream );
return stream;
} // print()
/*
* subsystems
*/
/**
* Gets a reference to the analog input subsystem of this device.
* @return A reference to the analog input subsystem.
*/
public AnalogInputSubsystem adc() {
return analogInputSubsystem;
} // adc()
/**
* Gets a reference to the digital I/O subsystem of this device.
* @return A reference to the digital I/O subsystem.
*/
public DigitalIOSubsystem dio() {
return digitalIOSubsystem;
} // dio()
/**
* Gets a reference to the counter/timer subsystem of this device.
* @return A reference to the counter/timer subsystem.
*/
public CounterSubsystem ctr() {
return counterSubsystem;
} // ctr()
// }}}
} // class USB_AI16_Family
/* end of file */
| accesio/AIOUSB | AIOUSB/deprecated/java/com/acces/aiousb/USB_AI16_Family.java | Java | lgpl-3.0 | 7,364 |
package org.nustaq.kontraktor.remoting.http.servlet;
import org.nustaq.kontraktor.remoting.http.KHttpExchange;
import org.nustaq.kontraktor.util.Log;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* Created by ruedi on 19.06.17.
*/
public class ServletKHttpExchangeImpl implements KHttpExchange {
KontraktorServlet servlet;
AsyncContext aCtx;
public ServletKHttpExchangeImpl(KontraktorServlet servlet, AsyncContext aCtx) {
this.servlet = servlet;
this.aCtx = aCtx;
}
@Override
public void endExchange() {
aCtx.complete();
}
@Override
public void setResponseContentLength(int length) {
aCtx.getResponse().setContentLength(length);
}
@Override
public void setResponseCode(int i) {
((HttpServletResponse) aCtx.getResponse()).setStatus(i);
}
@Override
public void send(String s) {
try {
aCtx.getResponse().setCharacterEncoding("UTF-8");
aCtx.getResponse().setContentType("text/html; charset=utf-8");
aCtx.getResponse().getWriter().write(s);
} catch (IOException e) {
Log.Warn(this,e);
}
}
@Override
public void send(byte[] b) {
try {
send(new String(b,"UTF-8"));
} catch (UnsupportedEncodingException e) {
Log.Error(this,e);
}
}
@Override
public void sendAuthResponse(byte[] response, String sessionId) {
try {
send(new String(response,"UTF-8"));
aCtx.complete();
} catch (UnsupportedEncodingException e) {
Log.Error(this,e);
}
}
}
| RuedigerMoeller/kontraktor | modules/kontraktor-http/src/main/java/org/nustaq/kontraktor/remoting/http/servlet/ServletKHttpExchangeImpl.java | Java | lgpl-3.0 | 1,761 |
/**
******************************************************************************
* @file wlan_hal.c
* @author Matthew McGowan
* @version V1.0.0
* @date 27-Sept-2014
* @brief
******************************************************************************
Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved.
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 3 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, see <http://www.gnu.org/licenses/>.
******************************************************************************
*/
#include "wlan_hal.h"
uint32_t HAL_NET_SetNetWatchDog(uint32_t timeOutInMS)
{
return 0;
}
int wlan_clear_credentials()
{
return 1;
}
int wlan_has_credentials()
{
return 1;
}
int wlan_connect_init()
{
return 0;
}
wlan_result_t wlan_activate()
{
return 0;
}
wlan_result_t wlan_deactivate()
{
return 0;
}
bool wlan_reset_credentials_store_required()
{
return false;
}
wlan_result_t wlan_reset_credentials_store()
{
return 0;
}
/**
* Do what is needed to finalize the connection.
* @return
*/
wlan_result_t wlan_connect_finalize()
{
// enable connection from stored profiles
return 0;
}
void Set_NetApp_Timeout(void)
{
}
wlan_result_t wlan_disconnect_now()
{
return 0;
}
wlan_result_t wlan_connected_rssi(char* ssid)
{
return 0;
}
int wlan_connected_info(void* reserved, wlan_connected_info_t* inf, void* reserved1)
{
return -1;
}
int wlan_set_credentials(WLanCredentials* c)
{
return -1;
}
void wlan_smart_config_init()
{
}
bool wlan_smart_config_finalize()
{
return false;
}
void wlan_smart_config_cleanup()
{
}
void wlan_setup()
{
}
void wlan_set_error_count(uint32_t errorCount)
{
}
int wlan_fetch_ipconfig(WLanConfig* config)
{
return -1;
}
void SPARK_WLAN_SmartConfigProcess()
{
}
void wlan_connect_cancel(bool called_from_isr)
{
}
/**
* Sets the IP source - static or dynamic.
*/
void wlan_set_ipaddress_source(IPAddressSource source, bool persist, void* reserved)
{
}
/**
* Sets the IP Addresses to use when the device is in static IP mode.
* @param device
* @param netmask
* @param gateway
* @param dns1
* @param dns2
* @param reserved
*/
void wlan_set_ipaddress(const HAL_IPAddress* device, const HAL_IPAddress* netmask,
const HAL_IPAddress* gateway, const HAL_IPAddress* dns1, const HAL_IPAddress* dns2, void* reserved)
{
}
IPAddressSource wlan_get_ipaddress_source(void* reserved)
{
return DYNAMIC_IP;
}
int wlan_get_ipaddress(IPConfig* conf, void* reserved)
{
return -1;
}
int wlan_scan(wlan_scan_result_t callback, void* cookie)
{
return -1;
}
int wlan_restart(void* reserved)
{
return -1;
}
int wlan_get_hostname(char* buf, size_t len, void* reserved)
{
// Unsupported
if (buf) {
buf[0] = '\0';
}
return -1;
}
int wlan_set_hostname(const char* hostname, void* reserved)
{
// Unsupported
return -1;
}
| spark/firmware | hal/src/template/wlan_hal.cpp | C++ | lgpl-3.0 | 3,455 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mediaconnectresponse.h"
#include "mediaconnectresponse_p.h"
#include <QDebug>
#include <QXmlStreamReader>
namespace QtAws {
namespace MediaConnect {
/*!
* \class QtAws::MediaConnect::MediaConnectResponse
* \brief The MediaConnectResponse class provides an interface for MediaConnect responses.
*
* \inmodule QtAwsMediaConnect
*/
/*!
* Constructs a MediaConnectResponse object with parent \a parent.
*/
MediaConnectResponse::MediaConnectResponse(QObject * const parent)
: QtAws::Core::AwsAbstractResponse(new MediaConnectResponsePrivate(this), parent)
{
}
/*!
* \internal
* Constructs a MediaConnectResponse object with private implementation \a d,
* and parent \a parent.
*
* This overload allows derived classes to provide their own private class
* implementation that inherits from MediaConnectResponsePrivate.
*/
MediaConnectResponse::MediaConnectResponse(MediaConnectResponsePrivate * const d, QObject * const parent)
: QtAws::Core::AwsAbstractResponse(d, parent)
{
}
/*!
* \reimp
*/
void MediaConnectResponse::parseFailure(QIODevice &response)
{
//Q_D(MediaConnectResponse);
Q_UNUSED(response);
/*QXmlStreamReader xml(&response);
if (xml.readNextStartElement()) {
if (xml.name() == QLatin1String("ErrorResponse")) {
d->parseErrorResponse(xml);
} else {
qWarning() << "ignoring" << xml.name();
xml.skipCurrentElement();
}
}
setXmlError(xml);*/
}
/*!
* \class QtAws::MediaConnect::MediaConnectResponsePrivate
* \brief The MediaConnectResponsePrivate class provides private implementation for MediaConnectResponse.
* \internal
*
* \inmodule QtAwsMediaConnect
*/
/*!
* Constructs a MediaConnectResponsePrivate object with public implementation \a q.
*/
MediaConnectResponsePrivate::MediaConnectResponsePrivate(
MediaConnectResponse * const q) : QtAws::Core::AwsAbstractResponsePrivate(q)
{
}
} // namespace MediaConnect
} // namespace QtAws
| pcolby/libqtaws | src/mediaconnect/mediaconnectresponse.cpp | C++ | lgpl-3.0 | 2,716 |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Fileharbor.Common.Database;
namespace Fileharbor.Services.Entities
{
[Table("collections")]
public class CollectionEntity
{
[Key]
[ColumnName("id")]
public Guid Id { get; set; }
[Required]
[ColumnName("name")]
public string Name { get; set; }
[Required]
[ColumnName("quota")]
public long Quota { get; set; }
[Required]
[ColumnName("bytes_used")]
public long BytesUsed { get; set; }
[ColumnName("template_id")]
public Guid? TemplateId { get; set; }
[ColumnName("description")]
public string Description { get; set; }
}
} | dennisbappert/fileharbor | src/Services/Entities/CollectionEntity.cs | C# | lgpl-3.0 | 789 |
using UnityEngine;
using System.Collections;
public class SimpleDebug : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI() {
float val = FalconUnity.getFPS();
GUI.Label(new Rect(5,5,200,30), val.ToString() );
}
}
| kbogert/falconunity | UnityDemoProject/Assets/SimpleDebug.cs | C# | lgpl-3.0 | 323 |
/**
* This file is part of the nestk library.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Nicolas Burrus <nicolas.burrus@uc3m.es>, (C) 2010
*/
# include "table_object_detector.h"
# include <ntk/utils/time.h>
# include <boost/make_shared.hpp>
using namespace pcl;
using cv::Point3f;
namespace ntk
{
template <class PointType>
TableObjectDetector<PointType> :: TableObjectDetector()
: m_max_dist_to_plane(0.03)
{
// ---[ Create all PCL objects and set their parameters
setObjectVoxelSize();
setBackgroundVoxelSize();
setDepthLimits();
setObjectHeightLimits();
// Normal estimation parameters
k_ = 10; // 50 k-neighbors by default
// Table model fitting parameters
sac_distance_threshold_ = 0.01; // 1cm
// Don't know ?
normal_distance_weight_ = 0.1;
// Clustering parameters
object_cluster_tolerance_ = 0.05; // 5cm between two objects
object_cluster_min_size_ = 100; // 100 points per object cluster
}
template <class PointType>
void TableObjectDetector<PointType> :: initialize()
{
grid_.setLeafSize (downsample_leaf_, downsample_leaf_, downsample_leaf_);
grid_objects_.setLeafSize (downsample_leaf_objects_, downsample_leaf_objects_, downsample_leaf_objects_);
grid_.setFilterFieldName ("z");
pass_.setFilterFieldName ("z");
grid_.setFilterLimits (min_z_bounds_, max_z_bounds_);
pass_.setFilterLimits (min_z_bounds_, max_z_bounds_);
grid_.setDownsampleAllData (false);
grid_objects_.setDownsampleAllData (false);
#ifdef HAVE_PCL_GREATER_THAN_1_2_0
normals_tree_ = boost::make_shared<pcl::search::KdTree<Point> > ();
clusters_tree_ = boost::make_shared<pcl::search::KdTree<Point> > ();
#else
normals_tree_ = boost::make_shared<pcl::KdTreeFLANN<Point> > ();
clusters_tree_ = boost::make_shared<pcl::KdTreeFLANN<Point> > ();
#endif
clusters_tree_->setEpsilon (1);
//tree_.setSearchWindowAsK (10);
//tree_.setMaxDistance (0.5);
n3d_.setKSearch (k_);
n3d_.setSearchMethod (normals_tree_);
normal_distance_weight_ = 0.1;
seg_.setNormalDistanceWeight (normal_distance_weight_);
seg_.setOptimizeCoefficients (true);
seg_.setModelType (pcl::SACMODEL_NORMAL_PLANE);
seg_.setMethodType (pcl::SAC_RANSAC);
seg_.setProbability (0.99);
seg_.setDistanceThreshold (sac_distance_threshold_);
seg_.setMaxIterations (10000);
proj_.setModelType (pcl::SACMODEL_NORMAL_PLANE);
prism_.setHeightLimits (object_min_height_, object_max_height_);
cluster_.setClusterTolerance (object_cluster_tolerance_);
cluster_.setMinClusterSize (object_cluster_min_size_);
cluster_.setSearchMethod (clusters_tree_);
}
template <class PointType>
bool TableObjectDetector<PointType> :: detect(PointCloudConstPtr cloud)
{
ntk::TimeCount tc("TableObjectDetector::detect", 1);
m_object_clusters.clear();
initialize();
ntk_dbg(1) << cv::format("PointCloud with %d data points.\n", cloud->width * cloud->height);
// ---[ Convert the dataset
cloud_ = cloud; // FIXME: Find out whether the removal of the (deep-copying) cloud.makeShared() call sped things up.
// ---[ Create the voxel grid
pcl::PointCloud<Point> cloud_filtered;
pass_.setInputCloud (cloud_);
pass_.filter (cloud_filtered);
cloud_filtered_.reset (new pcl::PointCloud<Point> (cloud_filtered));
ntk_dbg(1) << cv::format("Number of points left after filtering (%f -> %f): %d out of %d.\n", min_z_bounds_, max_z_bounds_, (int)cloud_filtered.points.size (), (int)cloud->points.size ());
pcl::PointCloud<Point> cloud_downsampled;
grid_.setInputCloud (cloud_filtered_);
grid_.filter (cloud_downsampled);
cloud_downsampled_.reset (new pcl::PointCloud<Point> (cloud_downsampled));
if ((int)cloud_filtered_->points.size () < k_)
{
ntk_dbg(0) << cv::format("WARNING Filtering returned %d points! Continuing.\n", (int)cloud_filtered_->points.size ());
return false;
}
// ---[ Estimate the point normals
pcl::PointCloud<pcl::Normal> cloud_normals;
n3d_.setInputCloud (cloud_downsampled_);
n3d_.compute (cloud_normals);
cloud_normals_.reset (new pcl::PointCloud<pcl::Normal> (cloud_normals));
ntk_dbg(1) << cv::format("%d normals estimated.", (int)cloud_normals.points.size ());
//ROS_ASSERT (cloud_normals_->points.size () == cloud_filtered_->points.size ());
// ---[ Perform segmentation
pcl::PointIndices table_inliers; pcl::ModelCoefficients table_coefficients;
seg_.setInputCloud (cloud_downsampled_);
seg_.setInputNormals (cloud_normals_);
seg_.segment (table_inliers, table_coefficients);
table_inliers_.reset (new pcl::PointIndices (table_inliers));
table_coefficients_.reset (new pcl::ModelCoefficients (table_coefficients));
if (table_coefficients.values.size () > 3)
ntk_dbg(1) << cv::format("Model found with %d inliers: [%f %f %f %f].\n", (int)table_inliers.indices.size (),
table_coefficients.values[0], table_coefficients.values[1], table_coefficients.values[2], table_coefficients.values[3]);
if (table_inliers_->indices.size () == 0)
return false;
m_plane = ntk::Plane (table_coefficients.values[0],
table_coefficients.values[1],
table_coefficients.values[2],
table_coefficients.values[3]);
// ---[ Extract the table
pcl::PointCloud<Point> table_projected;
proj_.setInputCloud (cloud_downsampled_);
proj_.setIndices (table_inliers_);
proj_.setModelCoefficients (table_coefficients_);
proj_.filter (table_projected);
table_projected_.reset (new pcl::PointCloud<Point> (table_projected));
ntk_dbg(1) << cv::format("Number of projected inliers: %d.\n", (int)table_projected.points.size ());
// ---[ Estimate the convex hull
pcl::PointCloud<Point> table_hull;
hull_.setInputCloud (table_projected_);
hull_.reconstruct (table_hull);
table_hull_.reset (new pcl::PointCloud<Point> (table_hull));
// ---[ Get the objects on top of the table
pcl::PointIndices cloud_object_indices;
prism_.setInputCloud (cloud_filtered_);
prism_.setInputPlanarHull (table_hull_);
prism_.segment (cloud_object_indices);
ntk_dbg(1) << cv::format("Number of object point indices: %d.\n", (int)cloud_object_indices.indices.size ());
pcl::PointCloud<Point> cloud_objects;
pcl::ExtractIndices<Point> extract_object_indices;
//extract_object_indices.setInputCloud (cloud_all_minus_table_ptr);
extract_object_indices.setInputCloud (cloud_filtered_);
// extract_object_indices.setInputCloud (cloud_downsampled_);
extract_object_indices.setIndices (boost::make_shared<const pcl::PointIndices> (cloud_object_indices));
extract_object_indices.filter (cloud_objects);
cloud_objects_.reset (new pcl::PointCloud<Point> (cloud_objects));
ntk_dbg(1) << cv::format("Number of object point candidates: %d.\n", (int)cloud_objects.points.size ());
if (cloud_objects.points.size () == 0)
return false;
// ---[ Downsample the points
pcl::PointCloud<Point> cloud_objects_downsampled;
grid_objects_.setInputCloud (cloud_objects_);
grid_objects_.filter (cloud_objects_downsampled);
cloud_objects_downsampled_.reset (new pcl::PointCloud<Point> (cloud_objects_downsampled));
ntk_dbg(1) << cv::format("Number of object point candidates left after downsampling: %d.\n", (int)cloud_objects_downsampled.points.size ());
// ---[ Split the objects into Euclidean clusters
std::vector< PointIndices > object_clusters;
cluster_.setInputCloud (cloud_objects_downsampled_);
cluster_.extract (object_clusters);
ntk_dbg(1) << cv::format("Number of clusters found matching the given constraints: %d.\n", (int)object_clusters.size ());
for (size_t i = 0; i < object_clusters.size (); ++i)
{
std::vector<Point3f> object_points;
foreach_idx(k, object_clusters[i].indices)
{
int index = object_clusters[i].indices[k];
Point p = cloud_objects_downsampled_->points[index];
object_points.push_back(Point3f(p.x,p.y,p.z));
}
float min_dist_to_plane = FLT_MAX;
for (int j = 0; j < object_points.size(); ++j)
{
Point3f pobj = object_points[j];
min_dist_to_plane = std::min(plane().distanceToPlane(pobj), min_dist_to_plane);
}
ntk_dbg_print(min_dist_to_plane, 1);
if (min_dist_to_plane > m_max_dist_to_plane)
continue;
m_object_clusters.push_back(object_points);
}
tc.stop();
return true;
}
template <class PointType>
int TableObjectDetector<PointType> :: getMostCentralCluster() const
{
// Look for the most central cluster which is not flying.
int selected_object = -1;
float min_x = FLT_MAX;
for (int i = 0; i < objectClusters().size(); ++i)
{
const std::vector<Point3f>& object_points = objectClusters()[i];
float min_dist_to_plane = FLT_MAX;
for (int j = 0; j < object_points.size(); ++j)
{
Point3f pobj = object_points[j];
min_dist_to_plane = std::min(plane().distanceToPlane(pobj), min_dist_to_plane);
}
if (min_dist_to_plane > m_max_dist_to_plane)
continue;
ntk::Rect3f bbox = bounding_box(object_points);
if (std::abs(bbox.centroid().x) < min_x)
{
min_x = std::abs(bbox.centroid().x);
selected_object = i;
}
}
return selected_object;
}
} // ntk
| tjbwyk/myrgbdemo | nestk/ntk/detection/table_object_detector.hpp | C++ | lgpl-3.0 | 10,289 |
package com.silicolife.textmining.processes.ir.patentpipeline.components.searchmodule.googlesearch;
public class IRPatentIDRetrievalGoogleSearchConfigurationImpl implements IIRPatentIDRecoverGoogleSearchConfiguration {
private String accessToken;
private String CustomSearchID;
public IRPatentIDRetrievalGoogleSearchConfigurationImpl(String accessToken, String CustomSearchID) {
this.accessToken=accessToken;
this.CustomSearchID=CustomSearchID;
}
@Override
public String getAccessToken() {
return accessToken;
}
@Override
public String getCustomSearchID() {
return CustomSearchID;
}
}
| biotextmining/processes | src/main/java/com/silicolife/textmining/processes/ir/patentpipeline/components/searchmodule/googlesearch/IRPatentIDRetrievalGoogleSearchConfigurationImpl.java | Java | lgpl-3.0 | 614 |
public class PlstEscape {
public void harvestConstructors( int stage ) {
super.harvestConstructors( stage-1 );
}
}
| SergiyKolesnikov/fuji | examples/AHEAD/j2jast/PlstEscape.java | Java | lgpl-3.0 | 140 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\world\sound;
use pocketmine\math\Vector3;
use pocketmine\network\mcpe\protocol\LevelEventPacket;
class IgniteSound implements Sound{
public function encode(?Vector3 $pos) : array{
return [LevelEventPacket::create(LevelEventPacket::EVENT_SOUND_IGNITE, 0, $pos)];
}
}
| JackNoordhuis/PocketMine-MP | src/world/sound/IgniteSound.php | PHP | lgpl-3.0 | 1,028 |
package org.openbase.bco.device.openhab.registry.synchronizer;
/*-
* #%L
* BCO Openhab Device Manager
* %%
* Copyright (C) 2015 - 2021 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import org.eclipse.smarthome.core.thing.link.dto.ItemChannelLinkDTO;
import org.eclipse.smarthome.io.rest.core.item.EnrichedItemDTO;
import org.openbase.bco.device.openhab.communication.OpenHABRestCommunicator;
import org.openbase.bco.device.openhab.registry.diff.IdentifiableEnrichedItemDTO;
import org.openbase.bco.device.openhab.registry.synchronizer.OpenHABItemProcessor.OpenHABItemNameMetaData;
import org.openbase.bco.registry.remote.Registries;
import org.openbase.jul.exception.CouldNotPerformException;
import org.openbase.jul.exception.InstantiationException;
import org.openbase.jul.exception.NotAvailableException;
import org.openbase.jul.schedule.SyncObject;
import org.openbase.jul.storage.registry.AbstractSynchronizer;
import org.openbase.type.domotic.service.ServiceTemplateType.ServiceTemplate.ServiceType;
import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState;
import org.openbase.type.domotic.unit.UnitConfigType.UnitConfig;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:pleminoq@openbase.org">Tamino Huxohl</a>
*/
public class ItemUnitSynchronization extends AbstractSynchronizer<String, IdentifiableEnrichedItemDTO> {
public ItemUnitSynchronization(final SyncObject synchronizationLock) throws InstantiationException {
super(new ItemObservable(), synchronizationLock);
}
@Override
public void activate() throws CouldNotPerformException, InterruptedException {
OpenHABRestCommunicator.getInstance().waitForConnectionState(ConnectionState.State.CONNECTED);
super.activate();
}
@Override
public void update(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) throws CouldNotPerformException {
logger.trace("Synchronize update {} ...", identifiableEnrichedItemDTO.getDTO().name);
validateAndUpdateItem(identifiableEnrichedItemDTO.getDTO());
}
@Override
public void register(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) throws CouldNotPerformException {
logger.trace("Synchronize registration {} ...", identifiableEnrichedItemDTO.getDTO().name);
// do nothing because items are registers by the thing synchronization
validateAndUpdateItem(identifiableEnrichedItemDTO.getDTO());
}
@Override
public void remove(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) throws CouldNotPerformException {
logger.trace("Synchronize removal {} ...", identifiableEnrichedItemDTO.getDTO().name);
final OpenHABItemNameMetaData metaData = new OpenHABItemNameMetaData(identifiableEnrichedItemDTO.getId());
try {
// unit exists for item so sync and register it again
final UnitConfig unitConfig = Registries.getUnitRegistry().getUnitConfigByAlias(metaData.getAlias());
updateItem(unitConfig, metaData.getServiceType(), identifiableEnrichedItemDTO.getDTO());
OpenHABRestCommunicator.getInstance().registerItem(identifiableEnrichedItemDTO.getDTO());
} catch (NotAvailableException ex) {
// unit does not exist so removal is okay
}
}
@Override
protected void afterInternalSync() {
logger.debug("Internal sync finished!");
}
@Override
public List<IdentifiableEnrichedItemDTO> getEntries() throws CouldNotPerformException {
final List<IdentifiableEnrichedItemDTO> itemList = new ArrayList<>();
for (final EnrichedItemDTO item : OpenHABRestCommunicator.getInstance().getItems()) {
itemList.add(new IdentifiableEnrichedItemDTO(item));
}
return itemList;
}
@Override
public boolean isSupported(final IdentifiableEnrichedItemDTO identifiableEnrichedItemDTO) {
return true;
}
private boolean updateItem(final UnitConfig unitConfig, final ServiceType serviceType, final EnrichedItemDTO item) throws CouldNotPerformException {
boolean modification = false;
final String label = SynchronizationProcessor.generateItemLabel(unitConfig, serviceType);
if (item.label == null || !item.label.equals(label)) {
if (item.label != null) {
logger.info("Item name of {} change from {} to {}", item.name, label, item.label, label);
}
item.label = label;
modification = true;
}
return modification;
}
private void validateAndUpdateItem(final EnrichedItemDTO item) throws CouldNotPerformException {
OpenHABItemNameMetaData metaData;
try {
metaData = new OpenHABItemNameMetaData(item.name);
} catch (CouldNotPerformException ex) {
// ignore item because it was not configured by this app
return;
}
try {
// unit exists for item so sync label from dal unit back to item if necessary
final UnitConfig unitConfig = Registries.getUnitRegistry().getUnitConfigByAlias(metaData.getAlias());
if (updateItem(unitConfig, metaData.getServiceType(), item)) {
OpenHABRestCommunicator.getInstance().updateItem(item);
}
} catch (NotAvailableException ex) {
// unit does not exist for item so remove it
try {
OpenHABRestCommunicator.getInstance().deleteItem(item);
} catch (CouldNotPerformException exx) {
// It seems like openHAB is sometimes not deleting item channel links but the links still
// cause items to be returned when queried.
// Thus if the item could not be deleted search a link still referencing it.
for (final ItemChannelLinkDTO itemChannelLink : OpenHABRestCommunicator.getInstance().getItemChannelLinks()) {
if (itemChannelLink.itemName.equals(item.name)) {
OpenHABRestCommunicator.getInstance().deleteItemChannelLink(itemChannelLink);
return;
}
}
throw exx;
}
}
}
}
| DivineCooperation/bco.core-manager | openhab/src/main/java/org/openbase/bco/device/openhab/registry/synchronizer/ItemUnitSynchronization.java | Java | lgpl-3.0 | 6,930 |
/*!
@file
@author Albert Semenov
@date 11/2007
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_LayerItem.h"
#include <algorithm>
namespace MyGUI
{
LayerItem::LayerItem() :
mLayer(nullptr),
mLayerNode(nullptr),
mSaveLayerNode(nullptr),
mTexture(nullptr)
{
}
LayerItem::~LayerItem()
{
}
void LayerItem::addChildItem(LayerItem* _item)
{
mLayerItems.push_back(_item);
if (mLayerNode != nullptr)
{
_item->attachToLayerItemNode(mLayerNode, false);
}
}
void LayerItem::removeChildItem(LayerItem* _item)
{
VectorLayerItem::iterator item = std::remove(mLayerItems.begin(), mLayerItems.end(), _item);
MYGUI_ASSERT(item != mLayerItems.end(), "item not found");
mLayerItems.erase(item);
}
void LayerItem::addChildNode(LayerItem* _item)
{
mLayerNodes.push_back(_item);
if (mLayerNode != nullptr)
{
// создаем оверлаппеду новый айтем
ILayerNode* child_node = mLayerNode->createChildItemNode();
_item->attachToLayerItemNode(child_node, true);
}
}
void LayerItem::removeChildNode(LayerItem* _item)
{
VectorLayerItem::iterator item = std::remove(mLayerNodes.begin(), mLayerNodes.end(), _item);
MYGUI_ASSERT(item != mLayerNodes.end(), "item not found");
mLayerNodes.erase(item);
}
void LayerItem::addRenderItem(ISubWidget* _item)
{
mDrawItems.push_back(_item);
}
void LayerItem::removeAllRenderItems()
{
detachFromLayerItemNode(false);
mDrawItems.clear();
}
void LayerItem::setRenderItemTexture(ITexture* _texture)
{
mTexture = _texture;
if (mLayerNode)
{
ILayerNode* node = mLayerNode;
// позже сделать детач без текста
detachFromLayerItemNode(false);
attachToLayerItemNode(node, false);
}
}
void LayerItem::saveLayerItem()
{
mSaveLayerNode = mLayerNode;
}
void LayerItem::restoreLayerItem()
{
mLayerNode = mSaveLayerNode;
if (mLayerNode)
{
attachToLayerItemNode(mLayerNode, false);
}
}
void LayerItem::attachItemToNode(ILayer* _layer, ILayerNode* _node)
{
mLayer = _layer;
mLayerNode = _node;
attachToLayerItemNode(_node, true);
}
void LayerItem::detachFromLayer()
{
// мы уже отдетачены в доску
if (nullptr == mLayer)
return;
// такого быть не должно
MYGUI_ASSERT(mLayerNode, "mLayerNode == nullptr");
// отписываемся от пиккинга
mLayerNode->detachLayerItem(this);
// при детаче обнулиться
ILayerNode* save = mLayerNode;
// физически отсоединяем
detachFromLayerItemNode(true);
// отсоединяем леер и обнуляем у рутового виджета
mLayer->destroyChildItemNode(save);
mLayerNode = nullptr;
mLayer = nullptr;
}
void LayerItem::upLayerItem()
{
if (mLayerNode)
mLayerNode->getLayer()->upChildItemNode(mLayerNode);
}
void LayerItem::attachToLayerItemNode(ILayerNode* _item, bool _deep)
{
MYGUI_DEBUG_ASSERT(nullptr != _item, "attached item must be valid");
// сохраняем, чтобы последующие дети могли приаттачиться
mLayerNode = _item;
for (VectorSubWidget::iterator skin = mDrawItems.begin(); skin != mDrawItems.end(); ++skin)
{
(*skin)->createDrawItem(mTexture, _item);
}
for (VectorLayerItem::iterator item = mLayerItems.begin(); item != mLayerItems.end(); ++item)
{
(*item)->attachToLayerItemNode(_item, _deep);
}
for (VectorLayerItem::iterator item = mLayerNodes.begin(); item != mLayerNodes.end(); ++item)
{
// создаем оверлаппеду новый айтем
if (_deep)
{
ILayerNode* child_node = _item->createChildItemNode();
(*item)->attachToLayerItemNode(child_node, _deep);
}
}
}
void LayerItem::detachFromLayerItemNode(bool _deep)
{
for (VectorLayerItem::iterator item = mLayerItems.begin(); item != mLayerItems.end(); ++item)
{
(*item)->detachFromLayerItemNode(_deep);
}
for (VectorLayerItem::iterator item = mLayerNodes.begin(); item != mLayerNodes.end(); ++item)
{
if (_deep)
{
ILayerNode* node = (*item)->mLayerNode;
(*item)->detachFromLayerItemNode(_deep);
if (node)
{
node->getLayer()->destroyChildItemNode(node);
}
}
}
// мы уже отаттачены
ILayerNode* node = mLayerNode;
if (node)
{
//for (VectorWidgetPtr::iterator widget = mWidgetChildSkin.begin(); widget != mWidgetChildSkin.end(); ++widget) (*widget)->_detachFromLayerItemKeeperByStyle(_deep);
for (VectorSubWidget::iterator skin = mDrawItems.begin(); skin != mDrawItems.end(); ++skin)
{
(*skin)->destroyDrawItem();
}
// при глубокой очистке, если мы оверлаппед, то для нас создавали айтем
/*if (_deep && !this->isRootWidget() && mWidgetStyle == WidgetStyle::Overlapped)
{
node->destroyItemNode();
}*/
// очищаем
mLayerNode = nullptr;
}
}
ILayer* LayerItem::getLayer() const
{
return mLayer;
}
ILayerNode* LayerItem::getLayerNode() const
{
return mLayerNode;
}
} // namespace MyGUI
| blunted2night/MyGUI | MyGUIEngine/src/MyGUI_LayerItem.cpp | C++ | lgpl-3.0 | 5,791 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "describeidentityusagerequest.h"
#include "describeidentityusagerequest_p.h"
#include "describeidentityusageresponse.h"
#include "cognitosyncrequest_p.h"
namespace QtAws {
namespace CognitoSync {
/*!
* \class QtAws::CognitoSync::DescribeIdentityUsageRequest
* \brief The DescribeIdentityUsageRequest class provides an interface for CognitoSync DescribeIdentityUsage requests.
*
* \inmodule QtAwsCognitoSync
*
* <fullname>Amazon Cognito Sync</fullname>
*
* Amazon Cognito Sync provides an AWS service and client library that enable cross-device syncing of application-related
* user data. High-level client libraries are available for both iOS and Android. You can use these libraries to persist
* data locally so that it's available even if the device is offline. Developer credentials don't need to be stored on the
* mobile device to access the service. You can use Amazon Cognito to obtain a normalized user ID and credentials. User
* data is persisted in a dataset that can store up to 1 MB of key-value pairs, and you can have up to 20 datasets per user
*
* identity>
*
* With Amazon Cognito Sync, the data stored for each identity is accessible only to credentials assigned to that identity.
* In order to use the Cognito Sync service, you need to make API calls using credentials retrieved with <a
* href="http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/Welcome.html">Amazon Cognito Identity
*
* service</a>>
*
* If you want to use Cognito Sync in an Android or iOS application, you will probably want to make API calls via the AWS
* Mobile SDK. To learn more, see the <a
* href="http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-sync.html">Developer Guide for Android</a>
* and the <a href="http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-sync.html">Developer Guide for
*
* \sa CognitoSyncClient::describeIdentityUsage
*/
/*!
* Constructs a copy of \a other.
*/
DescribeIdentityUsageRequest::DescribeIdentityUsageRequest(const DescribeIdentityUsageRequest &other)
: CognitoSyncRequest(new DescribeIdentityUsageRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a DescribeIdentityUsageRequest object.
*/
DescribeIdentityUsageRequest::DescribeIdentityUsageRequest()
: CognitoSyncRequest(new DescribeIdentityUsageRequestPrivate(CognitoSyncRequest::DescribeIdentityUsageAction, this))
{
}
/*!
* \reimp
*/
bool DescribeIdentityUsageRequest::isValid() const
{
return false;
}
/*!
* Returns a DescribeIdentityUsageResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * DescribeIdentityUsageRequest::response(QNetworkReply * const reply) const
{
return new DescribeIdentityUsageResponse(*this, reply);
}
/*!
* \class QtAws::CognitoSync::DescribeIdentityUsageRequestPrivate
* \brief The DescribeIdentityUsageRequestPrivate class provides private implementation for DescribeIdentityUsageRequest.
* \internal
*
* \inmodule QtAwsCognitoSync
*/
/*!
* Constructs a DescribeIdentityUsageRequestPrivate object for CognitoSync \a action,
* with public implementation \a q.
*/
DescribeIdentityUsageRequestPrivate::DescribeIdentityUsageRequestPrivate(
const CognitoSyncRequest::Action action, DescribeIdentityUsageRequest * const q)
: CognitoSyncRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the DescribeIdentityUsageRequest
* class' copy constructor.
*/
DescribeIdentityUsageRequestPrivate::DescribeIdentityUsageRequestPrivate(
const DescribeIdentityUsageRequestPrivate &other, DescribeIdentityUsageRequest * const q)
: CognitoSyncRequestPrivate(other, q)
{
}
} // namespace CognitoSync
} // namespace QtAws
| pcolby/libqtaws | src/cognitosync/describeidentityusagerequest.cpp | C++ | lgpl-3.0 | 4,598 |
from pymongo import MongoClient
import config
class Database:
def __init__(self, db_name=None):
self.mongodb_client = create_mongodb_client()
self.db = self.create_db(db_name)
self.authenticate_user()
def create_db(self, db_name):
if db_name is None:
return self.mongodb_client[config.get_database_name()]
return self.mongodb_client[db_name]
def authenticate_user(self):
if config.is_database_authentication_enabled():
self.db.authenticate(config.get_database_user(), config.get_database_password())
def insert_document_in_collection(self, doc, collection_name):
collection = self.db[collection_name]
collection.insert_one(doc)
def exist_doc_in_collection(self, search_condition, collection_name):
collection = self.db[collection_name]
query_result = collection.find(search_condition).limit(1)
return doc_found(query_result)
def search_text_with_regex_in_collection(self, regex, field, collection_name):
collection = self.db[collection_name]
return collection.find({field: get_regex_dict(regex)})
def search_text_with_regex_in_collection_mul(self, regex_a, regex_b, field_a, field_b, collection_name):
collection = self.db[collection_name]
return collection.find({'$and': [{field_a: get_regex_dict(regex_a)}, {field_b: get_regex_dict(regex_b)}]})
def search_document_in_collection(self, search_condition, collection_name):
collection = self.db[collection_name]
return collection.find_one(search_condition, {'_id': 0})
def search_documents_in_collection(self, search_condition, collection_name):
collection = self.db[collection_name]
return collection.find(search_condition, {'_id': 0})
def search_documents_and_aggregate(self, search_condition, aggregation, collection_name):
collection = self.db[collection_name]
return list(collection.aggregate([{'$match': search_condition}, {'$project': aggregation}]))
def get_number_of_documents_in_collection(self, collection_name, filter_=None):
collection = self.db[collection_name]
return collection.count(filter_)
def update_document_in_collection(self, filter_, update, collection_name, insert_if_not_exists=False):
collection = self.db[collection_name]
collection.update_one(filter_, {'$set': update}, upsert=insert_if_not_exists)
def update_documents_in_collection(self, docs, find_filter, collection_name):
if len(docs) > 0:
bulk = self.db[collection_name].initialize_ordered_bulk_op()
for doc in docs:
bulk.find({find_filter: doc.get(find_filter)}).upsert().update({'$set': doc})
bulk.execute()
def get_documents_from_collection(self, collection_name):
collection = self.db[collection_name]
return list(collection.find({}, {'_id': 0}))
def get_documents_from_collection_in_range(self, collection_name, skip=0, limit=0):
collection = self.db[collection_name]
return list(collection.find({}, {'_id': 0}).skip(skip).limit(limit))
def delete_document_from_collection(self, query, collection_name):
collection = self.db[collection_name]
collection.delete_one(query)
def close(self):
self.mongodb_client.close()
def drop_collection(self, collection_name):
collection = self.db[collection_name]
collection.drop()
def insert_documents_in_collection(self, documents, collection_name):
collection = self.db[collection_name]
collection.insert_many(documents=documents)
def create_mongodb_client():
return MongoClient(config.get_database_host(), config.get_database_port())
def doc_found(query_result):
found = query_result.count() > 0
query_result.close()
return found
def get_regex_dict(regex):
return {'$regex': regex} | fkie-cad/iva | database.py | Python | lgpl-3.0 | 3,952 |
/*******************************************************************************
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2009-2011 by sprylab technologies GmbH
*
* WebInLoop - a program for testing web applications
*
* This file is part of WebInLoop.
*
* WebInLoop is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* WebInLoop 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with WebInLoop. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>
* for a copy of the LGPLv3 License.
******************************************************************************/
package com.sprylab.webinloop.util.mailer.tests;
import javax.mail.MessagingException;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.sprylab.webinloop.util.mailer.MailAccountParseResult;
@Test
public class MailAccountParseResultTest {
private String buildMailTargetString(String account, Integer lowerBound, Integer upperBound, String target) {
String result = account;
if (lowerBound != null && upperBound != null) {
result += ":" + lowerBound + "-" + upperBound;
}
if (target != null) {
result += ":" + target;
}
return result;
}
private void testParseMailTargetString(String account, Integer lowerBound, Integer upperBound, String target)
throws MessagingException {
String mailTarget = buildMailTargetString(account, lowerBound, upperBound, target);
MailAccountParseResult result = MailAccountParseResult.parse(mailTarget);
if (lowerBound == null) {
lowerBound = 0;
}
if (upperBound == null) {
upperBound = Integer.MAX_VALUE;
}
Assert.assertEquals(result.getMailAccount(), account);
Assert.assertEquals(result.getLowerBound(), lowerBound);
Assert.assertEquals(result.getUpperBound(), upperBound);
Assert.assertEquals(result.getTarget(), target);
}
@Test
public void parseAccount() throws MessagingException {
String account = "mail1";
Integer lowerBound = null;
Integer upperBound = null;
String target = null;
testParseMailTargetString(account, lowerBound, upperBound, target);
}
@Test
public void parseAccountAndTarget() throws MessagingException {
String account = "mail1";
Integer lowerBound = null;
Integer upperBound = null;
String target = "subject";
testParseMailTargetString(account, lowerBound, upperBound, target);
}
@Test
public void parseAccountRangeAndTarget() throws MessagingException {
String account = "mail1";
Integer lowerBound = 1;
Integer upperBound = 10;
String target = "subject";
testParseMailTargetString(account, lowerBound, upperBound, target);
}
}
| sprylab/webinloop | webinloop/src/test/java/com/sprylab/webinloop/util/mailer/tests/MailAccountParseResultTest.java | Java | lgpl-3.0 | 3,415 |
/**
* This file is part of the CRISTAL-iSE REST API.
* Copyright (c) 2001-2016 The CRISTAL Consortium. All rights reserved.
*
* 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 3 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; with out 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.
*
* http://www.fsf.org/licensing/licenses/lgpl.html
*/
package org.cristalise.restapi;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.Semaphore;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.cristalise.kernel.common.InvalidDataException;
import org.cristalise.kernel.entity.proxy.ItemProxy;
import org.cristalise.kernel.persistency.outcome.Outcome;
import org.cristalise.kernel.persistency.outcome.Schema;
import org.cristalise.kernel.scripting.Script;
import org.cristalise.kernel.scripting.ScriptingEngineException;
import org.cristalise.kernel.utils.CastorHashMap;
import org.cristalise.kernel.utils.LocalObjectLoader;
import org.cristalise.kernel.utils.Logger;
import org.json.JSONObject;
import org.json.XML;
public class ScriptUtils extends ItemUtils {
static Semaphore mutex = new Semaphore(1);
public ScriptUtils() {
super();
}
/**
*
* @param item
* @param script
* @return
* @throws ScriptingEngineException
* @throws InvalidDataException
*/
protected Object executeScript(ItemProxy item, final Script script, CastorHashMap inputs)
throws ScriptingEngineException, InvalidDataException {
Object scriptResult = null;
try {
scriptResult = script.evaluate(item == null ? script.getItemPath() : item.getPath(), inputs, null, null);
}
catch (ScriptingEngineException e) {
throw e;
}
catch (Exception e) {
throw new InvalidDataException(e.getMessage());
}
return scriptResult;
}
public Response executeScript(HttpHeaders headers, ItemProxy item, String scriptName, Integer scriptVersion,
String inputJson, Map<String, Object> additionalInputs) {
// FIXME: version should be retrieved from the current item or the Module
// String view = "last";
if (scriptVersion == null) scriptVersion = 0;
Script script = null;
if (scriptName != null) {
try {
script = LocalObjectLoader.getScript(scriptName, scriptVersion);
JSONObject json =
new JSONObject(
inputJson == null ? "{}" : URLDecoder.decode(inputJson, "UTF-8"));
CastorHashMap inputs = new CastorHashMap();
for (String key: json.keySet()) {
inputs.put(key, json.get(key));
}
inputs.putAll(additionalInputs);
return returnScriptResult(scriptName, item, null, script, inputs, produceJSON(headers.getAcceptableMediaTypes()));
}
catch (Exception e) {
Logger.error(e);
throw ItemUtils.createWebAppException("Error executing script, please contact support", e, Response.Status.NOT_FOUND);
}
}
else {
throw ItemUtils.createWebAppException("Name or UUID of Script was missing", Response.Status.NOT_FOUND);
}
}
public Response returnScriptResult(String scriptName, ItemProxy item, final Schema schema, final Script script, CastorHashMap inputs, boolean jsonFlag)
throws ScriptingEngineException, InvalidDataException
{
try {
mutex.acquire();
return runScript(scriptName, item, schema, script, inputs, jsonFlag);
}
catch (ScriptingEngineException e) {
throw e;
}
catch (Exception e) {
throw new InvalidDataException(e.getMessage());
}
finally {
mutex.release();
}
}
/**
*
* @param scriptName
* @param item
* @param schema
* @param script
* @param jsonFlag whether the response is a JSON or XML
* @return
* @throws ScriptingEngineException
* @throws InvalidDataException
*/
protected Response runScript(String scriptName, ItemProxy item, final Schema schema, final Script script, CastorHashMap inputs, boolean jsonFlag)
throws ScriptingEngineException, InvalidDataException
{
String xmlOutcome = null;
Object scriptResult = executeScript(item, script, inputs);
if (scriptResult instanceof String) {
xmlOutcome = (String)scriptResult;
}
else if (scriptResult instanceof Map) {
//the map shall have one Key only
String key = ((Map<?,?>) scriptResult).keySet().toArray(new String[0])[0];
xmlOutcome = (String)((Map<?,?>) scriptResult).get(key);
}
else
throw ItemUtils.createWebAppException("Cannot handle result of script:" + scriptName, NOT_FOUND);
if (xmlOutcome == null)
throw ItemUtils.createWebAppException("Cannot handle result of script:" + scriptName, NOT_FOUND);
if (schema != null) return getOutcomeResponse(new Outcome(xmlOutcome, schema), new Date(), jsonFlag);
else {
if (jsonFlag) return Response.ok(XML.toJSONObject(xmlOutcome).toString()).build();
else return Response.ok((xmlOutcome)).build();
}
}
}
| cristal-ise/restapi | src/main/java/org/cristalise/restapi/ScriptUtils.java | Java | lgpl-3.0 | 6,223 |
/*--------------------------------------------------------------------
(C) Copyright 2006-2011 Barcelona Supercomputing Center
Centro Nacional de Supercomputacion
This file is part of Mercurium C/C++ source-to-source compiler.
See AUTHORS file in the top level directory for information
regarding developers 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 3 of the License, or (at your option) any later version.
Mercurium C/C++ source-to-source compiler 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 Mercurium C/C++ source-to-source compiler; if
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.
--------------------------------------------------------------------*/
#ifndef TL_PRAGMASUPPORT_HPP
#define TL_PRAGMASUPPORT_HPP
#include "tl-common.hpp"
#include <string>
#include <stack>
#include <algorithm>
#include "tl-clauses-info.hpp"
#include "tl-compilerphase.hpp"
#include "tl-langconstruct.hpp"
#include "tl-handler.hpp"
#include "tl-traverse.hpp"
#include "tl-source.hpp"
#include "cxx-attrnames.h"
namespace TL
{
class LIBTL_CLASS ClauseTokenizer
{
public:
virtual ObjectList<std::string> tokenize(const std::string& str) const = 0;
virtual ~ClauseTokenizer() { }
};
class LIBTL_CLASS NullClauseTokenizer : public ClauseTokenizer
{
public:
virtual ObjectList<std::string> tokenize(const std::string& str) const
{
ObjectList<std::string> result;
result.append(str);
return result;
}
};
class LIBTL_CLASS ExpressionTokenizer : public ClauseTokenizer
{
public:
virtual ObjectList<std::string> tokenize(const std::string& str) const
{
int bracket_nesting = 0;
ObjectList<std::string> result;
std::string temporary("");
for (std::string::const_iterator it = str.begin();
it != str.end();
it++)
{
const char & c(*it);
if (c == ','
&& bracket_nesting == 0
&& temporary != "")
{
result.append(temporary);
temporary = "";
}
else
{
if (c == '('
|| c == '{'
|| c == '[')
{
bracket_nesting++;
}
else if (c == ')'
|| c == '}'
|| c == ']')
{
bracket_nesting--;
}
temporary += c;
}
}
if (temporary != "")
{
result.append(temporary);
}
return result;
}
};
class LIBTL_CLASS ExpressionTokenizerTrim : public ExpressionTokenizer
{
public:
virtual ObjectList<std::string> tokenize(const std::string& str) const
{
ObjectList<std::string> result;
result = ExpressionTokenizer::tokenize(str);
std::transform(result.begin(), result.end(), result.begin(), trimExp);
return result;
}
private:
static std::string trimExp (const std::string &str) {
ssize_t first = str.find_first_not_of(" \t");
ssize_t last = str.find_last_not_of(" \t");
return str.substr(first, last - first + 1);
}
};
//! This class wraps a clause in a PragmaCustomConstruct
/*!
This class allows a clause to be named several times, thus
#pragma prefix name clause(a) clause(b)
will be equivalent as if the user had written
#pragma prefix name clause(a, b)
There is no way to tell apart these two cases, except for using
PragmaCustomClause::get_arguments_unflattened, see below.
Pragma clauses are pretty flexible on what they allow as arguments. Free,
well parenthesized, text is allowed in clauses. Thus forwarding the
responsability of giving a syntactic validity and semantic meaning to
PragmaCustomCompilerPhase classes.
Since the raw string is most of the time of little use, the class can cook
some usual cases:
When the clause should contain a list of expressions, use
PragmaCustomClause::get_expression_list
When the clause should contain a list of variable-names (but not
general expressions), use PragmaCustomClause::get_id_expressions
You can always get raw versions of the clause content (in case you have
very special syntax in it requiring special parsing) using
PragmaCustomClause::get_arguments and
PragmaCustomClause::get_arguments_unflattened. The second version returns
a list of lists of strings, one list per occurrence of the clause while
the first flats them in a single list.
*/
class LIBTL_CLASS PragmaCustomClause : public LangConstruct
{
private:
ObjectList<std::string> _clause_names;
ObjectList<AST_t> filter_pragma_clause();
public:
PragmaCustomClause(const std::string& src, AST_t ref, ScopeLink scope_link)
: LangConstruct(ref, scope_link)
{
_clause_names.push_back(src);
}
PragmaCustomClause(const ObjectList<std::string> & src, AST_t ref, ScopeLink scope_link)
: LangConstruct(ref, scope_link), _clause_names(src)
{
}
//! Returns the name of the current clause
std::string get_clause_name() { return _clause_names[0]; }
//! States whether the clause was actually in the pragma
/*!
Since PragmaCustomConstruct always returns a PragmaCustomClause
use this function to know whether the clause was actually in the
pragma line. No other function of PragmaCustomClause should be
used if this function returns false
*/
bool is_defined();
//! Convenience function, it returns all the arguments of the clause parsed as expressions
ObjectList<Expression> get_expression_list();
//! Convenience function, it returns all arguments of the clause parsed as id-expressions
ObjectList<IdExpression> get_id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS);
//! Do not use this one, its name is deprecated, use get_id_expressions instead
ObjectList<IdExpression> id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS);
//! Returns the string contents of the clause arguments
/*!
This function actually returns a list of a single element
*/
ObjectList<std::string> get_arguments();
//! Returns the string contents of the clause arguments but using a tokenizer
/*!
The tokenizer can further split the text in additional substrings
*/
ObjectList<std::string> get_arguments(const ClauseTokenizer&);
//! Returns the string contents of the clause arguments but using a tokenizer
/*!
This function is similar to get_arguments but does not combine them in a single list.
There is a list per each clause occurrence in the pragma
*/
ObjectList<ObjectList<std::string> > get_arguments_unflattened();
//! This is like get_arguments but at tree level. This function is of little use
/*!
It is highly unlikely that you need this function. Check the others
*/
ObjectList<AST_t> get_arguments_tree();
};
class LIBTL_CLASS PragmaCustomConstruct : public LangConstruct, public LinkData
{
private:
DTO* _dto;
public:
PragmaCustomConstruct(AST_t ref, ScopeLink scope_link)
: LangConstruct(ref, scope_link),
_dto(NULL)
{
}
//! Returns the name of the pragma prefix
std::string get_pragma() const;
//! Returns the name of the pragma directive
std::string get_directive() const;
//! States if this is a directive
/*!
When this function is true it means that the pragma itself is a sole entity
*/
bool is_directive() const;
//! States if this is a construct
/*!
When this function is true it means that the pragma acts as a header of another
language construct. Functions get_statement and get_declaration can then, be used to
retrieve that language construct.
For pragma constructs at block-scope only get_statement should be
used, otherwise use get_declaration as the nested construct can
be a declaration or a function definition (or even something else)
*/
bool is_construct() const;
//! Returns the statement associated to this pragma construct
/*!
Using this function is only valid when the pragma is in block-scope
and function is_construct returned true
*/
Statement get_statement() const;
//! Returns the tree associated to this pragma construct
/*!
Using this function is only valid when the pragma is in a scope
other than block and function is_construct returned true
This tree can be a Declaration, FunctionDefinition or some other
tree not wrapped yet in a LangConstruct (e.g. a Namespace
definition)
*/
AST_t get_declaration() const;
//! This function returns the tree related to the pragma itself
/*!
This function is rarely needed, only when a change of the pragma itself is required
*/
AST_t get_pragma_line() const;
//! This is used internally to initialize clauses information
/*!
Use it only if you want automatic clause checks but you never call get_clause on it
It is safe to call it more than once.
*/
void init_clause_info() const;
//! States if the pragma encloses a function definition
/*!
This is useful when using get_declaration, to quickly know if we can use a FunctionDefinition
or we should use a Declaration instead
*/
bool is_function_definition() const;
//! States if the pragma is followed by a first clause-alike parenthesis pair
/*!
#pragma prefix directive(a,b)
'a,b' is sort of an unnamed clause which is called the parameter of the pragma
This function states if this pragma has this syntax
*/
bool is_parameterized() const;
//! Returns a list of IdExpression's found in the parameter of the pragma
ObjectList<IdExpression> get_parameter_id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS) const;
//! Returns a list of Expressions in the parameter of the pragma
/*!
Parameters allow well-parenthesized free text. This function interprets the content of the parameter
as a list of comma-separated expressions, parses them at this moment (if not parsed already)
and returns it as a list
*/
ObjectList<Expression> get_parameter_expressions() const;
//! Returns the string of the parameter of the pragma
/*!
Parameters allow well-parenthesized free text. This function returns the whole text with no tokenization.
This function will always return one element, but for parallelism with the equivalent function of PragmaCustomClause
it returns a list (that will contain a single element)
*/
ObjectList<std::string> get_parameter_arguments() const;
//! Returns the string of the parameter of the pragma using a tokenizer
/*!
This function is identical to get_parameter_arguments() but uses \a tokenizer to
split the contents of the string.
*/
ObjectList<std::string> get_parameter_arguments(const ClauseTokenizer& tokenizer) const;
//! This function returns all the clauses of this pragma
ObjectList<std::string> get_clause_names() const;
//! This function returns a PragmaCustomClause object for a named clause
/*!
Note that this function always returns a PragmaCustomClause
object even if no clause with the given /a name exists. Use
PragmaCustomClause::is_defined to check its existence.
Adds to the DTO of PragmaCustomCompilerPhase the clause only if /a name exists.
*/
PragmaCustomClause get_clause(const std::string& name) const;
PragmaCustomClause get_clause(const ObjectList<std::string>& names) const;
//! This function set to the object _dto the dto get from de compiler phase
void set_dto(DTO* dto);
//! This function returns a boolean that show if some warnings must be printed out
bool get_show_warnings();
};
LIBTL_EXTERN bool is_pragma_custom(const std::string& pragma_preffix,
AST_t ast,
ScopeLink scope_link);
LIBTL_EXTERN bool is_pragma_custom_directive(const std::string& pragma_preffix,
const std::string& pragma_directive,
AST_t ast,
ScopeLink scope_link);
LIBTL_EXTERN bool is_pragma_custom_construct(const std::string& pragma_preffix,
const std::string& pragma_directive,
AST_t ast,
ScopeLink scope_link);
typedef std::map<std::string, Signal1<PragmaCustomConstruct> > CustomFunctorMap;
class LIBTL_CLASS PragmaCustomDispatcher : public TraverseFunctor
{
private:
std::string _pragma_handled;
CustomFunctorMap& _pre_map;
CustomFunctorMap& _post_map;
DTO* _dto;
bool _warning_clauses;
std::stack<PragmaCustomConstruct*> _construct_stack;
void dispatch_pragma_construct(CustomFunctorMap& search_map, PragmaCustomConstruct& pragma_custom_construct);
public:
PragmaCustomDispatcher(const std::string& pragma_handled,
CustomFunctorMap& pre_map,
CustomFunctorMap& post_map,
bool warning_clauses);
virtual void preorder(Context ctx, AST_t node);
virtual void postorder(Context ctx, AST_t node);
void set_dto(DTO* dto);
void set_warning_clauses(bool warning);
};
//! Base class for all compiler phases working on user defined pragma lines
/*!
* Configuration of mcxx will require a 'pragma_prefix' line in order
* to properly parse these pragma lines. In addition, the phases
* will have to call register_directive and register_construct
* accordingly to register specific constructs and directives.
*/
class LIBTL_CLASS PragmaCustomCompilerPhase : public CompilerPhase
{
private:
std::string _pragma_handled;
PragmaCustomDispatcher _pragma_dispatcher;
public:
//! Constructor
/*!
* \param pragma_handled The pragma prefix actually handled in this phase.
*/
PragmaCustomCompilerPhase(const std::string& pragma_handled);
virtual void pre_run(DTO& data_flow);
//! Entry point of the phase
/*!
* This function registers traverse functors to perform
* a traversal on all the constructs and directives.
*/
virtual void run(DTO& data_flow);
//! Custom functor map for directives found in preorder
CustomFunctorMap on_directive_pre;
//! Custom functor map for directives found in postorder
CustomFunctorMap on_directive_post;
//! Function to register a directive
/*!
* This is required for successful parsing of directives
*/
void register_directive(const std::string& name);
//! Function to register a construct
/*!
* This is required for successful parsing of construct
*
* \param bound_to_statement This parameter is only meaningful in
* Fortran and will have no effect in C/C++. If true, the
* construct is bounded to the next single statement. By default in
* Fortran a construct 'name' is bound to a block of statements,
* thus requiring a 'end name' directive to know where such block
* ends. By binding the construct to the next statement, such 'end
* name' it is not strictly needed anymore thus becoming optional.
* This parameter does not have any effect in C/C++ since in those
* languages pragma constructs are always bound to the next
* statement since blocks are expressed by compound-statements
* which are statements (recursively) containing other statements
*/
void register_construct(const std::string& name, bool bound_to_statement = false);
//! Function to activate a flag in order to warning about all the unused clauses of a pragma
/*!
* Each fase must activate this flag if wants to show the warnings
*/
void warning_pragma_unused_clauses(bool warning);
};
}
#endif // TL_PRAGMASUPPORT_HPP
| sdruix/AutomaticParallelization | src/tl/tl-pragmasupport.hpp | C++ | lgpl-3.0 | 18,927 |
"""
useful decorators
"""
__author__ = "Philippe Guglielmetti"
__copyright__ = "Copyright 2015, Philippe Guglielmetti"
__credits__ = ["http://include.aorcsik.com/2014/05/28/timeout-decorator/"]
__license__ = "LGPL + MIT"
import multiprocessing
from multiprocessing import TimeoutError
from threading import Timer
import weakref
import threading
import _thread as thread
from multiprocessing.pool import ThreadPool
import logging
import functools
import sys
import logging
_gettrace = getattr(sys, 'gettrace', None)
debugger = _gettrace and _gettrace()
logging.info('debugger ' + ('ACTIVE' if debugger else 'INACTIVE'))
# http://wiki.python.org/moin/PythonDecoratorLibrary
def memoize(obj):
"""speed up repeated calls to a function by caching its results in a dict index by params
:see: https://en.wikipedia.org/wiki/Memoization
"""
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
def debug(func):
# Customize these messages
ENTRY_MESSAGE = 'Entering {}'
EXIT_MESSAGE = 'Exiting {}'
@functools.wraps(func)
def wrapper(*args, **kwds):
logger = logging.getLogger()
logger.info(ENTRY_MESSAGE.format(func.__name__))
level = logger.getEffectiveLevel()
logger.setLevel(logging.DEBUG)
f_result = func(*args, **kwds)
logger.setLevel(level)
logger.info(EXIT_MESSAGE.format(func.__name__))
return f_result
return wrapper
def nodebug(func):
@functools.wraps(func)
def wrapper(*args, **kwds):
logger = logging.getLogger()
level = logger.getEffectiveLevel()
logger.setLevel(logging.INFO)
f_result = func(*args, **kwds)
logger.setLevel(level)
return f_result
return wrapper
# https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
def timeit(method):
import time
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
logging.info('%r %2.2f ms' % (method.__name__, (te - ts) * 1000))
return result
return timed
# http://include.aorcsik.com/2014/05/28/timeout-decorator/
# BUT read http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python
thread_pool = None
def get_thread_pool():
global thread_pool
if thread_pool is None:
# fix for python <2.7.2
if not hasattr(threading.current_thread(), "_children"):
threading.current_thread()._children = weakref.WeakKeyDictionary()
thread_pool = ThreadPool(processes=1)
return thread_pool
def timeout(timeout):
def wrap_function(func):
if not timeout:
return func
@functools.wraps(func)
def __wrapper(*args, **kwargs):
try:
async_result = get_thread_pool().apply_async(func, args=args, kwds=kwargs)
return async_result.get(timeout)
except thread.error:
return func(*args, **kwargs)
return __wrapper
return wrap_function
# https://gist.github.com/goulu/45329ef041a368a663e5
def itimeout(iterable, timeout):
"""timeout for loops
:param iterable: any iterable
:param timeout: float max running time in seconds
:yield: items in iterator until timeout occurs
:raise: multiprocessing.TimeoutError if timeout occured
"""
if False: # handle debugger better one day ...
n = 100 * timeout
for i, x in enumerate(iterable):
yield x
if i > n:
break
else:
timer = Timer(timeout, lambda: None)
timer.start()
for x in iterable:
yield x
if timer.finished.is_set():
raise TimeoutError
# don't forget it, otherwise the thread never finishes...
timer.cancel()
# https://www.artima.com/weblogs/viewpost.jsp?thread=101605
registry = {}
class MultiMethod(object):
def __init__(self, name):
self.name = name
self.typemap = {}
def __call__(self, *args):
types = tuple(arg.__class__ for arg in args) # a generator expression!
function = self.typemap.get(types)
if function is None:
raise TypeError("no match")
return function(*args)
def register(self, types, function):
if types in self.typemap:
raise TypeError("duplicate registration")
self.typemap[types] = function
def multimethod(*types):
"""
allows to overload functions for various parameter types
@multimethod(int, int)
def foo(a, b):
...code for two ints...
@multimethod(float, float):
def foo(a, b):
...code for two floats...
@multimethod(str, str):
def foo(a, b):
...code for two strings...
"""
def register(function):
name = function.__name__
mm = registry.get(name)
if mm is None:
mm = registry[name] = MultiMethod(name)
mm.register(types, function)
return mm
return register
| goulu/Goulib | Goulib/decorators.py | Python | lgpl-3.0 | 5,279 |
# This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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/>.
'''
Created on 18.02.2015
@author: marscher
'''
import os
import numpy as np
from deeptime.clustering import ClusterModel, metrics
from pyemma._base.serialization.serialization import SerializableMixIn
from pyemma._base.model import Model
from pyemma._base.parallel import NJobsMixIn
from pyemma._ext.sklearn.base import ClusterMixin
from pyemma.coordinates.data._base.transformer import StreamingEstimationTransformer
from pyemma.util.annotators import fix_docs, aliased, alias
from pyemma.util.discrete_trajectories import index_states, sample_indexes_by_state
from pyemma.util.files import mkdir_p
@fix_docs
@aliased
class AbstractClustering(StreamingEstimationTransformer, Model, ClusterMixin, NJobsMixIn, SerializableMixIn):
"""
provides a common interface for cluster algorithms.
Parameters
----------
metric: str, default='euclidean'
metric to pass to c extension
n_jobs: int or None, default=None
How much threads to use during assignment
If None, all available CPUs will be used.
"""
def __init__(self, metric='euclidean', n_jobs=None):
super(AbstractClustering, self).__init__()
from ._ext import rmsd
metrics.register("minRMSD", rmsd)
self.metric = metric
self.clustercenters = None
self._previous_stride = -1
self._dtrajs = []
self._overwrite_dtrajs = False
self._index_states = []
self.n_jobs = n_jobs
__serialize_fields = ('_dtrajs', '_previous_stride', '_index_states', '_overwrite_dtrajs', '_precentered')
__serialize_version = 0
def set_model_params(self, clustercenters):
self.clustercenters = clustercenters
@property
@alias('cluster_centers_') # sk-learn compat.
def clustercenters(self):
""" Array containing the coordinates of the calculated cluster centers. """
return self._clustercenters
@clustercenters.setter
def clustercenters(self, val):
self._clustercenters = np.asarray(val, dtype='float32', order='C')[:] if val is not None else None
self._precentered = False
@property
def overwrite_dtrajs(self):
"""
Should existing dtraj files be overwritten. Set this property to True to overwrite.
"""
return self._overwrite_dtrajs
@overwrite_dtrajs.setter
def overwrite_dtrajs(self, value):
self._overwrite_dtrajs = value
@property
#@alias('labels_') # TODO: for fully sklearn-compat this would have to be a flat array!
def dtrajs(self):
"""Discrete trajectories (assigned data to cluster centers)."""
if len(self._dtrajs) == 0: # nothing assigned yet, doing that now
self._dtrajs = self.assign(stride=1)
return self._dtrajs # returning what we have saved
@property
def index_clusters(self):
"""Returns trajectory/time indexes for all the clusters
Returns
-------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this cluster occurs.
Each matrix has a number of rows equal to the number of occurrences of the corresponding state,
with rows consisting of a tuple (i, t), where i is the index of the trajectory and t is the time index
within the trajectory.
"""
if len(self._dtrajs) == 0: # nothing assigned yet, doing that now
self._dtrajs = self.assign()
if len(self._index_states) == 0: # has never been run
self._index_states = index_states(self._dtrajs)
return self._index_states
def sample_indexes_by_cluster(self, clusters, nsample, replace=True):
"""Samples trajectory/time indexes according to the given sequence of states.
Parameters
----------
clusters : iterable of integers
It contains the cluster indexes to be sampled
nsample : int
Number of samples per cluster. If replace = False, the number of returned samples per cluster could be smaller
if less than nsample indexes are available for a cluster.
replace : boolean, optional
Whether the sample is with or without replacement
Returns
-------
indexes : list of ndarray( (N, 2) )
List of the sampled indices by cluster.
Each element is an index array with a number of rows equal to N=len(sequence), with rows consisting of a
tuple (i, t), where i is the index of the trajectory and t is the time index within the trajectory.
"""
# Check if the catalogue (index_states)
if len(self._index_states) == 0: # has never been run
self._index_states = index_states(self.dtrajs)
return sample_indexes_by_state(self._index_states[clusters], nsample, replace=replace)
def _transform_array(self, X):
"""get closest index of point in :attr:`clustercenters` to x."""
X = np.require(X, dtype=np.float32, requirements='C')
# for performance reasons we pre-center the cluster centers for minRMSD.
if self.metric == 'minRMSD' and not self._precentered:
self._precentered = True
model = ClusterModel(cluster_centers=self.clustercenters, metric=self.metric)
dtraj = model.transform(X)
res = dtraj[:, None] # always return a column vector in this function
return res
def dimension(self):
"""output dimension of clustering algorithm (always 1)."""
return 1
def output_type(self):
return np.int32()
def assign(self, X=None, stride=1):
"""
Assigns the given trajectory or list of trajectories to cluster centers by using the discretization defined
by this clustering method (usually a Voronoi tesselation).
You can assign multiple times with different strides. The last result of assign will be saved and is available
as the attribute :func:`dtrajs`.
Parameters
----------
X : ndarray(T, n) or list of ndarray(T_i, n), optional, default = None
Optional input data to map, where T is the number of time steps and n is the number of dimensions.
When a list is provided they can have differently many time steps, but the number of dimensions need
to be consistent. When X is not provided, the result of assign is identical to get_output(), i.e. the
data used for clustering will be assigned. If X is given, the stride argument is not accepted.
stride : int, optional, default = 1
If set to 1, all frames of the input data will be assigned. Note that this could cause this calculation
to be very slow for large data sets. Since molecular dynamics data is usually
correlated at short timescales, it is often sufficient to obtain the discretization at a longer stride.
Note that the stride option used to conduct the clustering is independent of the assign stride.
This argument is only accepted if X is not given.
Returns
-------
Y : ndarray(T, dtype=int) or list of ndarray(T_i, dtype=int)
The discretized trajectory: int-array with the indexes of the assigned clusters, or list of such int-arrays.
If called with a list of trajectories, Y will also be a corresponding list of discrete trajectories
"""
if X is None:
# if the stride did not change and the discrete trajectory is already present,
# just return it
if self._previous_stride is stride and len(self._dtrajs) > 0:
return self._dtrajs
self._previous_stride = stride
skip = self.skip if hasattr(self, 'skip') else 0
# map to column vectors
mapped = self.get_output(stride=stride, chunk=self.chunksize, skip=skip)
# flatten and save
self._dtrajs = [np.transpose(m)[0] for m in mapped]
# return
return self._dtrajs
else:
if stride != 1:
raise ValueError('assign accepts either X or stride parameters, but not both. If you want to map '+
'only a subset of your data, extract the subset yourself and pass it as X.')
# map to column vector(s)
mapped = self.transform(X)
# flatten
if isinstance(mapped, np.ndarray):
mapped = np.transpose(mapped)[0]
else:
mapped = [np.transpose(m)[0] for m in mapped]
# return
return mapped
def save_dtrajs(self, trajfiles=None, prefix='',
output_dir='.',
output_format='ascii',
extension='.dtraj'):
"""saves calculated discrete trajectories. Filenames are taken from
given reader. If data comes from memory dtrajs are written to a default
filename.
Parameters
----------
trajfiles : list of str (optional)
names of input trajectory files, will be used generate output files.
prefix : str
prepend prefix to filenames.
output_dir : str
save files to this directory.
output_format : str
if format is 'ascii' dtrajs will be written as csv files, otherwise
they will be written as NumPy .npy files.
extension : str
file extension to append (eg. '.itraj')
"""
if extension[0] != '.':
extension = '.' + extension
# obtain filenames from input (if possible, reader is a featurereader)
if output_format == 'ascii':
from msmtools.dtraj import write_discrete_trajectory as write_dtraj
else:
from msmtools.dtraj import save_discrete_trajectory as write_dtraj
import os.path as path
output_files = []
if trajfiles is not None: # have filenames available?
for f in trajfiles:
p, n = path.split(f) # path and file
basename, _ = path.splitext(n)
if prefix != '':
name = "%s_%s%s" % (prefix, basename, extension)
else:
name = "%s%s" % (basename, extension)
# name = path.join(p, name)
output_files.append(name)
else:
for i in range(len(self.dtrajs)):
if prefix != '':
name = "%s_%i%s" % (prefix, i, extension)
else:
name = str(i) + extension
output_files.append(name)
assert len(self.dtrajs) == len(output_files)
if not os.path.exists(output_dir):
mkdir_p(output_dir)
for filename, dtraj in zip(output_files, self.dtrajs):
dest = path.join(output_dir, filename)
self.logger.debug('writing dtraj to "%s"' % dest)
try:
if path.exists(dest) and not self.overwrite_dtrajs:
raise EnvironmentError('Attempted to write dtraj "%s" which already existed. To automatically'
' overwrite existing files, set source.overwrite_dtrajs=True.' % dest)
write_dtraj(dest, dtraj)
except IOError:
self.logger.exception('Exception during writing dtraj to "%s"' % dest)
| markovmodel/PyEMMA | pyemma/coordinates/clustering/interface.py | Python | lgpl-3.0 | 12,270 |
<import resource="classpath:/alfresco/templates/org/alfresco/import/alfresco-util.js">
/**
* Cloud Sync Status Information
*
*/
function main()
{
AlfrescoUtil.param("nodeRef");
AlfrescoUtil.param("site", "defaultSite");
AlfrescoUtil.param("rootPage", "documentlibrary");
AlfrescoUtil.param("rootLabelId", "path.documents");
var nodeDetails = AlfrescoUtil.getNodeDetails(model.nodeRef, model.site);
if (nodeDetails)
{
model.item = nodeDetails.item;
model.node = nodeDetails.item.node;
model.paths = AlfrescoUtil.getPaths(nodeDetails, model.rootPage, model.rootLabelId);
}
}
main(); | loftuxab/community-edition-old | projects/slingshot/config/alfresco/site-webscripts/org/alfresco/components/node-details/node-path.get.js | JavaScript | lgpl-3.0 | 650 |
/*
* Gene.java
*
* Copyright (c) 2013, Pablo Garcia-Sanchez. All rights reserved.
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*
* Contributors:
*/
package es.ugr.osgiliath.evolutionary.individual;
import java.io.Serializable;
public interface Gene extends Serializable, Cloneable{
public Object clone();
}
| fergunet/osgiliath | OsgiliathEvolutionaryAlgorithm/src/es/ugr/osgiliath/evolutionary/individual/Gene.java | Java | lgpl-3.0 | 1,022 |
/*
* 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.orekit.propagation.sampling;
import org.orekit.errors.OrekitException;
import org.orekit.errors.PropagationException;
import org.orekit.propagation.SpacecraftState;
import org.orekit.time.AbsoluteDate;
/**
* This class wraps an object implementing {@link OrekitFixedStepHandler}
* into a {@link OrekitStepHandler}.
* <p>It mirrors the <code>StepNormalizer</code> interface from <a
* href="http://commons.apache.org/math/">commons-math</a> but
* provides a space-dynamics interface to the methods.</p>
* @author Luc Maisonobe
* @version $Revision$ $Date$
*/
public class OrekitStepNormalizer implements OrekitStepHandler {
/** Serializable UID. */
private static final long serialVersionUID = 6335110162884693078L;
/** Fixed time step. */
private double h;
/** Underlying step handler. */
private OrekitFixedStepHandler handler;
/** Last step date. */
private AbsoluteDate lastDate;
/** Last State vector. */
private SpacecraftState lastState;
/** Integration direction indicator. */
private boolean forward;
/** Simple constructor.
* @param h fixed time step (sign is not used)
* @param handler fixed time step handler to wrap
*/
public OrekitStepNormalizer(final double h, final OrekitFixedStepHandler handler) {
this.h = Math.abs(h);
this.handler = handler;
reset();
}
/** Determines whether this handler needs dense output.
* This handler needs dense output in order to provide data at
* regularly spaced steps regardless of the steps the propagator
* uses, so this method always returns true.
* @return always true
*/
public boolean requiresDenseOutput() {
return true;
}
/** Reset the step handler.
* Initialize the internal data as required before the first step is
* handled.
*/
public void reset() {
lastDate = null;
lastState = null;
forward = true;
}
/**
* Handle the last accepted step.
* @param interpolator interpolator for the last accepted step. For
* efficiency purposes, the various propagators reuse the same
* object on each call, so if the instance wants to keep it across
* all calls (for example to provide at the end of the propagation a
* continuous model valid throughout the propagation range), it
* should build a local copy using the clone method and store this
* copy.
* @param isLast true if the step is the last one
* @throws PropagationException this exception is propagated to the
* caller if the underlying user function triggers one
*/
public void handleStep(final OrekitStepInterpolator interpolator, final boolean isLast)
throws PropagationException {
try {
if (lastState == null) {
// initialize lastState in the first step case
lastDate = interpolator.getPreviousDate();
interpolator.setInterpolatedDate(lastDate);
lastState = interpolator.getInterpolatedState();
// take the propagation direction into account
forward = interpolator.getCurrentDate().compareTo(lastDate) >= 0;
if (!forward) {
h = -h;
}
}
// use the interpolator to push fixed steps events to the underlying handler
AbsoluteDate nextTime = lastDate.shiftedBy(h);
boolean nextInStep = forward ^ (nextTime.compareTo(interpolator.getCurrentDate()) > 0);
while (nextInStep) {
// output the stored previous step
handler.handleStep(lastState, false);
// store the next step
lastDate = nextTime;
interpolator.setInterpolatedDate(lastDate);
lastState = interpolator.getInterpolatedState();
// prepare next iteration
nextTime = nextTime.shiftedBy(h);
nextInStep = forward ^ (nextTime.compareTo(interpolator.getCurrentDate()) > 0);
}
if (isLast) {
// there will be no more steps,
// the stored one should be flagged as being the last
handler.handleStep(lastState, true);
}
} catch (OrekitException oe) {
// recover a possible embedded PropagationException
for (Throwable t = oe; t != null; t = t.getCause()) {
if (t instanceof PropagationException) {
throw (PropagationException) t;
}
}
throw new PropagationException(oe.getMessage(), oe);
}
}
}
| haisamido/SFDaaS | src/org/orekit/propagation/sampling/OrekitStepNormalizer.java | Java | lgpl-3.0 | 5,548 |
namespace MBINCompiler.Models.Structs
{
public class TkCameraWanderData : NMSTemplate
{
public bool CamWander;
public float CamWanderPhase;
public float CamWanderAmplitude;
[NMS(Size = 4, Ignore = true)]
public byte[] PaddingC;
}
}
| Bananasft/MBINCompiler | MBINCompiler/Models/Structs/TkCameraWanderData.cs | C# | lgpl-3.0 | 287 |
#include "visservotask.h"
void VisuoServoTask::switchtotask(VISTaskNameT tn){
curtaskname.vist = tn;
}
void VisuoServoTask::switchtoglobalframe(){
mft = GLOBAL;
}
void VisuoServoTask::switchtolocalframe(){
mft = LOCAL;
}
VisuoServoTask::VisuoServoTask(VISTaskNameT tn)
{
curtaskname.vist = tn;
desired_pose_range.setZero();
desired_dis = 0;
}
Eigen::Vector3d VisuoServoTask::get_desired_rotation_range(){
Eigen::Vector3d des;
des.setZero();
des = desired_pose_range;
return des;
}
double VisuoServoTask::get_desired_mv_dis(){
return desired_dis;
}
void VisuoServoTask::set_desired_mv_dis(double s){
desired_dis =s;
} | liqiang1980/VTFS | src/TaskModule/visservotask.cpp | C++ | lgpl-3.0 | 670 |
package de.invesdwin.nowicket.examples.guide.page.documentation.tagtransformations.tablesandchoices;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import de.invesdwin.nowicket.generated.binding.GeneratedBinding;
import de.invesdwin.nowicket.generated.binding.processor.element.SelectHtmlElement;
import de.invesdwin.nowicket.generated.binding.processor.visitor.builder.BindingInterceptor;
import de.invesdwin.nowicket.generated.binding.processor.visitor.builder.component.palette.ModelPalette;
@NotThreadSafe
public class TablesAndChoicesPanel extends Panel {
public TablesAndChoicesPanel(final String id, final IModel<TablesAndChoices> model) {
super(id, model);
new GeneratedBinding(this).withBindingInterceptor(new BindingInterceptor() {
@Override
public Component createSelect(final SelectHtmlElement e) {
if (TablesAndChoicesConstants.asMultiselectPalette.equals(e.getWicketId())) {
return new ModelPalette(e);
}
return super.createSelect(e);
}
}).bind();
}
}
| subes/invesdwin-nowicket | invesdwin-nowicket-examples/invesdwin-nowicket-examples-guide/src/main/java/de/invesdwin/nowicket/examples/guide/page/documentation/tagtransformations/tablesandchoices/TablesAndChoicesPanel.java | Java | lgpl-3.0 | 1,236 |
<?php
namespace Google\AdsApi\Dfp\v201711;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class LongCreativeTemplateVariable extends \Google\AdsApi\Dfp\v201711\CreativeTemplateVariable
{
/**
* @var int $defaultValue
*/
protected $defaultValue = null;
/**
* @param string $label
* @param string $uniqueName
* @param string $description
* @param boolean $isRequired
* @param int $defaultValue
*/
public function __construct($label = null, $uniqueName = null, $description = null, $isRequired = null, $defaultValue = null)
{
parent::__construct($label, $uniqueName, $description, $isRequired);
$this->defaultValue = $defaultValue;
}
/**
* @return int
*/
public function getDefaultValue()
{
return $this->defaultValue;
}
/**
* @param int $defaultValue
* @return \Google\AdsApi\Dfp\v201711\LongCreativeTemplateVariable
*/
public function setDefaultValue($defaultValue)
{
$this->defaultValue = (!is_null($defaultValue) && PHP_INT_SIZE === 4)
? floatval($defaultValue) : $defaultValue;
return $this;
}
}
| advanced-online-marketing/AOM | vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/LongCreativeTemplateVariable.php | PHP | lgpl-3.0 | 1,178 |
/* $Id: BioTreeContainer.hpp 103491 2007-05-04 17:18:18Z kazimird $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
*/
/// @file BioTreeContainer.hpp
/// User-defined methods of the data storage class.
///
/// This file was originally generated by application DATATOOL
/// using the following specifications:
/// 'biotree.asn'.
///
/// New methods or data members can be added to it if needed.
/// See also: BioTreeContainer_.hpp
#ifndef OBJECTS_BIOTREE_BIOTREECONTAINER_HPP
#define OBJECTS_BIOTREE_BIOTREECONTAINER_HPP
// generated includes
#include <objects/biotree/BioTreeContainer_.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
/////////////////////////////////////////////////////////////////////////////
class NCBI_BIOTREE_EXPORT CBioTreeContainer : public CBioTreeContainer_Base
{
typedef CBioTreeContainer_Base Tparent;
public:
// constructor
CBioTreeContainer(void);
// destructor
~CBioTreeContainer(void);
size_t GetNodeCount() const;
size_t GetLeafCount() const;
private:
// Prohibit copy constructor and assignment operator
CBioTreeContainer(const CBioTreeContainer& value);
CBioTreeContainer& operator=(const CBioTreeContainer& value);
};
/////////////////// CBioTreeContainer inline methods
// constructor
inline
CBioTreeContainer::CBioTreeContainer(void)
{
}
/////////////////// end of CBioTreeContainer inline methods
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
#endif // OBJECTS_BIOTREE_BIOTREECONTAINER_HPP
/* Original file checksum: lines: 94, chars: 2716, CRC32: ccfc4edf */
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/include/objects/biotree/BioTreeContainer.hpp | C++ | lgpl-3.0 | 2,831 |
package ch.hefr.gridgroup.magate.em;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ch.hefr.gridgroup.magate.MaGateEntity;
import ch.hefr.gridgroup.magate.em.ssl.BlatAntNestController;
import ch.hefr.gridgroup.magate.em.ssl.IBlatAntNestController;
import ch.hefr.gridgroup.magate.em.ssl.IBlatAntNestObserver;
import ch.hefr.gridgroup.magate.env.MaGateMessage;
import ch.hefr.gridgroup.magate.env.MaGateParam;
import ch.hefr.gridgroup.magate.storage.*;
public class SSLService implements IResDiscovery {
private static Log log = LogFactory.getLog(SSLService.class);
private MaGateEntity maGate;
private String maGateIdentity;
// private int timeout = 500;
private int counter = 0;
private Map<String, String> results = new HashMap<String, String>();
private HashMap<String,Object> maGateProfile = new HashMap<String,Object>();
public SSLService(MaGateEntity maGate) {
this.maGate = maGate;
this.maGateIdentity = maGate.getMaGateIdentity();
// Create and preserve the profile of MaGate Node
this.maGateProfile = new HashMap<String,Object>();
maGateProfile.put(MaGateMessage.MatchProfile_OS, this.maGate.getLRM().getOsType());
maGateProfile.put(MaGateMessage.MatchProfile_CPUCount, new Integer(this.maGate.getLRM().getNumOfPEPerResource()));
maGateProfile.put(MaGateMessage.MatchProfile_VO, this.maGate.getLRM().getVO());
// maGateProfile.put(MaGateMessage.MatchProfile_ExePrice, new Double(-1.0));
this.maGate.setMaGateProfile(maGateProfile);
// IMPORTANT: register a Nest for resource discovery
try {
this.maGate.getMaGateInfra().updateProfile(maGateIdentity, maGateProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Send synchronous query for searching remote MaGates
*/
public String[] syncSearchRemoteNode(ConcurrentHashMap<String,Object> extQuery) {
String queryId = this.maGateIdentity + "_" + java.util.UUID.randomUUID().toString();
String[] resultArray = null;
this.results.put(queryId, "");
HashMap<String,Object> query = new HashMap<String,Object>();
query.put(MaGateMessage.MatchProfile_OS, extQuery.get(MaGateMessage.MatchProfile_OS));
query.put(MaGateMessage.MatchProfile_CPUCount, extQuery.get(MaGateMessage.MatchProfile_CPUCount));
try {
// send the query
this.maGate.getMaGateInfra().startQuery(this.maGateIdentity, queryId, query);
// record the search issue
int currentCommunitySearch = this.maGate.getStorage().getCommunitySearch().get();
this.maGate.getStorage().setCommunitySearch(new AtomicInteger(currentCommunitySearch + 1));
/***************************************************************************
* Sleep a while and collect the returned results while the time is reached
***************************************************************************/
Thread.sleep(MaGateParam.timeSearchCommunity);
String result = this.results.get(queryId);
resultArray = result.split("_");
// Remove Redundancy
this.results.remove(queryId);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// In case new nodes discovered, put them into the cached netowrkNeighbor Map
NetworkNeighborsManager.cacheNetworkNeighbors(this.maGate, resultArray);
return resultArray;
}
/**
* Result found from the infrastructure
*/
public void onResultFound(String queryId, String matchedResult) {
if(this.results.containsKey(queryId)) {
String existResult = this.results.get(queryId);
this.results.put(queryId, existResult + matchedResult + "_");
} else {
this.results.put(queryId, matchedResult + "_");
}
}
public HashMap<String, Object> getMaGateProfile() {
return maGateProfile;
}
}
| huangye177/magate | src/main/java/ch/hefr/gridgroup/magate/em/SSLService.java | Java | lgpl-3.0 | 4,030 |
<?php
/**
* https://neofr.ag
* @author: Michaël BILCOT <michael.bilcot@neofr.ag>
*/
namespace NF\Modules\Monitoring;
use NF\NeoFrag\Addons\Module;
class Monitoring extends Module
{
protected function __info()
{
return [
'title' => 'Monitoring',
'description' => '',
'icon' => 'fas fa-heartbeat',
'link' => 'https://neofr.ag',
'author' => 'Michaël BILCOT & Jérémy VALENTIN <contact@neofrag.com>',
'license' => 'LGPLv3 <https://neofr.ag/license>',
'admin' => FALSE
];
}
public function need_checking()
{
return ($this->config->nf_monitoring_last_check < ($time = strtotime('01:00')) && time() > $time) || !file_exists('cache/monitoring/monitoring.json');
}
public function display()
{
if (file_exists('cache/monitoring/monitoring.json'))
{
foreach (array_merge(array_fill_keys(['danger', 'warning', 'info'], 0), array_count_values(array_map(function($a){
return $a[1];
}, json_decode(file_get_contents('cache/monitoring/monitoring.json'))->notifications))) as $class => $count)
{
if ($count)
{
return '<span class="float-right badge badge-'.$class.'">'.$count.'</span>';
}
}
}
return '';
}
}
| NeoFragCMS/neofrag-cms | modules/monitoring/monitoring.php | PHP | lgpl-3.0 | 1,215 |
#include "precice/impl/DataContext.hpp"
#include <memory>
namespace precice {
namespace impl {
logging::Logger DataContext::_log{"impl::DataContext"};
DataContext::DataContext(mesh::PtrData data, mesh::PtrMesh mesh)
{
PRECICE_ASSERT(data);
_providedData = data;
PRECICE_ASSERT(mesh);
_mesh = mesh;
}
mesh::PtrData DataContext::providedData()
{
PRECICE_ASSERT(_providedData);
return _providedData;
}
mesh::PtrData DataContext::toData()
{
PRECICE_ASSERT(_toData);
return _toData;
}
std::string DataContext::getDataName() const
{
PRECICE_ASSERT(_providedData);
return _providedData->getName();
}
int DataContext::getProvidedDataID() const
{
PRECICE_ASSERT(_providedData);
return _providedData->getID();
}
int DataContext::getFromDataID() const
{
PRECICE_TRACE();
PRECICE_ASSERT(hasMapping());
PRECICE_ASSERT(_fromData);
return _fromData->getID();
}
void DataContext::resetProvidedData()
{
PRECICE_TRACE();
_providedData->toZero();
}
void DataContext::resetToData()
{
PRECICE_TRACE();
_toData->toZero();
}
int DataContext::getToDataID() const
{
PRECICE_TRACE();
PRECICE_ASSERT(hasMapping());
PRECICE_ASSERT(_toData);
return _toData->getID();
}
int DataContext::getDataDimensions() const
{
PRECICE_TRACE();
PRECICE_ASSERT(_providedData);
return _providedData->getDimensions();
}
std::string DataContext::getMeshName() const
{
PRECICE_ASSERT(_mesh);
return _mesh->getName();
}
int DataContext::getMeshID() const
{
PRECICE_ASSERT(_mesh);
return _mesh->getID();
}
void DataContext::setMapping(MappingContext mappingContext, mesh::PtrData fromData, mesh::PtrData toData)
{
PRECICE_ASSERT(!hasMapping());
PRECICE_ASSERT(fromData);
PRECICE_ASSERT(toData);
_mappingContext = mappingContext;
PRECICE_ASSERT(fromData == _providedData || toData == _providedData, "Either fromData or toData has to equal _providedData.");
PRECICE_ASSERT(fromData->getName() == getDataName());
_fromData = fromData;
PRECICE_ASSERT(toData->getName() == getDataName());
_toData = toData;
PRECICE_ASSERT(_toData != _fromData);
}
bool DataContext::hasMapping() const
{
return hasReadMapping() || hasWriteMapping();
}
bool DataContext::hasReadMapping() const
{
return _toData == _providedData;
}
bool DataContext::hasWriteMapping() const
{
return _fromData == _providedData;
}
const MappingContext DataContext::mappingContext() const
{
PRECICE_ASSERT(hasMapping());
return _mappingContext;
}
} // namespace impl
} // namespace precice
| precice/precice | src/precice/impl/DataContext.cpp | C++ | lgpl-3.0 | 2,508 |
/*
* #%L
* Nerd4j CSV
* %%
* Copyright (C) 2013 Nerd4j
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
package org.nerd4j.csv.reader.binding;
import org.nerd4j.csv.exception.CSVToModelBindingException;
import org.nerd4j.csv.reader.CSVReaderMetadata;
import org.nerd4j.csv.registry.CSVRegistryEntry;
/**
* Represents a {@code Factory} able to build and configure
* {@link CSVToModelBinder}s which populates data models of the given type.
*
* @param <Model> type of the model returned by the builder.
*
* @author Nerd4j Team
*/
public interface CSVToModelBinderFactory<Model> extends CSVRegistryEntry
{
/**
* Returns a new CSV model binder which builds
* and fills the data model objects of the
* specified type.
*
* @param configuration used to configure the binding.
* @param columnMapping used to map columns with model.
* @return a new CSV model binder.
* @throws CSVToModelBindingException if binding configuration is inconsistent.
*/
public CSVToModelBinder<Model> getCSVToModelBinder( final CSVReaderMetadata<Model> configuration,
final Integer[] columnMapping )
throws CSVToModelBindingException;
} | nerd4j/nerd4j-csv | src/main/java/org/nerd4j/csv/reader/binding/CSVToModelBinderFactory.java | Java | lgpl-3.0 | 1,901 |
/* global shoproot */
/**
* 编辑分类
* @description Hope You Do Good But Not Evil
* @copyright Copyright 2014-2015 <ycchen@iwshop.cn>
* @license LGPL (http://www.gnu.org/licenses/lgpl.html)
* @author Chenyong Cai <ycchen@iwshop.cn>
* @package Wshop
* @link http://www.iwshop.cn
*/
requirejs(['jquery', 'util', 'fancyBox', 'jUploader'], function ($, Util, fancyBox, jUploader) {
$(function () {
$("#pd-cat-select").find("option[value='" + $('#cat_parent').val() + "']").get(0).selected = true;
$('#del-cate').click(function () {
if (confirm('你确定要删除这个分类吗')) {
$.post('?/wProduct/ajaxDelCategroy/', {
id: $('#cat_id').val()
}, function (r) {
r = parseInt(r);
if (r > 0) {
alert('删除成功');
window.parent.fnDelSelectCat();
window.parent.location.reload();
}
});
}
});
// alter
$('#save-cate').click(function () {
var data = $('#catForm').serializeArray();
$.post('?/wProduct/ajaxAlterCategroy/', {
id: $('#cat_id').val(),
data: data
}, function (r) {
r = parseInt(r);
if (r > 0) {
Util.Alert('保存成功');
window.parent.fnReloadTree();
} else {
Util.Alert('保存失败');
}
});
});
$.jUploader({
button: 'alter_categroy_image',
action: '?/wImages/ImageUpload/',
onComplete: function (fileName, response) {
if (response.ret_code == 0) {
$('#cat_image_src').val(response.ret_msg);
$('#catimage').attr('src', response.ret_msg).show();
$('#cat_none_pic').hide();
Util.Alert('上传图片成功');
} else {
Util.Alert('上传图片失败');
}
}
});
});
}); | mentallxm/iwshop | static/script/Wdmin/products/alter_categroy.js | JavaScript | lgpl-3.0 | 2,214 |
class DropCommunityPlans < ActiveRecord::Migration
def up
drop_table :community_plans
end
def down
create_table "community_plans" do |t|
t.integer "community_id", :null => false
t.integer "plan_level", :default => 0, :null => false
t.datetime "expires_at"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
end
end
| ziyoucaishi/marketplace | db/migrate/20151204083028_drop_community_plans.rb | Ruby | lgpl-3.0 | 452 |
<?php
/**
* Contao Open Source CMS, Copyright (C) 2005-2013 Leo Feyer
*
* Module Backend User Online - DCA
*
* @copyright Glen Langer 2012..2013 <http://www.contao.glen-langer.de>
* @author Glen Langer (BugBuster)
* @package BackendUserOnline
* @license LGPL
* @filesource
* @see https://github.com/BugBuster1701/backend_user_online
*/
/**
* DCA Config, overwrite label_callback
*/
$GLOBALS['TL_DCA']['tl_member']['list']['label']['label_callback'] = array('BugBuster\BackendUserOnline\DCA_member_onlineicon','addIcon');
| BugBuster1701/backend_user_online | dca/tl_member.php | PHP | lgpl-3.0 | 560 |
""" X """
import cPickle as pickle
import os
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class PlotInterface(object):
def plot_timeseries(self, times, values):
pass
def plot_sinwave(self, times, sinewave):
pass
def plot_area_ratio(self, on_period_area, off_period_area):
pass
def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold):
pass
def plot_acf(self, times, acf):
pass
def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx):
pass
def show(self):
pass
class ImageOutput(PlotInterface):
""" Output the timeseries data and the period estimate as plot in png format """
def __init__(self, jobid, metricname):
ijobid = int(jobid)
top = (ijobid / 1000000)
middle = (ijobid / 1000) % 1000
try:
os.makedirs("{}/{}".format(top, middle))
except OSError:
pass
self.outfilename = "{}/{}/{}_{}.png".format(top, middle, jobid, metricname)
self.fig = plt.figure()
self.data_ax = plt.subplot(211, xlabel='Elapsed time (s)', ylabel='Data rate (MB/s)')
self.sine_ax = None
self.verbose = False
def plot_timeseries(self, times, values):
self.data_ax.plot(times, values / 1024.0 / 1024.0, label='Timeseries')
def plot_sinwave(self, times, sinewave):
self.sine_ax = plt.subplot(212, xlabel='Elapsed time (s)', ylabel='Data rate (MB/s)')
self.sine_ax.plot(times, sinewave / 1024.0 / 1024.0, label='Estimate')
def show(self):
self.fig.tight_layout()
self.fig.savefig(self.outfilename, format='png', transparent=True)
class Dumper(object):
def __init__(self, filename='data.dat'):
self.filename = filename
self.data = {}
self.verbose = True
def plot_timeseries(self, times, values):
self.data['timeseries'] = (times, values)
def plot_sinwave(self, times, sinewave):
self.data['sinewave'] = (times, sinewave)
def plot_area_ratio(self, on_period_area, off_period_area):
self.data['area_ratio'] = (on_period_area, off_period_area)
def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold):
self.data['periodogram'] = (periods, powers, hints, power_threshold, time_threshold)
def plot_acf(self, times, acf):
self.data['acf'] = (times, acf)
def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx):
self.data['acf_validation'] = (times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx)
def show(self):
with open(self.filename, 'wb') as fp:
pickle.dump(self.data, fp)
def load(self):
with open(self.filename, 'rb') as fp:
self.data = pickle.load(fp)
class Plotter(object):
def __init__(self, title="Autoperiod", filename='output.pdf', figsize=(4, 3), verbose=False):
self.title = title
self.filename = filename
self.fig = plt.figure()
self.figsize = figsize
self.verbose = verbose
self.timeseries_ax = plt.subplot2grid((3, 10), (0, 0), colspan=9, xlabel='Times', ylabel='Values')
self.area_ratio_ax = plt.subplot2grid((3, 10), (0, 9), colspan=1, xticks=(1, 2), xticklabels=("on", "off"))
self.area_ratio_ax.get_yaxis().set_visible(False)
self.periodogram_ax = plt.subplot2grid((3, 10), (1, 0), colspan=10, xlabel='Period', ylabel='Power')
self.acf_ax = plt.subplot2grid((3, 10), (2, 0), colspan=10, xlabel='Lag', ylabel='Correlation')
self.time_threshold = None
def plot_timeseries(self, times, values):
self.timeseries_ax.plot(times, values, label='Timeseries')
self.timeseries_ax.legend()
def plot_sinwave(self, times, sinwave):
self.timeseries_ax.plot(times, sinwave, label='Estimated Period')
self.timeseries_ax.legend()
def plot_area_ratio(self, on_period_area, off_period_area):
self.area_ratio_ax.bar(1, on_period_area)
self.area_ratio_ax.bar(2, off_period_area)
self.area_ratio_ax.legend()
def plot_periodogram(self, periods, powers, hints, power_threshold, time_threshold):
self.time_threshold = time_threshold
self.periodogram_ax.plot(periods, powers, label='Periodogram')
self.periodogram_ax.scatter([p for i, p in hints], [powers[i] for i, p in hints], c='red', marker='x', label='Period Hints')
self.periodogram_ax.axhline(power_threshold, color='green', linewidth=1, linestyle='dashed', label='Min Power')
#self.periodogram_ax.axvline(time_threshold, c='purple', linewidth=1, linestyle='dashed', label='Max Period')
self.periodogram_ax.legend()
self.periodogram_ax.set_xlim([0, self.time_threshold])
def plot_acf(self, times, acf):
self.acf_ax.plot(times, acf, '-o', lw=0.5, ms=2, label='Autocorrelation')
if self.time_threshold is not None:
self.acf_ax.set_xlim([0, self.time_threshold])
self.acf_ax.legend()
def plot_acf_validation(self, times, acf, times1, m1, c1, err1, times2, m2, c2, err2, split_idx, peak_idx):
self.acf_ax.plot(times1, c1 + m1 * times1, c='r', label='Slope: {}, Error: {}'.format(m1, err1))
self.acf_ax.plot(times2, c2 + m2 * times2, c='r', label='Slope: {}, Error: {}'.format(m2, err2))
self.acf_ax.scatter(times[split_idx], acf[split_idx], c='y', label='Split point: {}'.format(times[split_idx]))
self.acf_ax.scatter(times[peak_idx], acf[peak_idx], c='g', label='Peak point: {}'.format(times[peak_idx]))
self.acf_ax.legend()
def show(self):
self.fig.tight_layout()
if self.filename:
self.fig.set_size_inches(*self.figsize)
self.fig.savefig(self.filename, format='pdf', facecolor=self.fig.get_facecolor())
def main():
""" X """
d = Dumper('gpfs-fsios-write_bytes_data.dat')
d.load()
p = Plotter()
p.plot_timeseries(*d.data['timeseries'])
p.plot_sinwave(*d.data['sinewave'])
p.plot_area_ratio(*d.data['area_ratio'])
p.plot_periodogram(*d.data['periodogram'])
p.plot_acf(*d.data['acf'])
p.plot_acf_validation(*d.data['acf_validation'])
p.show()
if __name__ == "__main__":
main()
| ubccr/supremm | src/supremm/datadumper.py | Python | lgpl-3.0 | 6,457 |
package test.jts.perf.operation.union;
import java.util.Iterator;
import java.util.List;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.io.WKTWriter;
import com.vividsolutions.jts.operation.union.CascadedPolygonUnion;
import com.vividsolutions.jts.util.Stopwatch;
public class UnionPerfTester
{
public static final int CASCADED = 1;
public static final int ITERATED = 2;
public static final int BUFFER0 = 3;
public static final int ORDERED = 4;
public static void run(String testName, int testType, List polys)
{
UnionPerfTester test = new UnionPerfTester(polys);
test.run(testName, testType);
}
public static void runAll(List polys)
{
UnionPerfTester test = new UnionPerfTester(polys);
test.runAll();
}
static final int MAX_ITER = 1;
static PrecisionModel pm = new PrecisionModel();
static GeometryFactory fact = new GeometryFactory(pm, 0);
static WKTReader wktRdr = new WKTReader(fact);
static WKTWriter wktWriter = new WKTWriter();
Stopwatch sw = new Stopwatch();
GeometryFactory factory = new GeometryFactory();
private List polys;
public UnionPerfTester(List polys) {
this.polys = polys;
}
public void runAll()
{
System.out.println("# items: " + polys.size());
run("Cascaded", CASCADED, polys);
// run("Buffer-0", BUFFER0, polys);
run("Iterated", ITERATED, polys);
}
public void run(String testName, int testType)
{
System.out.println();
System.out.println("======= Union Algorithm: " + testName + " ===========");
Stopwatch sw = new Stopwatch();
for (int i = 0; i < MAX_ITER; i++) {
Geometry union = null;
switch (testType) {
case CASCADED:
union = unionCascaded(polys);
break;
case ITERATED:
union = unionAllSimple(polys);
break;
case BUFFER0:
union = unionAllBuffer(polys);
break;
}
// printFormatted(union);
}
System.out.println("Finished in " + sw.getTimeString());
}
private void printFormatted(Geometry geom)
{
WKTWriter writer = new WKTWriter();
System.out.println(writer.writeFormatted(geom));
}
public Geometry unionAllSimple(List geoms)
{
Geometry unionAll = null;
int count = 0;
for (Iterator i = geoms.iterator(); i.hasNext(); ) {
Geometry geom = (Geometry) i.next();
if (unionAll == null) {
unionAll = (Geometry) geom.clone();
}
else {
unionAll = unionAll.union(geom);
}
count++;
if (count % 100 == 0) {
System.out.print(".");
// System.out.println("Adding geom #" + count);
}
}
return unionAll;
}
public Geometry unionAllBuffer(List geoms)
{
Geometry gColl = factory.buildGeometry(geoms);
Geometry unionAll = gColl.buffer(0.0);
return unionAll;
}
public Geometry unionCascaded(List geoms)
{
return CascadedPolygonUnion.union(geoms);
}
/*
public Geometry unionAllOrdered(List geoms)
{
// return OrderedUnion.union(geoms);
}
*/
void printItemEnvelopes(List tree)
{
Envelope itemEnv = new Envelope();
for (Iterator i = tree.iterator(); i.hasNext(); ) {
Object o = i.next();
if (o instanceof List) {
printItemEnvelopes((List) o);
}
else if (o instanceof Geometry) {
itemEnv.expandToInclude( ((Geometry) o).getEnvelopeInternal());
}
}
System.out.println(factory.toGeometry(itemEnv));
}
}
| Semantive/jts | src/test/test/jts/perf/operation/union/UnionPerfTester.java | Java | lgpl-3.0 | 3,545 |
<?php
// ---------- CREDITS ----------
// Mirrored from pocketmine\network\mcpe\protocol\PlayerActionPacket.php
// Mirroring was done by @CortexPE of @LeverylTeam :D
//
// NOTE: We know that this was hacky... But It's here to still provide support for old plugins
// ---------- CREDITS ----------
namespace pocketmine\network\protocol;
use pocketmine\network\mcpe\protocol\PlayerActionPacket as Original;
class PlayerActionPacket extends Original {
}
| LeverylTeam/Leveryl | src/pocketmine/network/protocol/PlayerActionPacket.php | PHP | lgpl-3.0 | 461 |
# Copyright (c) 2010-2018 Benjamin Peterson
#
# 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.
"""
Utilities for writing code that runs on Python 2 and 3
WARNING: THIS VERSION OF SIX HAS BEEN MODIFIED.
Changed line 658:
def u(s):
s = s.replace(r'\\', r'\\\\')
if isinstance(s, unicode):
return s
else:
return unicode(s, "unicode_escape")
"""
from __future__ import absolute_import
import functools
import itertools
import operator
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
__version__ = "1.12.0"
# Useful for very coarse version differentiation.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
PY34 = sys.version_info[0:2] >= (3, 4)
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
try:
# This is a bit ugly, but it avoids running this again by
# removing this descriptor.
delattr(obj.__class__, self.name)
except AttributeError:
pass
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
def __getattr__(self, attr):
_module = self._resolve()
value = getattr(_module, attr)
setattr(self, attr, value)
return value
class _LazyModule(types.ModuleType):
def __init__(self, name):
super(_LazyModule, self).__init__(name)
self.__doc__ = self.__class__.__doc__
def __dir__(self):
attrs = ["__doc__", "__name__"]
attrs += [attr.name for attr in self._moved_attributes]
return attrs
# Subclasses should override this
_moved_attributes = []
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _SixMetaPathImporter(object):
"""
A meta path importer to import six.moves and its submodules.
This class implements a PEP302 finder and loader. It should be compatible
with Python 2.5 and all existing versions of Python3
"""
def __init__(self, six_module_name):
self.name = six_module_name
self.known_modules = {}
def _add_module(self, mod, *fullnames):
for fullname in fullnames:
self.known_modules[self.name + "." + fullname] = mod
def _get_module(self, fullname):
return self.known_modules[self.name + "." + fullname]
def find_module(self, fullname, path=None):
if fullname in self.known_modules:
return self
return None
def __get_module(self, fullname):
try:
return self.known_modules[fullname]
except KeyError:
raise ImportError("This loader does not know module " + fullname)
def load_module(self, fullname):
try:
# in case of a reload
return sys.modules[fullname]
except KeyError:
pass
mod = self.__get_module(fullname)
if isinstance(mod, MovedModule):
mod = mod._resolve()
else:
mod.__loader__ = self
sys.modules[fullname] = mod
return mod
def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__")
def get_code(self, fullname):
"""Return None
Required, if is_package is implemented"""
self.__get_module(fullname) # eventually raises ImportError
return None
get_source = get_code # same as get_code
_importer = _SixMetaPathImporter(__name__)
class _MovedItems(_LazyModule):
"""Lazy loading of moved objects"""
__path__ = [] # mark as package
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("intern", "__builtin__", "sys"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
MovedAttribute("getoutput", "commands", "subprocess"),
MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("UserDict", "UserDict", "collections"),
MovedAttribute("UserList", "UserList", "collections"),
MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),
MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"),
MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("_thread", "thread", "_thread"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
]
# Add windows specific modules.
if sys.platform == "win32":
_moved_attributes += [
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
_importer._add_module(attr, "moves." + attr.name)
del attr
_MovedItems._moved_attributes = _moved_attributes
moves = _MovedItems(__name__ + ".moves")
_importer._add_module(moves, "moves")
class Module_six_moves_urllib_parse(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_parse"""
_urllib_parse_moved_attributes = [
MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
MovedAttribute("urljoin", "urlparse", "urllib.parse"),
MovedAttribute("urlparse", "urlparse", "urllib.parse"),
MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
MovedAttribute("quote", "urllib", "urllib.parse"),
MovedAttribute("quote_plus", "urllib", "urllib.parse"),
MovedAttribute("unquote", "urllib", "urllib.parse"),
MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"),
MovedAttribute("urlencode", "urllib", "urllib.parse"),
MovedAttribute("splitquery", "urllib", "urllib.parse"),
MovedAttribute("splittag", "urllib", "urllib.parse"),
MovedAttribute("splituser", "urllib", "urllib.parse"),
MovedAttribute("splitvalue", "urllib", "urllib.parse"),
MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
MovedAttribute("uses_params", "urlparse", "urllib.parse"),
MovedAttribute("uses_query", "urlparse", "urllib.parse"),
MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
]
for attr in _urllib_parse_moved_attributes:
setattr(Module_six_moves_urllib_parse, attr.name, attr)
del attr
Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
"moves.urllib_parse", "moves.urllib.parse")
class Module_six_moves_urllib_error(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_error"""
_urllib_error_moved_attributes = [
MovedAttribute("URLError", "urllib2", "urllib.error"),
MovedAttribute("HTTPError", "urllib2", "urllib.error"),
MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
]
for attr in _urllib_error_moved_attributes:
setattr(Module_six_moves_urllib_error, attr.name, attr)
del attr
Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
"moves.urllib_error", "moves.urllib.error")
class Module_six_moves_urllib_request(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_request"""
_urllib_request_moved_attributes = [
MovedAttribute("urlopen", "urllib2", "urllib.request"),
MovedAttribute("install_opener", "urllib2", "urllib.request"),
MovedAttribute("build_opener", "urllib2", "urllib.request"),
MovedAttribute("pathname2url", "urllib", "urllib.request"),
MovedAttribute("url2pathname", "urllib", "urllib.request"),
MovedAttribute("getproxies", "urllib", "urllib.request"),
MovedAttribute("Request", "urllib2", "urllib.request"),
MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
MovedAttribute("FileHandler", "urllib2", "urllib.request"),
MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
MovedAttribute("urlretrieve", "urllib", "urllib.request"),
MovedAttribute("urlcleanup", "urllib", "urllib.request"),
MovedAttribute("URLopener", "urllib", "urllib.request"),
MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
MovedAttribute("parse_http_list", "urllib2", "urllib.request"),
MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),
]
for attr in _urllib_request_moved_attributes:
setattr(Module_six_moves_urllib_request, attr.name, attr)
del attr
Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
"moves.urllib_request", "moves.urllib.request")
class Module_six_moves_urllib_response(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_response"""
_urllib_response_moved_attributes = [
MovedAttribute("addbase", "urllib", "urllib.response"),
MovedAttribute("addclosehook", "urllib", "urllib.response"),
MovedAttribute("addinfo", "urllib", "urllib.response"),
MovedAttribute("addinfourl", "urllib", "urllib.response"),
]
for attr in _urllib_response_moved_attributes:
setattr(Module_six_moves_urllib_response, attr.name, attr)
del attr
Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
"moves.urllib_response", "moves.urllib.response")
class Module_six_moves_urllib_robotparser(_LazyModule):
"""Lazy loading of moved objects in six.moves.urllib_robotparser"""
_urllib_robotparser_moved_attributes = [
MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
]
for attr in _urllib_robotparser_moved_attributes:
setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
del attr
Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
"moves.urllib_robotparser", "moves.urllib.robotparser")
class Module_six_moves_urllib(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
__path__ = [] # mark as package
parse = _importer._get_module("moves.urllib_parse")
error = _importer._get_module("moves.urllib_error")
request = _importer._get_module("moves.urllib_request")
response = _importer._get_module("moves.urllib_response")
robotparser = _importer._get_module("moves.urllib_robotparser")
def __dir__(self):
return ['parse', 'error', 'request', 'response', 'robotparser']
_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
"moves.urllib")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_closure = "__closure__"
_func_code = "__code__"
_func_defaults = "__defaults__"
_func_globals = "__globals__"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_closure = "func_closure"
_func_code = "func_code"
_func_defaults = "func_defaults"
_func_globals = "func_globals"
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
next = advance_iterator
try:
callable = callable
except NameError:
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
if PY3:
def get_unbound_function(unbound):
return unbound
create_bound_method = types.MethodType
def create_unbound_method(func, cls):
return func
Iterator = object
else:
def get_unbound_function(unbound):
return unbound.im_func
def create_bound_method(func, obj):
return types.MethodType(func, obj, obj.__class__)
def create_unbound_method(func, cls):
return types.MethodType(func, None, cls)
class Iterator(object):
def next(self):
return type(self).__next__(self)
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
get_function_closure = operator.attrgetter(_func_closure)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
get_function_globals = operator.attrgetter(_func_globals)
if PY3:
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw))
def iterlists(d, **kw):
return iter(d.lists(**kw))
viewkeys = operator.methodcaller("keys")
viewvalues = operator.methodcaller("values")
viewitems = operator.methodcaller("items")
else:
def iterkeys(d, **kw):
return d.iterkeys(**kw)
def itervalues(d, **kw):
return d.itervalues(**kw)
def iteritems(d, **kw):
return d.iteritems(**kw)
def iterlists(d, **kw):
return d.iterlists(**kw)
viewkeys = operator.methodcaller("viewkeys")
viewvalues = operator.methodcaller("viewvalues")
viewitems = operator.methodcaller("viewitems")
_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
_add_doc(iteritems,
"Return an iterator over the (key, value) pairs of a dictionary.")
_add_doc(iterlists,
"Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY3:
def b(s):
return s.encode("latin-1")
def u(s, encoding=None):
return str(s)
unichr = chr
import struct
int2byte = struct.Struct(">B").pack
del struct
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
_assertCountEqual = "assertCountEqual"
if sys.version_info[1] <= 1:
_assertRaisesRegex = "assertRaisesRegexp"
_assertRegex = "assertRegexpMatches"
else:
_assertRaisesRegex = "assertRaisesRegex"
_assertRegex = "assertRegex"
else:
def b(s):
return s
# Workaround for standalone backslash
def u(s, encoding="unicode_escape"):
if not isinstance(s, basestring):
s = unicode(s, encoding)
s = s.replace(r'\\', r'\\\\')
if isinstance(s, unicode):
return s
else:
return unicode(s, encoding)
unichr = unichr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
iterbytes = functools.partial(itertools.imap, ord)
import StringIO
StringIO = BytesIO = StringIO.StringIO
_assertCountEqual = "assertItemsEqual"
_assertRaisesRegex = "assertRaisesRegexp"
_assertRegex = "assertRegexpMatches"
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
def assertCountEqual(self, *args, **kwargs):
return getattr(self, _assertCountEqual)(*args, **kwargs)
def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)
def assertRegex(self, *args, **kwargs):
return getattr(self, _assertRegex)(*args, **kwargs)
if PY3:
exec_ = getattr(moves.builtins, "exec")
def reraise(tp, value, tb=None):
try:
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
finally:
value = None
tb = None
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
exec_("""def reraise(tp, value, tb=None):
try:
raise tp, value, tb
finally:
tb = None
""")
if sys.version_info[:2] == (3, 2):
exec_("""def raise_from(value, from_value):
try:
if from_value is None:
raise value
raise value from from_value
finally:
value = None
""")
elif sys.version_info[:2] > (3, 2):
exec_("""def raise_from(value, from_value):
try:
raise value from from_value
finally:
value = None
""")
else:
def raise_from(value, from_value):
raise value
print_ = getattr(moves.builtins, "print", None)
if print_ is None:
def print_(*args, **kwargs):
"""The new-style print function for Python 2.4 and 2.5."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
# If the file has an encoding, encode unicode with it.
if (isinstance(fp, file) and
isinstance(data, unicode) and
fp.encoding is not None):
errors = getattr(fp, "errors", None)
if errors is None:
errors = "strict"
data = data.encode(fp.encoding, errors)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
if sys.version_info[:2] < (3, 3):
_print = print_
def print_(*args, **kwargs):
fp = kwargs.get("file", sys.stdout)
flush = kwargs.pop("flush", False)
_print(*args, **kwargs)
if flush and fp is not None:
fp.flush()
_add_doc(reraise, """Reraise an exception.""")
if sys.version_info[0:2] < (3, 4):
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
def wrapper(f):
f = functools.wraps(wrapped, assigned, updated)(f)
f.__wrapped__ = wrapped
return f
return wrapper
else:
wraps = functools.wraps
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
@classmethod
def __prepare__(cls, name, this_bases):
return meta.__prepare__(name, bases)
return type.__new__(metaclass, 'temporary_class', (), {})
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
if hasattr(cls, '__qualname__'):
orig_vars['__qualname__'] = cls.__qualname__
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
def ensure_binary(s, encoding='utf-8', errors='strict'):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.encode(encoding, errors)
elif isinstance(s, binary_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeError("not expecting type '%s'" % type(s))
if PY2 and isinstance(s, text_type):
s = s.encode(encoding, errors)
elif PY3 and isinstance(s, binary_type):
s = s.decode(encoding, errors)
return s
def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encoding, errors)
elif isinstance(s, text_type):
return s
else:
raise TypeError("not expecting type '%s'" % type(s))
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
# Complete the moves implementation.
# This code is at the end of this module to speed up module loading.
# Turn this module into a package.
__path__ = [] # required for PEP 302 and PEP 451
__package__ = __name__ # see PEP 366 @ReservedAssignment
if globals().get("__spec__") is not None:
__spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
# Remove other six meta path importers, since they cause problems. This can
# happen if six is removed from sys.modules and then reloaded. (Setuptools does
# this for some reason.)
if sys.meta_path:
for i, importer in enumerate(sys.meta_path):
# Here's some real nastiness: Another "instance" of the six module might
# be floating around. Therefore, we can't use isinstance() to check for
# the six meta path importer, since the other six instance will have
# inserted an importer with different class.
if (type(importer).__name__ == "_SixMetaPathImporter" and
importer.name == __name__):
del sys.meta_path[i]
break
del i, importer
# Finally, add the importer to the meta path import hook.
sys.meta_path.append(_importer)
| krathjen/studiolibrary | src/studiovendor/six.py | Python | lgpl-3.0 | 32,901 |
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: .......
*
* File Description:
* .......
*
* Remark:
* This code was originally generated by application DATATOOL
* using the following specifications:
* 'mmdb2.asn'.
*/
// standard includes
#include <ncbi_pch.hpp>
// generated includes
#include <objects/mmdb2/Reference_frame.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// destructor
CReference_frame::~CReference_frame(void)
{
}
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
/* Original file checksum: lines: 57, chars: 1738, CRC32: 6dc78079 */
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/objects/mmdb2/Reference_frame.cpp | C++ | lgpl-3.0 | 1,865 |
package com.example;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ExampleTest
{
@Test
public void foo()
{
Assert.assertTrue(new Example().foo());
}
}
| konvergeio/cofoja-example | src/test/java/com/example/ExampleTest.java | Java | lgpl-3.0 | 212 |
/*
* This file is part of MyPet
*
* Copyright © 2011-2016 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.api.skill.experience;
import org.bukkit.entity.EntityType;
import java.util.HashMap;
import java.util.Map;
public class MonsterExperience {
public static final Map<String, MonsterExperience> mobExp = new HashMap<>();
private static MonsterExperience unknown = new MonsterExperience(0., "UNKNOWN");
static {
mobExp.put("SKELETON", new MonsterExperience(5., "SKELETON"));
mobExp.put("ZOMBIE", new MonsterExperience(5., "ZOMBIE"));
mobExp.put("SPIDER", new MonsterExperience(5., "SPIDER"));
mobExp.put("WOLF", new MonsterExperience(1., 3., "WOLF"));
mobExp.put("CREEPER", new MonsterExperience(5., "CREEPER"));
mobExp.put("GHAST", new MonsterExperience(5., "GHAST"));
mobExp.put("PIG_ZOMBIE", new MonsterExperience(5., "PIG_ZOMBIE"));
mobExp.put("ENDERMAN", new MonsterExperience(5., "ENDERMAN"));
mobExp.put("ENDERMITE", new MonsterExperience(3., "ENDERMITE"));
mobExp.put("CAVE_SPIDER", new MonsterExperience(5., "CAVE_SPIDER"));
mobExp.put("MAGMA_CUBE", new MonsterExperience(1., 4., "MAGMA_CUBE"));
mobExp.put("SLIME", new MonsterExperience(1., 4., "SLIME"));
mobExp.put("SILVERFISH", new MonsterExperience(5., "SILVERFISH"));
mobExp.put("BLAZE", new MonsterExperience(10., "BLAZE"));
mobExp.put("GIANT", new MonsterExperience(25., "GIANT"));
mobExp.put("GUARDIAN", new MonsterExperience(10., "GUARDIAN"));
mobExp.put("COW", new MonsterExperience(1., 3., "COW"));
mobExp.put("PIG", new MonsterExperience(1., 3., "PIG"));
mobExp.put("CHICKEN", new MonsterExperience(1., 3., "CHICKEN"));
mobExp.put("SQUID", new MonsterExperience(1., 3., "SQUID"));
mobExp.put("SHEEP", new MonsterExperience(1., 3., "SHEEP"));
mobExp.put("OCELOT", new MonsterExperience(1., 3., "OCELOT"));
mobExp.put("MUSHROOM_COW", new MonsterExperience(1., 3., "MUSHROOM_COW"));
mobExp.put("VILLAGER", new MonsterExperience(0., "VILLAGER"));
mobExp.put("SHULKER", new MonsterExperience(5., "SHULKER"));
mobExp.put("SNOWMAN", new MonsterExperience(0., "SNOWMAN"));
mobExp.put("IRON_GOLEM", new MonsterExperience(0., "IRON_GOLEM"));
mobExp.put("ENDER_DRAGON", new MonsterExperience(20000., "ENDER_DRAGON"));
mobExp.put("WITCH", new MonsterExperience(10., "WITCH"));
mobExp.put("BAT", new MonsterExperience(1., "BAT"));
mobExp.put("ENDER_CRYSTAL", new MonsterExperience(10., "ENDER_CRYSTAL"));
mobExp.put("WITHER", new MonsterExperience(100., "WITHER"));
mobExp.put("RABBIT", new MonsterExperience(1., "RABBIT"));
mobExp.put("VINDICATOR", new MonsterExperience(5., "VINDICATOR"));
mobExp.put("EVOKER", new MonsterExperience(10., "EVOKER"));
mobExp.put("VEX", new MonsterExperience(3., "VEX"));
mobExp.put("LLAMA", new MonsterExperience(0., "LLAMA"));
}
private double min;
private double max;
private String entityType;
public MonsterExperience(double min, double max, String entityType) {
if (max >= min) {
this.max = max;
this.min = min;
} else if (max <= min) {
this.max = min;
this.min = max;
}
this.entityType = entityType;
}
public MonsterExperience(double exp, String entityType) {
this.max = exp;
this.min = exp;
this.entityType = entityType;
}
public double getRandomExp() {
return max == min ? max : ((int) (doubleRandom(min, max) * 100)) / 100.;
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
public EntityType getEntityType() {
return EntityType.valueOf(entityType);
}
public void setMin(double min) {
this.min = min;
if (min > max) {
max = min;
}
}
public void setMax(double max) {
this.max = max;
if (max < min) {
min = max;
}
}
public void setExp(double exp) {
max = (min = exp);
}
private static double doubleRandom(double low, double high) {
return Math.random() * (high - low) + low;
}
@Override
public String toString() {
return entityType + "{min=" + min + ", max=" + max + "}";
}
public static MonsterExperience getMonsterExperience(EntityType type) {
if (mobExp.containsKey(type.name())) {
return mobExp.get(type.name());
}
return unknown;
}
} | jjm223/MyPet | modules/API/src/main/java/de/Keyle/MyPet/api/skill/experience/MonsterExperience.java | Java | lgpl-3.0 | 5,371 |
// HTMLParser Library - A java-based parser for HTML
// http://htmlparser.org
// Copyright (C) 2006 Somik Raha
//
// Revision Control Information
//
// $URL: file:///svn/p/htmlparser/code/tags/HTMLParserProject-2.1/parser/src/test/java/org/htmlparser/tests/utilTests/AllTests.java $
// $Author: derrickoswald $
// $Date: 2006-09-16 14:44:17 +0000 (Sat, 16 Sep 2006) $
// $Revision: 4 $
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Common Public License; either
// version 1.0 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
// Common Public License for more details.
//
// You should have received a copy of the Common Public License
// along with this library; if not, the license is available from
// the Open Source Initiative (OSI) website:
// http://opensource.org/licenses/cpl1.0.php
package org.htmlparser.tests.utilTests;
import junit.framework.TestSuite;
import org.htmlparser.tests.ParserTestCase;
/**
* Insert the type's description here.
* Creation date: (6/17/2001 6:07:04 PM)
*/
public class AllTests extends ParserTestCase
{
static
{
System.setProperty ("org.htmlparser.tests.utilTests.AllTests", "AllTests");
}
/**
* AllTests constructor comment.
* @param name java.lang.String
*/
public AllTests(String name) {
super(name);
}
/**
* Insert the method's description here.
* Creation date: (6/17/2001 6:07:15 PM)
* @return junit.framework.TestSuite
*/
public static TestSuite suite()
{
TestSuite suite = new TestSuite("Utility Tests");
suite.addTestSuite(BeanTest.class);
suite.addTestSuite(HTMLParserUtilsTest.class);
suite.addTestSuite(NodeListTest.class);
suite.addTestSuite(NonEnglishTest.class);
suite.addTestSuite(SortTest.class);
return suite;
}
}
| socialwareinc/html-parser | parser/src/test/java/org/htmlparser/tests/utilTests/AllTests.java | Java | lgpl-3.0 | 2,165 |
/**
* Copyright (c) 2012-2014, Andrea Funto'. All rights reserved. See LICENSE for details.
*/
package org.dihedron.patterns.visitor.nodes;
import java.util.Map;
import org.dihedron.core.License;
import org.dihedron.patterns.visitor.VisitorException;
/**
* @author Andrea Funto'
*/
@License
public class ModifiableMapEntryNode extends UnmodifiableMapEntryNode {
/**
* Constructor.
*
* @param name
* the pseudo-OGNL path of the node.
* @param map
* the map owning this node.
* @param key
* the key of this entry in the map.
*/
public ModifiableMapEntryNode(String name, Map<?, ?> map, Object key) {
super(name, map, key);
}
/**
* @see org.dihedron.patterns.visitor.nodes.AbstractNode#getValue()
*/
@SuppressWarnings("unchecked")
public void setValue(Object value) throws VisitorException {
((Map<Object, Object>)map).put(key, value);
}
}
| dihedron/dihedron-commons | src/main/java/org/dihedron/patterns/visitor/nodes/ModifiableMapEntryNode.java | Java | lgpl-3.0 | 888 |
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2015 Ricardo Mariaca
* http://www.dynamicreports.org
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.builder.condition;
import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.definition.DRIValue;
import net.sf.dynamicreports.report.definition.ReportParameters;
import org.apache.commons.lang3.Validate;
/**
* @author Ricardo Mariaca (r.mariaca@dynamicreports.org)
*/
public class EqualExpression extends AbstractSimpleExpression<Boolean> {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
private DRIValue<?> value;
private Object[] values;
public <T> EqualExpression(DRIValue<T> value, T ...values) {
Validate.notNull(value, "value must not be null");
Validate.noNullElements(values, "values must not contains null value");
this.value = value;
this.values = values;
}
@Override
public Boolean evaluate(ReportParameters reportParameters) {
Object actualValue = reportParameters.getValue(value);
for (Object value : values) {
if (value.equals(actualValue)) {
return true;
}
}
return false;
}
@Override
public Class<Boolean> getValueClass() {
return Boolean.class;
}
}
| svn2github/dynamicreports-jasper | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/condition/EqualExpression.java | Java | lgpl-3.0 | 2,144 |
<?php
/*
* Copyright (c) 2012-2016, Hofmänner New Media.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of the n2n module ROCKET.
*
* ROCKET 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.
*
* ROCKET 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: http://www.gnu.org/licenses/
*
* The following people participated in this project:
*
* Andreas von Burg...........: Architect, Lead Developer, Concept
* Bert Hofmänner.............: Idea, Frontend UI, Design, Marketing, Concept
* Thomas Günther.............: Developer, Frontend UI, Rocket Capability for Hangar
*/
namespace rocket\si\content\impl\split;
use n2n\util\ex\IllegalStateException;
use rocket\si\content\impl\OutSiFieldAdapter;
class SplitOutSiField extends OutSiFieldAdapter {
private $subFields = [];
private $splitContents = [];
function __construct() {
}
/**
* {@inheritDoc}
* @see \rocket\si\content\SiField::getType()
*/
function getType(): string {
return 'split-out';
}
/**
* {@inheritDoc}
* @see \rocket\si\content\SiField::getData()
*/
function getData(): array {
return [
'splitContentsMap' => $this->splitContents
];
}
/**
* {@inheritDoc}
* @see \rocket\si\content\impl\OutSiFieldAdapter::handleInput()
*/
function handleInput(array $data): array {
throw new IllegalStateException();
}
}
| n2n/rocket | src/app/rocket/si/content/impl/split/SplitOutSiField.php | PHP | lgpl-3.0 | 1,814 |
/********************************************************************
** Image Component Library (ICL) **
** **
** Copyright (C) 2006-2013 CITEC, University of Bielefeld **
** Neuroinformatics Group **
** Website: www.iclcv.org and **
** http://opensource.cit-ec.de/projects/icl **
** **
** File : ICLUtils/src/ICLUtils/CLBuffer.cpp **
** Module : ICLUtils **
** Authors: Viktor Losing **
** **
** **
** GNU LESSER GENERAL PUBLIC LICENSE **
** This file may be used under the terms of the GNU Lesser General **
** Public License version 3.0 as published by the **
** **
** Free Software Foundation and appearing in the file LICENSE.GPL **
** included in the packaging of this file. Please review the **
** following information to ensure the license requirements will **
** be met: http://www.gnu.org/licenses/lgpl-3.0.txt **
** **
** The development of this software was supported by the **
** Excellence Cluster EXC 277 Cognitive Interaction Technology. **
** The Excellence Cluster EXC 277 is a grant of the Deutsche **
** Forschungsgemeinschaft (DFG) in the context of the German **
** Excellence Initiative. **
** **
********************************************************************/
#ifdef ICL_HAVE_OPENCL
#define __CL_ENABLE_EXCEPTIONS
#include <ICLUtils/CLImage2D.h>
#include <ICLUtils/Macros.h>
#include <ICLUtils/CLIncludes.h>
#include <iostream>
#include <sstream>
#include <set>
#include <map>
using namespace std;
namespace icl {
namespace utils {
struct CLImage2D::Impl {
size_t width;
size_t height;
cl::Image2D image2D;
cl::CommandQueue cmdQueue;
std::map< uint32_t, set<uint32_t> > supported_channel_orders;
static cl_mem_flags stringToMemFlags(const string &accessMode) {
switch(accessMode.length()) {
case 1:
if(accessMode[0] == 'w') return CL_MEM_WRITE_ONLY;
if(accessMode[0] == 'r') return CL_MEM_READ_ONLY;
case 2:
if( (accessMode[0] == 'r' && accessMode[1] == 'w') ||
(accessMode[0] == 'w' && accessMode[1] == 'r') ) {
return CL_MEM_READ_WRITE;
}
default:
throw CLBufferException("undefined access-mode '"+accessMode+"' (allowed are 'r', 'w' and 'rw')");
return CL_MEM_READ_WRITE;
}
}
static cl_channel_order parseChannelOrder(const int num_channels) {
cl_channel_order order = CL_R;
switch(num_channels) {
case(1): order = CL_R; break;
case(2): order = CL_RA; break;
case(3): order = CL_RGB; break;
case(4): order = CL_RGBA; break;
default: {
std::stringstream sstream;
sstream << num_channels;
throw CLBufferException("unsupported number of channels: "+sstream.str());
}
}
return order;
}
bool checkSupportedImageFormat(cl_channel_order order, cl_channel_type type) {
if (supported_channel_orders.count(order)) {
return supported_channel_orders[order].count(type);
}
return false;
}
Impl() {}
~Impl() {}
Impl(Impl& other):cmdQueue(other.cmdQueue) {
width = other.width;
height = other.height;
image2D = other.image2D;
supported_channel_orders = other.supported_channel_orders;
}
Impl(cl::Context &context, cl::CommandQueue &cmdQueue,
const string &accessMode, const size_t width, const size_t height,
int depth, int num_channel, const void *src = 0, const std::map<uint32_t, std::set<uint32_t> >
&supported_formats = std::map< uint32_t,std::set<uint32_t> >())
:cmdQueue(cmdQueue), supported_channel_orders(supported_formats) {
cl_mem_flags memFlags = stringToMemFlags(accessMode);
if (src) {
memFlags = memFlags | CL_MEM_COPY_HOST_PTR;
}
this->width = width;
this->height = height;
try {
cl_channel_type channelType;
switch(depth) {
case 0:
channelType = CL_UNSIGNED_INT8;
break;
case 1:
channelType = CL_SIGNED_INT16;
break;
case 2:
channelType = CL_SIGNED_INT32;
break;
case 3:
channelType = CL_FLOAT;
break;
default:
throw CLBufferException("unknown depth value");
}
cl_channel_order order = parseChannelOrder(num_channel);
if (!checkSupportedImageFormat(order,channelType)) {
std::stringstream sstream;
sstream << "channel: " << num_channel << ", depth-type: " << depth;
throw CLBufferException("No such image type is supported: "+sstream.str());
}
image2D = cl::Image2D(context, memFlags, cl::ImageFormat(order, channelType), width, height, 0, (void*) src);
} catch (cl::Error& error) {
throw CLBufferException(CLException::getMessage(error.err(), error.what()));
}
}
void regionToCLTypes(const utils::Rect ®ion, cl::size_t<3> &clOrigin,
cl::size_t<3> &clRegion) {
clOrigin[0] = region.x;
clOrigin[1] = region.y;
clOrigin[2] = 0;
if (region == Rect::null) {
clRegion[0] = width;
clRegion[1] = height;
} else {
clRegion[0] = region.width;
clRegion[1] = region.height;
}
clRegion[2] = 1;
}
void read(void *dst, const utils::Rect ®ion=utils::Rect::null, bool block = true) {
cl_bool blocking;
if (block)
blocking = CL_TRUE;
else
blocking = CL_FALSE;
try {
cl::size_t<3> clOrigin;
cl::size_t<3> clRegion;
regionToCLTypes(region, clOrigin, clRegion);
cmdQueue.enqueueReadImage(image2D, blocking, clOrigin, clRegion, 0, 0, dst);
} catch (cl::Error& error) {
throw CLBufferException(CLException::getMessage(error.err(), error.what()));
}
}
void write(void *src, const utils::Rect ®ion=utils::Rect::null,
bool block = true) {
cl_bool blocking;
if (block)
blocking = CL_TRUE;
else
blocking = CL_FALSE;
try {
cl::size_t<3> clOrigin;
cl::size_t<3> clRegion;
regionToCLTypes(region, clOrigin, clRegion);
cmdQueue.enqueueWriteImage(image2D, blocking, clOrigin, clRegion, 0, 0, src);
} catch (cl::Error& error) {
throw CLBufferException(CLException::getMessage(error.err(), error.what()));
}
}
static const icl32s iclDepthToByteDepth(int icl_depth) {
switch (icl_depth) {
case(0): return 1;
case(1): return 2;
case(2): return 4;
case(3): return 4;
case(4): return 8;
default: return 1; // maybe better to throw an exception here?
}
}
};
CLImage2D::CLImage2D(cl::Context &context, cl::CommandQueue &cmdQueue,
const string &accessMode, const size_t width, const size_t height,
int depth, int num_channel, const void *src,
const std::map<uint32_t, std::set<uint32_t> > &supported_formats)
: CLMemory(CLMemory::Image2D) {
impl = new Impl(context, cmdQueue, accessMode, width, height,
depth, num_channel, src, supported_formats);
setDimensions(width,height,num_channel);
m_byte_depth = Impl::iclDepthToByteDepth(depth);
}
CLImage2D::CLImage2D()
: CLMemory(CLMemory::Image2D) {
impl = new Impl();
}
CLImage2D::CLImage2D(const CLImage2D& other)
: CLMemory(other) {
impl = new Impl(*(other.impl));
}
CLImage2D& CLImage2D::operator=(CLImage2D const& other) {
CLMemory::operator=(other);
impl->cmdQueue = other.impl->cmdQueue;
impl->image2D = other.impl->image2D;
impl->width = other.impl->width;
impl->height = other.impl->height;
impl->supported_channel_orders = other.impl->supported_channel_orders;
return *this;
}
CLImage2D::~CLImage2D() {
delete impl;
}
void CLImage2D::read(void *dst, const utils::Rect ®ion, bool block) {
impl->read(dst, region, block);
}
void CLImage2D::write(const void *src, const utils::Rect ®ion,
bool block) {
impl->write((void *)src, region, block);
}
cl::Image2D CLImage2D::getImage2D() {
return impl->image2D;
}
const cl::Image2D CLImage2D::getImage2D() const {
return impl->image2D;
}
}
}
#endif
| iclcv/icl | ICLUtils/src/ICLUtils/CLImage2D.cpp | C++ | lgpl-3.0 | 10,270 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.scan;
import java.util.Optional;
import javax.annotation.concurrent.Immutable;
@Immutable
public interface ExternalProjectKeyAndOrganization {
Optional<String> getProjectKey();
Optional<String> getOrganization();
}
| Godin/sonar | sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ExternalProjectKeyAndOrganization.java | Java | lgpl-3.0 | 1,091 |
package com.silicolife.textmining.processes.ir.pubmed;
public class PubMedConfiguration {
public static final int timeToWaitbetweenQueries = 3000;
public static final int numberOFRetries = 5;
public static final int blockSearchSize = 50;
public static final int searchMetaInfoblockSize = 5;
}
| biotextmining/processes | src/main/java/com/silicolife/textmining/processes/ir/pubmed/PubMedConfiguration.java | Java | lgpl-3.0 | 299 |
// Copyright 2015 The daxxcoreAuthors
// This file is part of the daxxcore library.
//
// The daxxcore 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 3 of the License, or
// (at your option) any later version.
//
// The daxxcore 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 the daxxcore library. If not, see <http://www.gnu.org/licenses/>.
// +build none
//sed -e 's/_N_/Hash/g' -e 's/_S_/32/g' -e '1d' types_template.go | gofmt -w hash.go
package common
import "math/big"
type _N_ [_S_]byte
func BytesTo_N_(b []byte) _N_ {
var h _N_
h.SetBytes(b)
return h
}
func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }
func BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }
func HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }
// Don't use the default 'String' method in case we want to overwrite
// Get the string representation of the underlying hash
func (h _N_) Str() string { return string(h[:]) }
func (h _N_) Bytes() []byte { return h[:] }
func (h _N_) Big() *big.Int { return Bytes2Big(h[:]) }
func (h _N_) Hex() string { return "0x" + Bytes2Hex(h[:]) }
// Sets the hash to the value of b. If b is larger than len(h) it will panic
func (h *_N_) SetBytes(b []byte) {
// Use the right most bytes
if len(b) > len(h) {
b = b[len(b)-_S_:]
}
// Reverse the loop
for i := len(b) - 1; i >= 0; i-- {
h[_S_-len(b)+i] = b[i]
}
}
// Set string `s` to h. If s is larger than len(h) it will panic
func (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }
// Sets h to other
func (h *_N_) Set(other _N_) {
for i, v := range other {
h[i] = v
}
}
| daxxcoin/daxxcore | common/types_template.go | GO | lgpl-3.0 | 2,033 |
/*
* Copyright (C) 2022 Inera AB (http://www.inera.se)
*
* This file is part of sklintyg (https://github.com/sklintyg).
*
* sklintyg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sklintyg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package se.inera.statistics.service.warehouse;
import java.time.Clock;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import se.inera.statistics.integration.hsa.model.HsaIdEnhet;
import se.inera.statistics.integration.hsa.model.HsaIdLakare;
import se.inera.statistics.integration.hsa.model.HsaIdVardgivare;
import se.inera.statistics.service.helper.ConversionHelper;
import se.inera.statistics.service.helper.HSAServiceHelper;
import se.inera.statistics.service.helper.Patientdata;
import se.inera.statistics.service.hsa.HsaInfo;
import se.inera.statistics.service.processlog.Arbetsnedsattning;
import se.inera.statistics.service.processlog.EventType;
import se.inera.statistics.service.processlog.IntygDTO;
import se.inera.statistics.service.report.util.Icd10;
import se.inera.statistics.service.report.util.Icd10.Kategori;
import se.inera.statistics.service.warehouse.model.db.WideLine;
@Component
public class WidelineConverter extends AbstractWidlineConverter {
private static final LocalDate ERA = LocalDate.parse("2000-01-01");
public static final int QUARTER = 25;
public static final int HALF = 50;
public static final int THREE_QUARTER = 75;
public static final int FULL = 100;
public static final int MAX_LENGTH_VGID = 50;
public static final int MAX_LENGTH_ENHETNAME = 255;
public static final int MAX_LENGTH_VARDGIVARE_NAMN = 255;
public static final int MAX_LENGTH_LAN_ID = 50;
public static final int MAX_LENGTH_KOMMUN_ID = 4;
public static final int MAX_LENGTH_VERKSAMHET_TYP = Integer.MAX_VALUE;
public static final int MAX_LENGTH_LAKARE_ID = 128;
public static final int MAX_LENGTH_TILLTALSNAMN = 128;
public static final int MAX_LENGTH_EFTERNAMN = 128;
private static final int DATE20100101 = 3653; // 365*10 + 3
private static final int MAX_YEARS_INTO_FUTURE = 5;
private static final int MAX_LENGTH_CORRELATION_ID = 50;
public static final String UNKNOWN_DIAGNOS = "unknown";
@Autowired
private Icd10 icd10;
@Autowired
private Clock clock;
public List<WideLine> toWideline(IntygDTO dto, HsaInfo hsa, long logId, String correlationId, EventType type) {
String lkf = getLkf(hsa);
String huvudenhet = HSAServiceHelper.getHuvudEnhetId(hsa);
String underenhet = HSAServiceHelper.getUnderenhetId(hsa);
String vardenhet = huvudenhet != null ? huvudenhet : underenhet;
String enhet = huvudenhet != null ? underenhet : null;
HsaIdVardgivare vardgivare = HSAServiceHelper.getVardgivarId(hsa);
if (vardenhet == null) {
vardenhet = dto.getEnhet();
}
String patient = dto.getPatientid();
Patientdata patientData = dto.getPatientData();
int kon = patientData.getKon().getNumberRepresentation();
int alder = patientData.getAlder();
String diagnos = dto.getDiagnoskod();
final Diagnos dx = parseDiagnos(diagnos);
int lakarkon = HSAServiceHelper.getLakarkon(hsa);
int lakaralder = HSAServiceHelper.getLakaralder(hsa);
String lakarbefattning = HSAServiceHelper.getLakarbefattning(hsa);
HsaIdLakare lakareid = new HsaIdLakare(dto.getLakareId());
final boolean active = !EventType.REVOKED.equals(type);
List<WideLine> lines = new ArrayList<>();
for (Arbetsnedsattning arbetsnedsattning : dto.getArbetsnedsattnings()) {
WideLine line = createWideLine(logId, correlationId, type, lkf, vardenhet, enhet, vardgivare, patient, kon, alder, dx,
lakarkon, lakaralder, lakarbefattning, lakareid, arbetsnedsattning, active);
lines.add(line);
}
return lines;
}
// CHECKSTYLE:OFF ParameterNumberCheck
@java.lang.SuppressWarnings("squid:S00107") // Suppress parameter number warning in Sonar
private WideLine createWideLine(long logId, String correlationId, EventType type, String lkf, String vardenhet,
String enhet, HsaIdVardgivare vardgivare, String patient, int kon,
int alder, Diagnos dx, int lakarkon, int lakaralder, String lakarbefattning,
HsaIdLakare lakareid, Arbetsnedsattning arbetsnedsattning, boolean active) {
WideLine line = new WideLine();
int sjukskrivningsgrad = arbetsnedsattning.getNedsattning();
LocalDate kalenderStart = arbetsnedsattning.getStart();
LocalDate kalenderEnd = arbetsnedsattning.getSlut();
line.setCorrelationId(correlationId);
line.setLakarintyg(logId);
line.setIntygTyp(type);
line.setActive(active);
line.setLkf(lkf);
line.setEnhet(new HsaIdEnhet(enhet));
line.setVardenhet(new HsaIdEnhet(vardenhet));
line.setVardgivareId(vardgivare);
line.setStartdatum(toDay(kalenderStart));
line.setSlutdatum(toDay(kalenderEnd));
line.setDiagnoskapitel(dx.diagnoskapitel);
line.setDiagnosavsnitt(dx.diagnosavsnitt);
line.setDiagnoskategori(dx.diagnoskategori);
line.setDiagnoskod(dx.diagnoskod);
line.setSjukskrivningsgrad(sjukskrivningsgrad);
line.setPatientid(patient);
line.setAlder(alder);
line.setKon(kon);
line.setLakaralder(lakaralder);
line.setLakarkon(lakarkon);
line.setLakarbefattning(lakarbefattning);
line.setLakareId(lakareid);
return line;
}
// CHECKSTYLE:ON ParameterNumberCheck
private Diagnos parseDiagnos(String diagnos) {
boolean isUnknownDiagnos = diagnos == null || UNKNOWN_DIAGNOS.equals(diagnos);
final Icd10.Kod kod = isUnknownDiagnos ? null : icd10.findKod(diagnos);
final Kategori kategori = kod != null ? kod.getKategori() : isUnknownDiagnos ? null : icd10.findKategori(diagnos);
final Diagnos dx = new Diagnos();
dx.diagnoskod = kod != null ? kod.getId() : null;
if (kategori != null) {
dx.diagnoskapitel = kategori.getAvsnitt().getKapitel().getId();
dx.diagnosavsnitt = kategori.getAvsnitt().getId();
dx.diagnoskategori = kategori.getId();
} else if (UNKNOWN_DIAGNOS.equals(diagnos)) {
dx.diagnoskapitel = null;
dx.diagnosavsnitt = null;
dx.diagnoskategori = UNKNOWN_DIAGNOS;
} else {
dx.diagnoskapitel = null;
dx.diagnosavsnitt = null;
dx.diagnoskategori = null;
}
return dx;
}
private void checkSjukskrivningsgrad(List<String> errors, int grad) {
if (!(grad == QUARTER || grad == HALF || grad == THREE_QUARTER || grad == FULL)) {
errors.add("Illegal sjukskrivningsgrad: " + grad);
}
}
private void checkStartdatum(List<String> errors, int startdatum) {
if (startdatum < DATE20100101 || startdatum > toDay(LocalDate.now(clock).plusYears(MAX_YEARS_INTO_FUTURE))) {
errors.add("Illegal startdatum: " + startdatum);
}
}
private void checkSlutdatum(List<String> errors, int slutdatum) {
if (slutdatum > toDay(LocalDate.now(clock).plusYears(MAX_YEARS_INTO_FUTURE))) {
errors.add("Illegal slutdatum: " + slutdatum);
}
}
private String getLkf(HsaInfo hsa) {
String lkf = HSAServiceHelper.getKommun(hsa);
if (lkf.isEmpty()) {
lkf = HSAServiceHelper.getLan(hsa);
} else if (lkf.length() == 2) {
lkf = HSAServiceHelper.getLan(hsa) + lkf;
}
return lkf;
}
public static int toDay(LocalDate dayDate) {
return (int) ChronoUnit.DAYS.between(ERA, dayDate);
}
public static LocalDate toDate(int day) {
return ERA.plusDays(day);
}
public List<String> validate(WideLine line) {
List<String> errors = new ArrayList<>();
checkField(errors, line.getLkf(), "LKF");
checkField(errors, line.getVardgivareId(), "Vårdgivare", MAX_LENGTH_VGID);
checkField(errors, line.getVardenhet(), "Vardenhet");
checkField(errors, line.getPatientid(), "Patient");
checkAge(errors, line.getAlder());
checkField(errors, line.getCorrelationId(), "CorrelationId", MAX_LENGTH_CORRELATION_ID);
checkSjukskrivningsgrad(errors, line.getSjukskrivningsgrad());
checkDates(errors, line.getStartdatum(), line.getSlutdatum());
return errors;
}
private void checkDates(List<String> errors, int startdatum, int slutdatum) {
checkStartdatum(errors, startdatum);
checkSlutdatum(errors, slutdatum);
if (startdatum > slutdatum) {
errors.add("Illegal dates. Start date (" + startdatum + ") must be before end date (" + slutdatum + ")");
}
}
private void checkAge(List<String> errors, int alder) {
if (alder == ConversionHelper.NO_AGE) {
errors.add("Error in patient age");
}
}
private static class Diagnos {
private String diagnoskod;
private String diagnoskapitel;
private String diagnosavsnitt;
private String diagnoskategori;
}
}
| sklintyg/statistik | service/src/main/java/se/inera/statistics/service/warehouse/WidelineConverter.java | Java | lgpl-3.0 | 10,101 |
package nif.compound;
import java.io.IOException;
import java.nio.ByteBuffer;
import nif.ByteConvert;
public class NifbhkCMSDMaterial
{
/**
* <compound name="bhkCMSDMaterial">
per-chunk material, used in bhkCompressedMeshShapeData
<add name="Material ID" type="uint">Unknown</add>
<add name="Unknown Integer" type="uint">Always 1?</add>
</compound>
*/
public int MaterialID;
public int UnknownInteger;
public NifbhkCMSDMaterial(ByteBuffer stream) throws IOException
{
MaterialID = ByteConvert.readInt(stream);
UnknownInteger = ByteConvert.readInt(stream);
}
}
| philjord/jnif | jnif/src/nif/compound/NifbhkCMSDMaterial.java | Java | lgpl-3.0 | 623 |
/**
* Copyright (C) 2013-2014 Kametic <epo.jemba@kametic.com>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* or any later version
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* 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.nuun.plugin.spring.sample;
public class Service3Internal implements Service3
{
@Override
public String serve()
{
return this.getClass().getName();
}
}
| nuun-io/nuun-spring-plugin | src/test/java/io/nuun/plugin/spring/sample/Service3Internal.java | Java | lgpl-3.0 | 875 |
package org.mysqlmv.cd.workers;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.mysqlmv.Switch;
import org.mysqlmv.cd.dao.CdDao;
import org.mysqlmv.cd.workers.impl.DefaultLogFileChangeProcessor;
import org.mysqlmv.cd.workers.impl.LogFileScanStatus;
import org.mysqlmv.common.config.reader.ConfigFactory;
import org.slf4j.Logger;
import java.io.*;
import java.sql.SQLException;
/**
* Created by Kelvin Li on 11/18/2014 2:38 PM.
*/
public class LogFileChangeDetector implements Runnable {
public static Logger logger = org.slf4j.LoggerFactory.getLogger(LogFileChangeDetector.class);
private volatile long lastChangeTimeStamp;
private volatile String logRoot;
private LogFileChangeProcessor processor = new DefaultLogFileChangeProcessor();
@Override
public void run() {
logRoot = ConfigFactory.getINSTANCE().getProperty("log-root-folder");
Switch controller = Switch.getSwitch();
while(controller.getStatus()) {
scannLog();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void scannLog() {
try {
// When mysql is shutdown normally, a stop event will appears in the log file,
// then should handle this situation.
LogFileScanStatus status = LogFileScanStatus.SUCCESS;
File logFile = new File(findCurrentLogFile());
boolean isNewFile = false;
while(true) {
status = processor.onFileChange(logFile, isNewFile);
if(status.equals(LogFileScanStatus.SUCCESS)) {
break;
} else if(status.equals(LogFileScanStatus.STOP)) {
isNewFile = true;
logger.warn("Mysql DB service is shutdown.");
} else if(status.equals(LogFileScanStatus.CONTINUE_NEXT)) {
logFile = findNextFile();
isNewFile = true;
}
}
} catch (IOException e) {
logger.error("Error happened when reading bin-log.");
logger.error(ExceptionUtils.getStackTrace(e));
// throw new RuntimeException(e);
} catch (SQLException e) {
e.printStackTrace();
}
}
private File findNextFile() throws SQLException, IOException {
String logFullName = CdDao.findCurrentLogFileName();
String curFileName = new File(logFullName).getName();
File indexFile = findIndexLogfile();
BufferedReader indexReader = new BufferedReader(new FileReader(indexFile));
if(indexReader == null) {
return null;
}
String line = null;
while((line = indexReader.readLine()) != null) {
if(line.contains(".\\")) {
line = line.replace(".\\", "");
if(curFileName.equals(line)) {
line = indexReader.readLine().replace(".\\", "");
break;
}
}
}
if("".equals(line)) {
return null;
}
return new File(logRoot + "/" + line);
}
public File findIndexLogfile() {
File logDir = new File(logRoot);
File indexFile = null;
for(File ff : logDir.listFiles()) {
if(ff.getName().endsWith(".index")) {
indexFile = ff;
}
}
return indexFile;
}
private String findCurrentLogFile() throws IOException {
String currentLogFile = null;
File indexFile = findIndexLogfile();
BufferedReader indexReader = new BufferedReader(new FileReader(indexFile));
if(indexReader == null) {
return null;
}
String line = null;
while((line = indexReader.readLine()) != null) {
if(line.contains(".\\")) {
currentLogFile = line.replace(".\\", "");
}
}
return logRoot + "/" + currentLogFile;
}
}
| Kelvinli1988/mysqlmv | src/main/java/org/mysqlmv/cd/workers/LogFileChangeDetector.java | Java | lgpl-3.0 | 4,083 |
//------------------------------------------------------------------------------
// <copyright company="Tunynet">
// Copyright (c) Tunynet Inc. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using PetaPoco;
using Tunynet.Caching;
namespace Tunynet.Common
{
/// <summary>
/// 公告实体类
/// </summary>
[TableName("spb_Announcements")]
[PrimaryKey("Id", autoIncrement = true)]
[CacheSetting(true)]
[Serializable]
public class Announcement : IEntity
{
/// <summary>
/// 新建实体时使用
/// </summary>
public static Announcement New()
{
Announcement announcement = new Announcement()
{
Subject = string.Empty,
SubjectStyle = string.Empty,
Body = string.Empty,
HyperLinkUrl = string.Empty,
ReleaseDate = DateTime.UtcNow,
ExpiredDate = DateTime.UtcNow,
LastModified = DateTime.UtcNow,
CreatDate = DateTime.UtcNow.ToLocalTime()
};
return announcement;
}
#region 需持久化属性
/// <summary>
///Primary key
/// </summary>
public long Id { get; protected set; }
/// <summary>
///公告主题
/// </summary>
public string Subject { get; set; }
/// <summary>
///主题字体风格
/// </summary>
public string SubjectStyle { get; set; }
/// <summary>
///公告内容
/// </summary>
public string Body { get; set; }
/// <summary>
///是否是连接
/// </summary>
public bool IsHyperLink { get; set; }
/// <summary>
///链接地址
/// </summary>
public string HyperLinkUrl { get; set; }
/// <summary>
///是否启用
/// </summary>
public bool EnabledDescription { get; set; }
/// <summary>
///发布时间
/// </summary>
public DateTime ReleaseDate { get; set; }
/// <summary>
///过期时间
/// </summary>
public DateTime ExpiredDate { get; set; }
/// <summary>
///更新时间
/// </summary>
public DateTime LastModified { get; set; }
/// <summary>
///创建时间
/// </summary>
[SqlBehavior(~SqlBehaviorFlags.Update)]
public DateTime CreatDate { get; set; }
/// <summary>
///创建人Id
/// </summary>
public long UserId { get; set; }
/// <summary>
///显示顺序
/// </summary>
public long DisplayOrder { get; set; }
/// <summary>
///展示区域
/// </summary>
public string DisplayArea { get; set; }
#endregion
#region 扩展属性和方法
/// <summary>
/// 浏览数
/// </summary>
[Ignore]
public int HitTimes
{
get
{
CountService countService = new CountService(TenantTypeIds.Instance().Announcement());
return countService.Get(CountTypes.Instance().HitTimes(), this.Id);
}
}
/// <summary>
/// 撰稿人
/// </summary>
[Ignore]
public string UserName
{ get; set; }
/// <summary>
/// 管理员标示
/// </summary>
[Ignore]
public bool IsAdministrator
{ get; set; }
#endregion
#region IEntity 成员
object IEntity.EntityId { get { return this.Id; } }
bool IEntity.IsDeletedInDatabase { get; set; }
#endregion
}
}
| yesan/Spacebuilder | BusinessComponents/ContentOrganization/Announcements/Announcement.cs | C# | lgpl-3.0 | 3,858 |
#include "CInterpreter.h"
#include "ErrorDefinitions.h"
#include "main.h"
CInterpreter::CInterpreter()
{}
CInterpreter::~CInterpreter()
{}
void CInterpreter::SetFileTree(CFileTree fileTree)
{
m_fileTree = fileTree;
}
unsigned int CInterpreter::CompileFileList()
{
char msg[512] = {0};
unsigned int* result = new unsigned int[m_fileTree.GetNumberOfFiles()];
for(int i = 0; i < m_fileTree.GetNumberOfFiles(); i++)
{
result[i] = CompileFile(m_fileTree.GetFile(i));
}
for(int i = 0; i < m_fileTree.GetNumberOfFiles(); i++)
{
if(result[i] == NO_ERROR)
m_fileTree.GetFile(i)->doScript();
else
{
sprintf(msg, "Could Not Run Script: %s | %s\n", m_fileTree.GetFile(i)->GetFilename(),
GetErrorText(result[i]));
debug.Log(msg);
}
}
return NO_ERROR;
}
unsigned int CInterpreter::CompileFile(CScriptFile* file)
{
m_scanner.SetFile(file);
unsigned int result = m_scanner.ScanFile();
if(result != NO_ERROR)
return result;
m_lexer.SetCharacters(m_scanner.GetCharacters(), m_scanner.GetCharacterCount());
result = m_lexer.ProcessCharacters();
if(result != NO_ERROR)
return result;
m_parser.SetScript(file);
m_parser.SetTokenList(m_lexer.GetTokens(), m_lexer.GetTokenCount());
result = m_parser.ParseTokens();
return result;
}
| patrickmortensen/Elektro | Source To Merge/Interpreter/CInterpreter.cpp | C++ | lgpl-3.0 | 1,413 |