repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
danielhuson/megan-ce | src/megan/clusteranalysis/commands/EcologicalIndexEuclideanCommand.java | 3496 | /*
* EcologicalIndexEuclideanCommand.java Copyright (C) 2021. Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package megan.clusteranalysis.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.EuclideanDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=Euclidean command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexEuclideanCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(EuclideanDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Euclidean";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Euclidean ecological index";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
* @param ev
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + EuclideanDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* parses the given command and executes it
*
* @param np
* @throws java.io.IOException
*/
public void apply(NexusStreamParser np) throws Exception {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| gpl-3.0 |
rhilker/ReadXplorer | readxplorer-tools-transcriptionanalyses/src/main/java/de/cebitec/readxplorer/transcriptionanalyses/wizard/TranscriptionAnalysesWizardIterator.java | 13878 | /*
* Copyright (C) 2014 Institute for Bioinformatics and Systems Biology, University Giessen, Germany
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cebitec.readxplorer.transcriptionanalyses.wizard;
import de.cebitec.readxplorer.databackend.dataobjects.PersistentTrack;
import de.cebitec.readxplorer.ui.dialogmenus.OpenTracksWizardPanel;
import de.cebitec.readxplorer.ui.dialogmenus.SelectFeatureTypeWizardPanel;
import de.cebitec.readxplorer.ui.dialogmenus.SelectReadClassWizardPanel;
import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.openide.WizardDescriptor;
import org.openide.WizardDescriptor.Panel;
import org.openide.util.ChangeSupport;
/**
* Wizard page iterator for a transcription analyses wizard.
* <p>
* @author Rolf Hilker <rhilker at cebitec.uni-bielefeld.de>
*/
public final class TranscriptionAnalysesWizardIterator implements
WizardDescriptor.Iterator<WizardDescriptor> {
public static final String PROP_TSS_ANALYSIS = "tssAnalysis";
public static final String PROP_OPERON_ANALYSIS = "Operon";
public static final String PROP_NORM_ANALYSIS = "Normalization";
public static final String PROP_UNANNOTATED_TRANSCRIPT_DET = "unannotatedTranscriptDetection";
public static final String PROP_AUTO_TSS_PARAMS = "automaticsTSSParameterEstimation";
public static final String PROP_AUTO_OPERON_PARAMS = "automaticOperonParameterEstimation";
public static final String PROP_MIN_TOTAL_INCREASE = "minTotalIncrease";
public static final String PROP_MIN_PERCENT_INCREASE = "minTotalPercentIncrease";
public static final String PROP_MAX_LOW_COV_INIT_COUNT = "maxLowCovInitialCount";
public static final String PROP_MIN_LOW_COV_INC = "minLowCovIncrease";
public static final String PROP_MIN_TRANSCRIPT_EXTENSION_COV = "minTranscriptExtensionCov";
public static final String PROP_MAX_LEADERLESS_DISTANCE = "maxLeaderlessDistance";
public static final String PROP_MAX_FEATURE_DISTANCE = "maxFeatureDistance";
public static final String PROP_MIN_NUMBER_READS = "minNumberReads";
public static final String PROP_MAX_NUMBER_READS = "maxNumberReads";
public static final String PROP_USE_EFFECTIVE_LENGTH = "useEffectiveLength";
public static final String PROP_MIN_SPANNING_READS = "minNumberSpanningReads";
public static final String PROP_ANALYSIS_DIRECTION = "analysisDirection";
public static final String PROP_ASSOCIATE_TSS_WINDOW = "associateTssWindow";
public static final String PROP_IS_ASSOCIATE_TSS = "isAssociateTss";
static final String PROP_WIZARD_NAME = "TransAnalyses";
private static final String FINISH_MSG = "Press 'Finish' to start";
private int index;
private final ChangeSupport changeSupport;
private WizardDescriptor wiz;
private String[] steps;
private final int referenceId;
private List<WizardDescriptor.Panel<WizardDescriptor>> allPanels;
private List<WizardDescriptor.Panel<WizardDescriptor>> currentPanels;
private TransAnalysesSelectionWizardPanel selectionPanel = new TransAnalysesSelectionWizardPanel();
private TransAnalysesTSSWizardPanel tSSPanel = new TransAnalysesTSSWizardPanel();
private TransAnalysesOperonWizardPanel operonPanel = new TransAnalysesOperonWizardPanel();
private TransAnalysesNormWizardPanel normalizationPanel = new TransAnalysesNormWizardPanel();
private OpenTracksWizardPanel openTracksPanel;
private SelectReadClassWizardPanel readClassPanel;
private SelectFeatureTypeWizardPanel featTypeNormPanel;
private SelectFeatureTypeWizardPanel featTypeOperonPanel;
private final Map<WizardDescriptor.Panel<WizardDescriptor>, Integer> panelToStepMap = new HashMap<>();
/**
* Wizard page iterator for a transcription analyses wizard. In order to use
* it correctly, the wizard, in which this iterator is used has to be set.
* @param referenceId The id of the current reference
*/
public TranscriptionAnalysesWizardIterator( int referenceId ) {
this.referenceId = referenceId;
this.changeSupport = new ChangeSupport( this );
this.initializePanels();
}
/**
* @return the sequence of all wizard panels of this wizard
*/
private List<WizardDescriptor.Panel<WizardDescriptor>> initializePanels() {
if( allPanels == null ) {
allPanels = new ArrayList<>();
openTracksPanel = new OpenTracksWizardPanel( PROP_WIZARD_NAME, referenceId );
selectionPanel = new TransAnalysesSelectionWizardPanel();
readClassPanel = new SelectReadClassWizardPanel( PROP_WIZARD_NAME, true );
tSSPanel = new TransAnalysesTSSWizardPanel();
operonPanel = new TransAnalysesOperonWizardPanel();
normalizationPanel = new TransAnalysesNormWizardPanel();
featTypeNormPanel = new SelectFeatureTypeWizardPanel( PROP_NORM_ANALYSIS, true );
featTypeOperonPanel = new SelectFeatureTypeWizardPanel( PROP_OPERON_ANALYSIS, false );
featTypeOperonPanel.getComponent().showDisplayName( true );
featTypeNormPanel.getComponent().showDisplayName( true );
allPanels.add( openTracksPanel );
allPanels.add( selectionPanel );
allPanels.add( readClassPanel );
allPanels.add( tSSPanel );
allPanels.add( operonPanel );
allPanels.add( featTypeOperonPanel );
allPanels.add( normalizationPanel );
allPanels.add( featTypeNormPanel );
this.panelToStepMap.put( openTracksPanel, 0 );
this.panelToStepMap.put( selectionPanel, 1 );
this.panelToStepMap.put( readClassPanel, 2 );
this.panelToStepMap.put( tSSPanel, 3 );
this.panelToStepMap.put( operonPanel, 4 );
this.panelToStepMap.put( featTypeOperonPanel, 5 );
this.panelToStepMap.put( normalizationPanel, 6 );
this.panelToStepMap.put( featTypeNormPanel, 7 );
this.steps = new String[allPanels.size() + 1];
for( int i = 0; i < allPanels.size(); i++ ) {
Component c = allPanels.get( i ).getComponent();
// Default step name to component name of panel.
steps[i] = c.getName();
if( c instanceof JComponent ) { // assume Swing components
JComponent jc = (JComponent) c;
jc.putClientProperty( WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, i );
jc.putClientProperty( WizardDescriptor.PROP_AUTO_WIZARD_STYLE, true );
jc.putClientProperty( WizardDescriptor.PROP_CONTENT_DISPLAYED, true );
jc.putClientProperty( WizardDescriptor.PROP_CONTENT_NUMBERED, true );
}
}
steps[steps.length - 1] = FINISH_MSG;
String[] initiallyShownSteps = new String[]{ steps[0], steps[1], "...", steps[steps.length - 1] };
openTracksPanel.getComponent().putClientProperty( WizardDescriptor.PROP_CONTENT_DATA, initiallyShownSteps );
currentPanels = new ArrayList<>();
currentPanels.add( openTracksPanel );
currentPanels.add( selectionPanel );
currentPanels.add( readClassPanel );
}
return allPanels;
}
/**
* @return the current wizard panel
*/
@Override
public WizardDescriptor.Panel<WizardDescriptor> current() {
return currentPanels.get( index );
}
@Override
public String name() {
return index + 1 + ". from " + currentPanels.size();
}
@Override
public boolean hasNext() {
return index < currentPanels.size() - 1;
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public void nextPanel() {
if( index == 1 ) {
this.updatePanelList( selectionPanel.getComponent().isTSSAnalysisSelected(), tSSPanel );
this.updatePanelList( selectionPanel.getComponent().isOperonAnalysisSelected(), operonPanel );
this.updatePanelList( selectionPanel.getComponent().isOperonAnalysisSelected(), featTypeOperonPanel );
this.updatePanelList( selectionPanel.getComponent().isNormAnalysisSelected(), normalizationPanel );
this.updatePanelList( selectionPanel.getComponent().isNormAnalysisSelected(), featTypeNormPanel );
String[] newStepArray = new String[0];
List<String> newSteps = new ArrayList<>();
for( Panel<WizardDescriptor> panel : currentPanels ) {
newSteps.add( this.steps[this.panelToStepMap.get( panel )] );
}
newSteps.add( FINISH_MSG );
wiz.putProperty( WizardDescriptor.PROP_CONTENT_DATA, newSteps.toArray( newStepArray ) );
}
if( !hasNext() ) {
throw new NoSuchElementException();
}
++index;
wiz.putProperty( WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, index );
}
@Override
public void previousPanel() {
if( !hasPrevious() ) {
throw new NoSuchElementException();
}
--index;
wiz.putProperty( WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, index );
}
// If nothing unusual changes in the middle of the wizard, simply:
@Override
public void addChangeListener( ChangeListener l ) {
changeSupport.addChangeListener( l );
}
@Override
public void removeChangeListener( ChangeListener l ) {
changeSupport.removeChangeListener( l );
}
// If something changes dynamically (besides moving between panels), e.g.
// the number of panels changes in response to user input, then use
// ChangeSupport to implement add/removeChangeListener and call fireChange
// when needed
/**
* @param wiz the wizard, in which this wizard iterator is contained. If it
* is not set, no properties can be stored, thus it always has to
* be set.
*/
public void setWiz( WizardDescriptor wiz ) {
this.wiz = wiz;
}
/**
* @return the wizard, in which this wizard iterator is contained.
*/
public WizardDescriptor getWiz() {
return wiz;
}
/**
* Updates the wizard's panel list with the given analysis panel and it's
* steps with the newStep string, if the given analysis is selected and the
* analysis panel is not already contained in the wizard panel list.
* <p>
* @param analysisSelected true, if the analysis is selected, false
* otherwise
* @param analysisPanel the analysis panel to add to the list of panels
*/
private void updatePanelList( boolean analysisSelected, Panel<WizardDescriptor> analysisPanel ) {
if( analysisSelected ) {
if( !currentPanels.contains( analysisPanel ) ) {
currentPanels.add( analysisPanel );
}
} else if( currentPanels.contains( analysisPanel ) ) {
currentPanels.remove( analysisPanel );
}
}
/**
* @return The dynamically generated property name for the read class
* selection for this wizard. Can be used to obtain the
* corresponding read class parameters.
*/
public String getReadClassPropForWiz() {
return readClassPanel.getPropReadClassParams();
}
/**
* @return The property string for the selected feature type list for the
* corresponding read count normalization analysis.
*/
public String getPropSelectedNormFeatTypes() {
return featTypeNormPanel.getPropSelectedFeatTypes();
}
/**
* @return The property string for the feature start offset configured for
* the read count normalization analysis.
*/
public String getPropNormFeatureStartOffset() {
return featTypeNormPanel.getPropFeatureStartOffset();
}
/**
* @return The property string for the feature stop offset configured for
* the read count normalization analysis.
*/
public String getPropNormFeatureStopOffset() {
return featTypeNormPanel.getPropFeatureStopOffset();
}
/**
* @return The property string for the selected feature type list for the
* corresponding operon detection.
*/
public String getPropSelectedOperonFeatTypes() {
return featTypeOperonPanel.getPropSelectedFeatTypes();
}
/**
* @return The dynamically generated property name for the combine tracks
* selection for this wizard. Can be used to obtain the
* corresponding boolean if the tracks shall be combined.
*/
public String getCombineTracksPropForWiz() {
return openTracksPanel.getPropCombineTracks();
}
/**
* @return The list of track selected in this wizard.
*/
public List<PersistentTrack> getSelectedTracks() {
return openTracksPanel.getComponent().getSelectedTracks();
}
}
| gpl-3.0 |
fanruan/finereport-design | designer_base/src/com/fr/design/gui/syntax/ui/rsyntaxtextarea/RSyntaxUtilities.java | 42360 | /*
* 08/06/2004
*
* RSyntaxUtilities.java - Utility methods used by RSyntaxTextArea and its
* views.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package com.fr.design.gui.syntax.ui.rsyntaxtextarea;
import java.awt.Color;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Toolkit;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.TabExpander;
import javax.swing.text.View;
import com.fr.design.gui.syntax.ui.rsyntaxtextarea.TokenUtils.TokenSubList;
import com.fr.design.gui.syntax.ui.rsyntaxtextarea.folding.FoldManager;
import com.fr.design.gui.syntax.ui.rtextarea.Gutter;
import com.fr.design.gui.syntax.ui.rtextarea.RTextArea;
import com.fr.design.gui.syntax.ui.rtextarea.RTextScrollPane;
/**
* Utility methods used by <code>RSyntaxTextArea</code> and its associated
* classes.
*
* @author Robert Futrell
* @version 0.2
*/
public class RSyntaxUtilities implements SwingConstants {
/**
* Integer constant representing a Windows-variant OS.
*/
public static final int OS_WINDOWS = 1;
/**
* Integer constant representing Mac OS X.
*/
public static final int OS_MAC_OSX = 2;
/**
* Integer constant representing Linux.
*/
public static final int OS_LINUX = 4;
/**
* Integer constant representing an "unknown" OS. 99.99% of the
* time, this means some UNIX variant (AIX, SunOS, etc.).
*/
public static final int OS_OTHER = 8;
/**
* Used for the color of hyperlinks when a LookAndFeel uses light text
* against a dark background.
*/
private static final Color LIGHT_HYPERLINK_FG = new Color(0xd8ffff);
private static final int OS = getOSImpl();
//private static final int DIGIT_MASK = 1;
private static final int LETTER_MASK = 2;
//private static final int WHITESPACE_MASK = 4;
//private static final int UPPER_CASE_MASK = 8;
private static final int HEX_CHARACTER_MASK = 16;
private static final int LETTER_OR_DIGIT_MASK = 32;
private static final int BRACKET_MASK = 64;
private static final int JAVA_OPERATOR_MASK = 128;
/**
* A lookup table used to quickly decide if a 16-bit Java char is a
* US-ASCII letter (A-Z or a-z), a digit, a whitespace char (either space
* (0x0020) or tab (0x0009)), etc. This method should be faster
* than <code>Character.isLetter</code>, <code>Character.isDigit</code>,
* and <code>Character.isWhitespace</code> because we know we are dealing
* with ASCII chars and so don't have to worry about code planes, etc.
*/
private static final int[] dataTable = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, // 0-15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
4, 128, 0, 0, 0, 128, 128, 0, 64, 64, 128, 128, 0, 128, 0, 128, // 32-47
49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 128, 0, 128, 128, 128, 128, // 48-63
0, 58, 58, 58, 58, 58, 58, 42, 42, 42, 42, 42, 42, 42, 42, 42, // 64-79
42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 64, 0, 64, 128, 0, // 80-95
0, 50, 50, 50, 50, 50, 50, 34, 34, 34, 34, 34, 34, 34, 34, 34, // 96-111
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 64, 128, 64, 128, 0, // 112-127
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128-143
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240-255.
};
/**
* Used in bracket matching methods.
*/
private static Segment charSegment = new Segment();
/**
* Used in token list manipulation methods.
*/
private static final TokenImpl tempToken = new TokenImpl();
/**
* Used internally.
*/
private static final char[] JS_KEYWORD_RETURN = { 'r', 'e', 't', 'u', 'r', 'n' };
/**
* Used internally.
*/
private static final String BRACKETS = "{([})]";
/**
* Returns a string with characters that are special to HTML (such as
* <code><</code>, <code>></code> and <code>&</code>) replaced
* by their HTML escape sequences.
*
* @param s The input string.
* @param newlineReplacement What to replace newline characters with.
* If this is <code>null</code>, they are simply removed.
* @param inPreBlock Whether this HTML will be in within <code>pre</code>
* tags. If this is <code>true</code>, spaces will be kept as-is;
* otherwise, they will be converted to "<code> </code>".
* @return The escaped version of <code>s</code>.
*/
public static final String escapeForHtml(String s,
String newlineReplacement, boolean inPreBlock) {
if (s==null) {
return null;
}
if (newlineReplacement==null) {
newlineReplacement = "";
}
final String tabString = " ";
boolean lastWasSpace = false;
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case ' ':
if (inPreBlock || !lastWasSpace) {
sb.append(' ');
}
else {
sb.append(" ");
}
lastWasSpace = true;
break;
case '\n':
sb.append(newlineReplacement);
lastWasSpace = false;
break;
case '&':
sb.append("&");
lastWasSpace = false;
break;
case '\t':
sb.append(tabString);
lastWasSpace = false;
break;
case '<':
sb.append("<");
lastWasSpace = false;
break;
case '>':
sb.append(">");
lastWasSpace = false;
break;
default:
sb.append(ch);
lastWasSpace = false;
break;
}
}
return sb.toString();
}
/**
* Returns the rendering hints for text that will most accurately reflect
* those of the native windowing system.
*
* @return The rendering hints, or <code>null</code> if they cannot be
* determined.
*/
public static Map<?,?> getDesktopAntiAliasHints() {
return (Map<?,?>)Toolkit.getDefaultToolkit().
getDesktopProperty("awt.font.desktophints");
}
/**
* Returns the color to use for the line underneath a folded region line.
*
* @param textArea The text area.
* @return The color to use.
*/
public static Color getFoldedLineBottomColor(RSyntaxTextArea textArea) {
Color color = Color.gray;
Gutter gutter = RSyntaxUtilities.getGutter(textArea);
if (gutter!=null) {
color = gutter.getFoldIndicatorForeground();
}
return color;
}
/**
* Returns the gutter component of the scroll pane containing a text
* area, if any.
*
* @param textArea The text area.
* @return The gutter, or <code>null</code> if the text area is not in
* an {@link RTextScrollPane}.
* @see RTextScrollPane#getGutter()
*/
public static Gutter getGutter(RTextArea textArea) {
Gutter gutter = null;
Container parent = textArea.getParent();
if (parent instanceof JViewport) {
parent = parent.getParent();
if (parent instanceof RTextScrollPane) {
RTextScrollPane sp = (RTextScrollPane)parent;
gutter = sp.getGutter(); // Should always be non-null
}
}
return gutter;
}
/**
* Returns the color to use for hyperlink-style components. This method
* will return <code>Color.blue</code> unless it appears that the current
* LookAndFeel uses light text on a dark background, in which case a
* brighter alternative is returned.
*
* @return The color to use for hyperlinks.
* @see #isLightForeground(Color)
*/
public static final Color getHyperlinkForeground() {
// This property is defined by all standard LaFs, even Nimbus (!),
// but you never know what crazy LaFs there are...
Color fg = UIManager.getColor("Label.foreground");
if (fg==null) {
fg = new JLabel().getForeground();
}
return isLightForeground(fg) ? LIGHT_HYPERLINK_FG : Color.blue;
}
/**
* Returns the leading whitespace of a string.
*
* @param text The String to check.
* @return The leading whitespace.
* @see #getLeadingWhitespace(Document, int)
*/
public static String getLeadingWhitespace(String text) {
int count = 0;
int len = text.length();
while (count<len && RSyntaxUtilities.isWhitespace(text.charAt(count))) {
count++;
}
return text.substring(0, count);
}
/**
* Returns the leading whitespace of a specific line in a document.
*
* @param doc The document.
* @param offs The offset whose line to get the leading whitespace for.
* @return The leading whitespace.
* @throws BadLocationException If <code>offs</code> is not a valid offset
* in the document.
* @see #getLeadingWhitespace(String)
*/
public static String getLeadingWhitespace(Document doc, int offs)
throws BadLocationException {
Element root = doc.getDefaultRootElement();
int line = root.getElementIndex(offs);
Element elem = root.getElement(line);
int startOffs = elem.getStartOffset();
int endOffs = elem.getEndOffset() - 1;
String text = doc.getText(startOffs, endOffs-startOffs);
return getLeadingWhitespace(text);
}
private static final Element getLineElem(Document d, int offs) {
Element map = d.getDefaultRootElement();
int index = map.getElementIndex(offs);
Element elem = map.getElement(index);
if ((offs>=elem.getStartOffset()) && (offs<elem.getEndOffset())) {
return elem;
}
return null;
}
/**
* Returns the bounding box (in the current view) of a specified position
* in the model. This method is designed for line-wrapped views to use,
* as it allows you to specify a "starting position" in the line, from
* which the x-value is assumed to be zero. The idea is that you specify
* the first character in a physical line as <code>p0</code>, as this is
* the character where the x-pixel value is 0.
*
* @param textArea The text area containing the text.
* @param s A segment in which to load the line. This is passed in so we
* don't have to reallocate a new <code>Segment</code> for each
* call.
* @param p0 The starting position in the physical line in the document.
* @param p1 The position for which to get the bounding box in the view.
* @param e How to expand tabs.
* @param rect The rectangle whose x- and width-values are changed to
* represent the bounding box of <code>p1</code>. This is reused
* to keep from needlessly reallocating Rectangles.
* @param x0 The x-coordinate (pixel) marking the left-hand border of the
* text. This is useful if the text area has a border, for example.
* @return The bounding box in the view of the character <code>p1</code>.
* @throws BadLocationException If <code>p0</code> or <code>p1</code> is
* not a valid location in the specified text area's document.
* @throws IllegalArgumentException If <code>p0</code> and <code>p1</code>
* are not on the same line.
*/
public static Rectangle getLineWidthUpTo(RSyntaxTextArea textArea,
Segment s, int p0, int p1,
TabExpander e, Rectangle rect,
int x0)
throws BadLocationException {
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
// Ensure p0 and p1 are valid document positions.
if (p0<0)
throw new BadLocationException("Invalid document position", p0);
else if (p1>doc.getLength())
throw new BadLocationException("Invalid document position", p1);
// Ensure p0 and p1 are in the same line, and get the start/end
// offsets for that line.
Element map = doc.getDefaultRootElement();
int lineNum = map.getElementIndex(p0);
// We do ">1" because p1 might be the first position on the next line
// or the last position on the previous one.
// if (lineNum!=map.getElementIndex(p1))
if (Math.abs(lineNum-map.getElementIndex(p1))>1)
throw new IllegalArgumentException("p0 and p1 are not on the " +
"same line (" + p0 + ", " + p1 + ").");
// Get the token list.
Token t = doc.getTokenListForLine(lineNum);
// Modify the token list 't' to begin at p0 (but still have correct
// token types, etc.), and get the x-location (in pixels) of the
// beginning of this new token list.
TokenSubList subList = TokenUtils.getSubTokenList(t, p0, e, textArea,
0, tempToken);
t = subList.tokenList;
rect = t.listOffsetToView(textArea, e, p1, x0, rect);
return rect;
}
/**
* Returns the location of the bracket paired with the one at the current
* caret position.
*
* @param textArea The text area.
* @param input A point to use as the return value. If this is
* <code>null</code>, a new object is created and returned.
* @return A point representing the matched bracket info. The "x" field
* is the offset of the bracket at the caret position (either just
* before or just after the caret), and the "y" field is the offset
* of the matched bracket. Both "x" and "y" will be
* <code>-1</code> if there isn't a matching bracket (or the caret
* isn't on a bracket).
*/
public static Point getMatchingBracketPosition(RSyntaxTextArea textArea,
Point input) {
if (input==null) {
input = new Point();
}
input.setLocation(-1, -1);
try {
// Actually position just BEFORE caret.
int caretPosition = textArea.getCaretPosition() - 1;
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
char bracket = 0;
// If the caret was at offset 0, we can't check "to its left."
if (caretPosition>=0) {
bracket = doc.charAt(caretPosition);
}
// Try to match a bracket "to the right" of the caret if one
// was not found on the left.
int index = BRACKETS.indexOf(bracket);
if (index==-1 && caretPosition<doc.getLength()-1) {
bracket = doc.charAt(++caretPosition);
}
// First, see if the char was a bracket (one of "{[()]}").
if (index==-1) {
index = BRACKETS.indexOf(bracket);
if (index==-1) {
return input;
}
}
// If it was, then make sure this bracket isn't sitting in
// the middle of a comment or string. If it isn't, then
// initialize some stuff so we can continue on.
char bracketMatch;
boolean goForward;
Element map = doc.getDefaultRootElement();
int curLine = map.getElementIndex(caretPosition);
Element line = map.getElement(curLine);
int start = line.getStartOffset();
int end = line.getEndOffset();
Token token = doc.getTokenListForLine(curLine);
token = RSyntaxUtilities.getTokenAtOffset(token, caretPosition);
// All brackets are always returned as "separators."
if (token.getType()!=Token.SEPARATOR) {
return input;
}
if (index<3) { // One of "{[("
goForward = true;
bracketMatch = BRACKETS.charAt(index + 3);
}
else { // One of ")]}"
goForward = false;
bracketMatch = BRACKETS.charAt(index - 3);
}
if (goForward) {
int lastLine = map.getElementCount();
// Start just after the found bracket since we're sure
// we're not in a comment.
start = caretPosition + 1;
int numEmbedded = 0;
boolean haveTokenList = false;
while (true) {
doc.getText(start,end-start, charSegment);
int segOffset = charSegment.offset;
for (int i=segOffset; i<segOffset+charSegment.count; i++) {
char ch = charSegment.array[i];
if (ch==bracket) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
token = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (token.getType()==Token.SEPARATOR)
numEmbedded++;
}
else if (ch==bracketMatch) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
token = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (token.getType()==Token.SEPARATOR) {
if (numEmbedded==0) {
if (textArea.isCodeFoldingEnabled() &&
textArea.getFoldManager().isLineHidden(curLine)) {
return input; // Match hidden in a fold
}
input.setLocation(caretPosition, offset);
return input;
}
numEmbedded--;
}
}
} // End of for (int i=segOffset; i<segOffset+charSegment.count; i++).
// Bail out if we've gone through all lines and
// haven't found the match.
if (++curLine==lastLine)
return input;
// Otherwise, go through the next line.
haveTokenList = false;
line = map.getElement(curLine);
start = line.getStartOffset();
end = line.getEndOffset();
} // End of while (true).
} // End of if (goForward).
// Otherwise, we're going backward through the file
// (since we found '}', ')' or ']').
else { // goForward==false
// End just before the found bracket since we're sure
// we're not in a comment.
end = caretPosition;// - 1;
int numEmbedded = 0;
boolean haveTokenList = false;
Token t2;
while (true) {
doc.getText(start,end-start, charSegment);
int segOffset = charSegment.offset;
int iStart = segOffset + charSegment.count - 1;
for (int i=iStart; i>=segOffset; i--) {
char ch = charSegment.array[i];
if (ch==bracket) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
t2 = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (t2.getType()==Token.SEPARATOR)
numEmbedded++;
}
else if (ch==bracketMatch) {
if (haveTokenList==false) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
t2 = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (t2.getType()==Token.SEPARATOR) {
if (numEmbedded==0) {
input.setLocation(caretPosition, offset);
return input;
}
numEmbedded--;
}
}
}
// Bail out if we've gone through all lines and
// haven't found the match.
if (--curLine==-1) {
return input;
}
// Otherwise, get ready for going through the
// next line.
haveTokenList = false;
line = map.getElement(curLine);
start = line.getStartOffset();
end = line.getEndOffset();
} // End of while (true).
} // End of else.
} catch (BadLocationException ble) {
// Shouldn't ever happen.
ble.printStackTrace();
}
// Something went wrong...
return input;
}
/**
* Returns the next non-whitespace, non-comment token in a text area.
*
* @param t The next token in this line's token list.
* @param textArea The text area.
* @param line The current line index (the line index of <code>t</code>).
* @return The next non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getPreviousImportantToken(RSyntaxTextArea, int)
*/
public static final Token getNextImportantToken(Token t,
RSyntaxTextArea textArea, int line) {
while (t!=null && t.isPaintable() && t.isCommentOrWhitespace()) {
t = t.getNextToken();
}
if ((t==null || !t.isPaintable()) && line<textArea.getLineCount()-1) {
t = textArea.getTokenListForLine(++line);
return getNextImportantToken(t, textArea, line);
}
return t;
}
/**
* Provides a way to determine the next visually represented model
* location at which one might place a caret.
* Some views may not be visible,
* they might not be in the same order found in the model, or they just
* might not allow access to some of the locations in the model.<p>
*
* NOTE: You should only call this method if the passed-in
* <code>javax.swing.text.View</code> is an instance of
* {@link TokenOrientedView} and <code>javax.swing.text.TabExpander</code>;
* otherwise, a <code>ClassCastException</code> could be thrown.
*
* @param pos the position to convert >= 0
* @param a the allocated region in which to render
* @param direction the direction from the current position that can
* be thought of as the arrow keys typically found on a keyboard.
* This will be one of the following values:
* <ul>
* <li>SwingConstants.WEST
* <li>SwingConstants.EAST
* <li>SwingConstants.NORTH
* <li>SwingConstants.SOUTH
* </ul>
* @return the location within the model that best represents the next
* location visual position
* @exception BadLocationException
* @exception IllegalArgumentException if <code>direction</code>
* doesn't have one of the legal values above
*/
public static int getNextVisualPositionFrom(int pos, Position.Bias b,
Shape a, int direction,
Position.Bias[] biasRet, View view)
throws BadLocationException {
RSyntaxTextArea target = (RSyntaxTextArea)view.getContainer();
biasRet[0] = Position.Bias.Forward;
// Do we want the "next position" above, below, to the left or right?
switch (direction) {
case NORTH:
case SOUTH:
if (pos == -1) {
pos = (direction == NORTH) ?
Math.max(0, view.getEndOffset() - 1) :
view.getStartOffset();
break;
}
Caret c = (target != null) ? target.getCaret() : null;
// YECK! Ideally, the x location from the magic caret
// position would be passed in.
Point mcp;
if (c != null)
mcp = c.getMagicCaretPosition();
else
mcp = null;
int x;
if (mcp == null) {
Rectangle loc = target.modelToView(pos);
x = (loc == null) ? 0 : loc.x;
}
else {
x = mcp.x;
}
if (direction == NORTH)
pos = getPositionAbove(target,pos,x,(TabExpander)view);
else
pos = getPositionBelow(target,pos,x,(TabExpander)view);
break;
case WEST:
if(pos == -1) {
pos = Math.max(0, view.getEndOffset() - 1);
}
else {
pos = Math.max(0, pos - 1);
if (target.isCodeFoldingEnabled()) {
int last = target.getLineOfOffset(pos+1);
int current = target.getLineOfOffset(pos);
if (last!=current) { // If moving up a line...
FoldManager fm = target.getFoldManager();
if (fm.isLineHidden(current)) {
while (--current>0 && fm.isLineHidden(current));
pos = target.getLineEndOffset(current) - 1;
}
}
}
}
break;
case EAST:
if(pos == -1) {
pos = view.getStartOffset();
}
else {
pos = Math.min(pos + 1, view.getDocument().getLength());
if (target.isCodeFoldingEnabled()) {
int last = target.getLineOfOffset(pos-1);
int current = target.getLineOfOffset(pos);
if (last!=current) { // If moving down a line...
FoldManager fm = target.getFoldManager();
if (fm.isLineHidden(current)) {
int lineCount = target.getLineCount();
while (++current<lineCount && fm.isLineHidden(current));
pos = current==lineCount ?
target.getLineEndOffset(last)-1 : // Was the last visible line
target.getLineStartOffset(current);
}
}
}
}
break;
default:
throw new IllegalArgumentException(
"Bad direction: " + direction);
}
return pos;
}
/**
* Determines the position in the model that is closest to the given
* view location in the row above. The component given must have a
* size to compute the result. If the component doesn't have a size
* a value of -1 will be returned.
*
* @param c the editor
* @param offs the offset in the document >= 0
* @param x the X coordinate >= 0
* @return the position >= 0 if the request can be computed, otherwise
* a value of -1 will be returned.
* @exception BadLocationException if the offset is out of range
*/
public static final int getPositionAbove(RSyntaxTextArea c, int offs,
float x, TabExpander e) throws BadLocationException {
TokenOrientedView tov = (TokenOrientedView)e;
Token token = tov.getTokenListForPhysicalLineAbove(offs);
if (token==null)
return -1;
// A line containing only Token.NULL is an empty line.
else if (token.getType()==Token.NULL) {
int line = c.getLineOfOffset(offs); // Sure to be >0 ??
return c.getLineStartOffset(line-1);
}
else {
return token.getListOffset(c, e, 0, x);
}
}
/**
* Determines the position in the model that is closest to the given
* view location in the row below. The component given must have a
* size to compute the result. If the component doesn't have a size
* a value of -1 will be returned.
*
* @param c the editor
* @param offs the offset in the document >= 0
* @param x the X coordinate >= 0
* @return the position >= 0 if the request can be computed, otherwise
* a value of -1 will be returned.
* @exception BadLocationException if the offset is out of range
*/
public static final int getPositionBelow(RSyntaxTextArea c, int offs,
float x, TabExpander e) throws BadLocationException {
TokenOrientedView tov = (TokenOrientedView)e;
Token token = tov.getTokenListForPhysicalLineBelow(offs);
if (token==null)
return -1;
// A line containing only Token.NULL is an empty line.
else if (token.getType()==Token.NULL) {
int line = c.getLineOfOffset(offs); // Sure to be > c.getLineCount()-1 ??
// return c.getLineStartOffset(line+1);
FoldManager fm = c.getFoldManager();
line = fm.getVisibleLineBelow(line);
return c.getLineStartOffset(line);
}
else {
return token.getListOffset(c, e, 0, x);
}
}
/**
* Returns the last non-whitespace, non-comment token, starting with the
* specified line.
*
* @param textArea The text area.
* @param line The line at which to start looking.
* @return The last non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getNextImportantToken(Token, RSyntaxTextArea, int)
*/
public static final Token getPreviousImportantToken(
RSyntaxTextArea textArea, int line){
if (line<0) {
return null;
}
Token t = textArea.getTokenListForLine(line);
if (t!=null) {
t = t.getLastNonCommentNonWhitespaceToken();
if (t!=null) {
return t;
}
}
return getPreviousImportantToken(textArea, line-1);
}
/**
* Returns the token at the specified index, or <code>null</code> if
* the given offset isn't in this token list's range.<br>
* Note that this method does NOT check to see if <code>tokenList</code>
* is null; callers should check for themselves.
*
* @param tokenList The list of tokens in which to search.
* @param offset The offset at which to get the token.
* @return The token at <code>offset</code>, or <code>null</code> if
* none of the tokens are at that offset.
*/
public static final Token getTokenAtOffset(Token tokenList, int offset) {
for (Token t=tokenList; t!=null && t.isPaintable(); t=t.getNextToken()){
if (t.containsPosition(offset))
return t;
}
return null;
}
/**
* Returns the end of the word at the given offset.
*
* @param textArea The text area.
* @param offs The offset into the text area's content.
* @return The end offset of the word.
* @throws BadLocationException If <code>offs</code> is invalid.
* @see #getWordStart(RSyntaxTextArea, int)
*/
public static int getWordEnd(RSyntaxTextArea textArea, int offs)
throws BadLocationException {
Document doc = textArea.getDocument();
int endOffs = textArea.getLineEndOffsetOfCurrentLine();
int lineEnd = Math.min(endOffs, doc.getLength());
if (offs == lineEnd) { // End of the line.
return offs;
}
String s = doc.getText(offs, lineEnd-offs-1);
if (s!=null && s.length()>0) { // Should always be true
int i = 0;
int count = s.length();
char ch = s.charAt(i);
if (Character.isWhitespace(ch)) {
while (i<count && Character.isWhitespace(s.charAt(i++)));
}
else if (Character.isLetterOrDigit(ch)) {
while (i<count && Character.isLetterOrDigit(s.charAt(i++)));
}
else {
i = 2;
}
offs += i - 1;
}
return offs;
}
/**
* Returns the start of the word at the given offset.
*
* @param textArea The text area.
* @param offs The offset into the text area's content.
* @return The start offset of the word.
* @throws BadLocationException If <code>offs</code> is invalid.
* @see #getWordEnd(RSyntaxTextArea, int)
*/
public static int getWordStart(RSyntaxTextArea textArea, int offs)
throws BadLocationException {
Document doc = textArea.getDocument();
Element line = getLineElem(doc, offs);
if (line == null) {
throw new BadLocationException("No word at " + offs, offs);
}
int lineStart = line.getStartOffset();
if (offs==lineStart) { // Start of the line.
return offs;
}
int endOffs = Math.min(offs+1, doc.getLength());
String s = doc.getText(lineStart, endOffs-lineStart);
if(s != null && s.length() > 0) {
int i = s.length() - 1;
char ch = s.charAt(i);
if (Character.isWhitespace(ch)) {
while (i>0 && Character.isWhitespace(s.charAt(i-1))) {
i--;
}
offs = lineStart + i;
}
else if (Character.isLetterOrDigit(ch)) {
while (i>0 && Character.isLetterOrDigit(s.charAt(i-1))) {
i--;
}
offs = lineStart + i;
}
}
return offs;
}
/**
* Determines the width of the given token list taking tabs
* into consideration. This is implemented in a 1.1 style coordinate
* system where ints are used and 72dpi is assumed.<p>
*
* This method also assumes that the passed-in token list begins at
* x-pixel <code>0</code> in the view (for tab purposes).
*
* @param tokenList The tokenList list representing the text.
* @param textArea The text area in which this token list resides.
* @param e The tab expander. This value cannot be <code>null</code>.
* @return The width of the token list, in pixels.
*/
public static final float getTokenListWidth(Token tokenList,
RSyntaxTextArea textArea,
TabExpander e) {
return getTokenListWidth(tokenList, textArea, e, 0);
}
/**
* Determines the width of the given token list taking tabs
* into consideration. This is implemented in a 1.1 style coordinate
* system where ints are used and 72dpi is assumed.<p>
*
* @param tokenList The token list list representing the text.
* @param textArea The text area in which this token list resides.
* @param e The tab expander. This value cannot be <code>null</code>.
* @param x0 The x-pixel coordinate of the start of the token list.
* @return The width of the token list, in pixels.
* @see #getTokenListWidthUpTo
*/
public static final float getTokenListWidth(final Token tokenList,
RSyntaxTextArea textArea,
TabExpander e, float x0) {
float width = x0;
for (Token t=tokenList; t!=null&&t.isPaintable(); t=t.getNextToken()) {
width += t.getWidth(textArea, e, width);
}
return width - x0;
}
/**
* Determines the width of the given token list taking tabs into
* consideration and only up to the given index in the document
* (exclusive).
*
* @param tokenList The token list representing the text.
* @param textArea The text area in which this token list resides.
* @param e The tab expander. This value cannot be <code>null</code>.
* @param x0 The x-pixel coordinate of the start of the token list.
* @param upTo The document position at which you want to stop,
* exclusive. If this position is before the starting position
* of the token list, a width of <code>0</code> will be
* returned; similarly, if this position comes after the entire
* token list, the width of the entire token list is returned.
* @return The width of the token list, in pixels, up to, but not
* including, the character at position <code>upTo</code>.
* @see #getTokenListWidth
*/
public static final float getTokenListWidthUpTo(final Token tokenList,
RSyntaxTextArea textArea, TabExpander e,
float x0, int upTo) {
float width = 0;
for (Token t=tokenList; t!=null&&t.isPaintable(); t=t.getNextToken()) {
if (t.containsPosition(upTo)) {
return width + t.getWidthUpTo(upTo-t.getOffset(), textArea, e,
x0+width);
}
width += t.getWidth(textArea, e, x0+width);
}
return width;
}
/**
* Returns whether or not this character is a "bracket" to be matched by
* such programming languages as C, C++, and Java.
*
* @param ch The character to check.
* @return Whether or not the character is a "bracket" - one of '(', ')',
* '[', ']', '{', and '}'.
*/
public static final boolean isBracket(char ch) {
// We need the first condition as it might be that ch>255, and thus
// not in our table. '}' is the highest-valued char in the bracket
// set.
return ch<='}' && (dataTable[ch]&BRACKET_MASK)>0;
}
/**
* Returns whether or not a character is a digit (0-9).
*
* @param ch The character to check.
* @return Whether or not the character is a digit.
*/
public static final boolean isDigit(char ch) {
// We do it this way as we'd need to do two conditions anyway (first
// to check that ch<255 so it can index into our table, then whether
// that table position has the digit mask).
return ch>='0' && ch<='9';
}
/**
* Returns whether or not this character is a hex character. This method
* accepts both upper- and lower-case letters a-f.
*
* @param ch The character to check.
* @return Whether or not the character is a hex character 0-9, a-f, or
* A-F.
*/
public static final boolean isHexCharacter(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table). 'f' is the highest-valued
// char that is a valid hex character.
return (ch<='f') && (dataTable[ch]&HEX_CHARACTER_MASK)>0;
}
/**
* Returns whether a character is a Java operator. Note that C and C++
* operators are the same as Java operators.
*
* @param ch The character to check.
* @return Whether or not the character is a Java operator.
*/
public static final boolean isJavaOperator(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table). '~' is the highest-valued
// char that is a valid Java operator.
return (ch<='~') && (dataTable[ch]&JAVA_OPERATOR_MASK)>0;
}
/**
* Returns whether a character is a US-ASCII letter (A-Z or a-z).
*
* @param ch The character to check.
* @return Whether or not the character is a US-ASCII letter.
*/
public static final boolean isLetter(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table).
return (ch<='z') && (dataTable[ch]&LETTER_MASK)>0;
}
/**
* Returns whether or not a character is a US-ASCII letter or a digit.
*
* @param ch The character to check.
* @return Whether or not the character is a US-ASCII letter or a digit.
*/
public static final boolean isLetterOrDigit(char ch) {
// We need the first condition as it could be that ch>255 (and thus
// not a valid index into our table).
return (ch<='z') && (dataTable[ch]&LETTER_OR_DIGIT_MASK)>0;
}
/**
* Returns whether the specified color is "light" to use as a foreground.
* Colors that return <code>true</code> indicate that the current Look and
* Feel probably uses light text colors on a dark background.
*
* @param fg The foreground color.
* @return Whether it is a "light" foreground color.
* @see #getHyperlinkForeground()
*/
public static final boolean isLightForeground(Color fg) {
return fg.getRed()>0xa0 && fg.getGreen()>0xa0 && fg.getBlue()>0xa0;
}
/**
* Returns whether or not a character is a whitespace character (either
* a space ' ' or tab '\t'). This checks for the Unicode character values
* 0x0020 and 0x0009.
*
* @param ch The character to check.
* @return Whether or not the character is a whitespace character.
*/
public static final boolean isWhitespace(char ch) {
// We do it this way as we'd need to do two conditions anyway (first
// to check that ch<255 so it can index into our table, then whether
// that table position has the whitespace mask).
return ch==' ' || ch=='\t';
}
/**
* Returns whether a regular expression token can follow the specified
* token in JavaScript.
*
* @param t The token to check, which may be <code>null</code>.
* @return Whether a regular expression token may follow this one in
* JavaScript.
*/
public static boolean regexCanFollowInJavaScript(Token t) {
char ch;
// We basically try to mimic Eclipse's JS editor's behavior here.
return t==null ||
//t.isOperator() ||
(t.length()==1 && (
(ch=t.charAt(0))=='=' ||
ch=='(' ||
ch==',' ||
ch=='?' ||
ch==':' ||
ch=='[' ||
ch=='!' ||
ch=='&'
)) ||
/* Operators "==", "===", "!=", "!==" */
(t.getType()==Token.OPERATOR &&
t.charAt(t.length()-1)=='=') ||
t.is(Token.RESERVED_WORD_2, JS_KEYWORD_RETURN);
}
/**
* If the character is an upper-case US-ASCII letter, it returns the
* lower-case version of that letter; otherwise, it just returns the
* character.
*
* @param ch The character to lower-case (if it is a US-ASCII upper-case
* character).
* @return The lower-case version of the character.
*/
public static final char toLowerCase(char ch) {
// We can logical OR with 32 because A-Z are 65-90 in the ASCII table
// and none of them have the 6th bit (32) set, and a-z are 97-122 in
// the ASCII table, which is 32 over from A-Z.
// We do it this way as we'd need to do two conditions anyway (first
// to check that ch<255 so it can index into our table, then whether
// that table position has the upper-case mask).
if (ch>='A' && ch<='Z')
return (char)(ch | 0x20);
return ch;
}
/**
* Returns an integer constant representing the OS. This can be handy for
* special case situations such as Mac OS-X (special application
* registration) or Windows (allow mixed case, etc.).
*
* @return An integer constant representing the OS.
*/
public static final int getOS() {
return OS;
}
/**
* Returns an integer constant representing the OS. This can be handy for
* special case situations such as Mac OS-X (special application
* registration) or Windows (allow mixed case, etc.).
*
* @return An integer constant representing the OS.
*/
private static final int getOSImpl() {
int os = OS_OTHER;
String osName = System.getProperty("os.name");
if (osName!=null) { // Should always be true.
osName = osName.toLowerCase();
if (osName.indexOf("windows") > -1)
os = OS_WINDOWS;
else if (osName.indexOf("mac os x") > -1)
os = OS_MAC_OSX;
else if (osName.indexOf("linux") > -1)
os = OS_LINUX;
else
os = OS_OTHER;
}
return os;
}
/**
* Creates a regular expression pattern that matches a "wildcard" pattern.
*
* @param wildcard The wildcard pattern.
* @param matchCase Whether the pattern should be case sensitive.
* @param escapeStartChar Whether to escape a starting <code>'^'</code>
* character.
* @return The pattern.
*/
public static Pattern wildcardToPattern(String wildcard, boolean matchCase,
boolean escapeStartChar) {
int flags = 0;
if (!matchCase) {
flags = Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE;
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<wildcard.length(); i++) {
char ch = wildcard.charAt(i);
switch (ch) {
case '*':
sb.append(".*");
break;
case '?':
sb.append('.');
break;
case '^':
if (i>0 || escapeStartChar) {
sb.append('\\');
}
sb.append('^');
break;
case '\\':
case '.': case '|':
case '+': case '-':
case '$':
case '[': case ']':
case '{': case '}':
case '(': case ')':
sb.append('\\').append(ch);
break;
default:
sb.append(ch);
break;
}
}
Pattern p = null;
try {
p = Pattern.compile(sb.toString(), flags);
} catch (PatternSyntaxException pse) {
pse.printStackTrace();
p = Pattern.compile(".+");
}
return p;
}
} | gpl-3.0 |
DarkSino98/Essentials | Essentials/src/com/earth2me/essentials/textreader/TextPager.java | 4490 | package com.earth2me.essentials.textreader;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.I18n;
import static com.earth2me.essentials.I18n._;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class TextPager
{
private final transient IText text;
private final transient boolean onePage;
public TextPager(final IText text)
{
this(text, false);
}
public TextPager(final IText text, final boolean onePage)
{
this.text = text;
this.onePage = onePage;
}
public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSource sender)
{
List<String> lines = text.getLines();
List<String> chapters = text.getChapters();
Map<String, Integer> bookmarks = text.getBookmarks();
//This code deals with the initial chapter. We use this to display the initial output or contents.
//We also use this code to display some extra information if we don't intend to use chapters
if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+"))
{
//If an info file starts with a chapter title, list the chapters
//If not display the text up until the first chapter.
if (!lines.isEmpty() && lines.get(0).startsWith("#"))
{
if (onePage)
{
return;
}
sender.sendMessage(_("infoChapter"));
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (String string : chapters)
{
if (!first)
{
sb.append(", ");
}
first = false;
sb.append(string);
}
sender.sendMessage(sb.toString());
return;
}
else
{
int page = 1;
try
{
page = Integer.parseInt(pageStr);
}
catch (NumberFormatException ex)
{
page = 1;
}
if (page < 1)
{
page = 1;
}
int start = onePage ? 0 : (page - 1) * 9;
int end;
for (end = 0; end < lines.size(); end++)
{
String line = lines.get(end);
if (line.startsWith("#"))
{
break;
}
}
int pages = end / 9 + (end % 9 > 0 ? 1 : 0);
if (!onePage && commandName != null)
{
StringBuilder content = new StringBuilder();
final String[] title = commandName.split(" ", 2);
if (title.length > 1)
{
content.append(I18n.capitalCase(title[0])).append(": ");
content.append(title[1]);
}
else
{
content.append(I18n.capitalCase(commandName));
}
sender.sendMessage(_("infoPages", page, pages, content));
}
for (int i = start; i < end && i < start + (onePage ? 20 : 9); i++)
{
sender.sendMessage("§r" + lines.get(i));
}
if (!onePage && page < pages && commandName != null)
{
sender.sendMessage(_("readNextPage", commandName, page + 1));
}
return;
}
}
//If we have a chapter, check to see if we have a page number
int chapterpage = 0;
if (chapterPageStr != null)
{
try
{
chapterpage = Integer.parseInt(chapterPageStr) - 1;
}
catch (NumberFormatException ex)
{
chapterpage = 0;
}
if (chapterpage < 0)
{
chapterpage = 0;
}
}
//This checks to see if we have the chapter in the index
if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH)))
{
sender.sendMessage(_("infoUnknownChapter"));
return;
}
//Since we have a valid chapter, count the number of lines in the chapter
final int chapterstart = bookmarks.get(pageStr.toLowerCase(Locale.ENGLISH)) + 1;
int chapterend;
for (chapterend = chapterstart; chapterend < lines.size(); chapterend++)
{
final String line = lines.get(chapterend);
if (line.length() > 0 && line.charAt(0) == '#')
{
break;
}
}
//Display the chapter from the starting position
final int start = chapterstart + (onePage ? 0 : chapterpage * 9);
final int page = chapterpage + 1;
final int pages = (chapterend - chapterstart) / 9 + ((chapterend - chapterstart) % 9 > 0 ? 1 : 0);
if (!onePage && commandName != null)
{
StringBuilder content = new StringBuilder();
content.append(I18n.capitalCase(commandName)).append(": ");
content.append(pageStr);
sender.sendMessage(_("infoChapterPages", content, page, pages));
}
for (int i = start; i < chapterend && i < start + (onePage ? 20 : 9); i++)
{
sender.sendMessage("§r" + lines.get(i));
}
if (!onePage && page < pages && commandName != null)
{
sender.sendMessage(_("readNextPage", commandName, pageStr + " " + (page + 1)));
}
}
}
| gpl-3.0 |
HelgeDMI/trollflow | java/org.eclipse.emf.mwe2.runtime.source_2.7.0.v201409021027/org/eclipse/emf/mwe2/runtime/Matches.java | 796 | /*******************************************************************************
* Copyright (c) 2008,2010 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.emf.mwe2.runtime;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Matches {
String value();
}
| gpl-3.0 |
waikato-datamining/adams-base | adams-core/src/main/java/adams/core/logging/MultiHandler.java | 4758 | /*
* 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/>.
*/
/**
* MultiHandler.java
* Copyright (C) 2017 University of Waikato, Hamilton, NZ
*/
package adams.core.logging;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Combines multiple handlers.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class MultiHandler
extends AbstractLogHandler {
/** the logging handlers to use. */
protected Handler[] m_Handlers;
/**
* Initializes the members.
*/
@Override
protected void initialize() {
super.initialize();
setHandlers(new Handler[0]);
}
/**
* Sets the handlers to use.
*
* @param value the handlers
*/
public void setHandlers(Handler[] value) {
m_Handlers = value;
reset();
}
/**
* Returns the current handlers.
*
* @return the handlers
*/
public Handler[] getHandlers() {
return m_Handlers;
}
/**
* Adds the specified handler.
*
* @param value the handler
*/
public void addHandler(Handler value) {
Handler[] handlers;
int i;
handlers = new Handler[m_Handlers.length + 1];
for (i = 0; i < m_Handlers.length; i++)
handlers[i] = m_Handlers[i];
handlers[handlers.length - 1] = value;
m_Handlers = handlers;
}
/**
* Removes the specified handler.
*
* @param index the handler index
*/
public void removeHandler(int index) {
Handler[] handlers;
int i;
int n;
handlers = new Handler[m_Handlers.length - 1];
n = 0;
for (i = 0; i < m_Handlers.length; i++) {
if (i == index)
continue;
handlers[n] = m_Handlers[i];
n++;
}
m_Handlers = handlers;
}
/**
* Flush any buffered output.
*/
@Override
public void flush() {
super.flush();
if (m_Handlers != null) {
for (Handler h : m_Handlers)
h.flush();
}
}
/**
* Close the <tt>Handler</tt> and free all associated resources.
* <p>
* The close method will perform a <tt>flush</tt> and then close the
* <tt>Handler</tt>. After close has been called this <tt>Handler</tt>
* should no longer be used. Method calls may either be silently
* ignored or may throw runtime exceptions.
*
* @exception SecurityException if a security manager exists and if
* the caller does not have <tt>LoggingPermission("control")</tt>.
*/
@Override
public void close() throws SecurityException {
if (m_Handlers != null) {
for (Handler h : m_Handlers)
h.close();
}
super.close();
}
/**
* Publish a <tt>LogRecord</tt>.
* <p>
* The logging request was made initially to a <tt>Logger</tt> object,
* which initialized the <tt>LogRecord</tt> and forwarded it here.
* <p>
* The <tt>Handler</tt> is responsible for formatting the message, when and
* if necessary. The formatting should include localization.
*
* @param record description of the log event. A null record is
* silently ignored and is not published
*/
@Override
protected void doPublish(LogRecord record) {
for (Handler h: m_Handlers)
h.publish(record);
}
/**
* Compares the handler with itself.
*
* @param o the other handler
* @return less than 0, equal to 0, or greater than 0 if the
* handler is less, equal to, or greater than this one
*/
public int compareTo(Handler o) {
int result;
MultiHandler other;
int i;
result = super.compareTo(o);
if (result == 0) {
other = (MultiHandler) o;
result = new Integer(getHandlers().length).compareTo(other.getHandlers().length);
if (result == 0) {
for (i = 0; i < getHandlers().length; i++) {
if ((getHandlers()[i] instanceof AbstractLogHandler) && (other.getHandlers()[i] instanceof AbstractLogHandler))
result = ((AbstractLogHandler) getHandlers()[i]).compareTo(other.getHandlers()[i]);
else
result = new Integer(getHandlers()[i].hashCode()).compareTo(other.getHandlers()[i].hashCode());
if (result != 0)
break;
}
}
}
return result;
}
}
| gpl-3.0 |
Olyol95/Saga | src/org/saga/shape/BlockFilter.java | 957 | package org.saga.shape;
import org.bukkit.Material;
import org.bukkit.block.Block;
import java.util.HashSet;
public class BlockFilter implements ShapeFilter {
/**
* Materials.
*/
private HashSet<Material> materials = new HashSet<>();
/**
* If true then the check will return the reverse result.
*/
private boolean flip = false;
// Initialisation:
/**
* Initialises.
*
*/
public BlockFilter() {
}
/**
* Adds a material.
*
* @param material
* material
*/
public void addMaterial(Material material) {
materials.add(material);
}
/**
* Flips the check result.
*
*/
public void flip() {
flip = true;
}
// Filtering:
/*
* (non-Javadoc)
*
* @see org.saga.shape.ShapeFilter#checkBlock(org.bukkit.block.Block)
*/
@Override
public boolean checkBlock(Block block) {
if (flip)
return !materials.contains(block.getType());
return materials.contains(block.getType());
}
}
| gpl-3.0 |
LeoTremblay/activityinfo | server/src/main/java/org/activityinfo/ui/client/component/importDialog/validation/ValidationMappingGrid.java | 1707 | package org.activityinfo.ui.client.component.importDialog.validation;
/*
* #%L
* ActivityInfo Server
* %%
* Copyright (C) 2009 - 2013 UNICEF
* %%
* 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 com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.TextHeader;
import com.google.gwt.user.client.ui.ResizeComposite;
import org.activityinfo.core.shared.importing.validation.ValidationResult;
import org.activityinfo.i18n.shared.I18N;
import org.activityinfo.ui.client.style.table.DataGridResources;
import java.util.List;
/**
* @author yuriyz on 4/30/14.
*/
public class ValidationMappingGrid extends ResizeComposite {
private DataGrid<ValidationResult> dataGrid;
public ValidationMappingGrid() {
this.dataGrid = new DataGrid<>(100, DataGridResources.INSTANCE);
dataGrid.addColumn(new ValidationClassGridColumn(), new TextHeader(I18N.CONSTANTS.message()));
initWidget(dataGrid);
}
public void refresh(List<ValidationResult> resultList) {
dataGrid.setRowData(resultList);
}
}
| gpl-3.0 |
AnodeCathode/ForestryMC | src/main/java/forestry/apiculture/gui/ContainerAlveary.java | 1213 | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.apiculture.gui;
import net.minecraft.entity.player.InventoryPlayer;
import forestry.apiculture.multiblock.TileAlvearyPlain;
import forestry.core.gui.ContainerTile;
import forestry.core.network.PacketGuiUpdate;
public class ContainerAlveary extends ContainerTile<TileAlvearyPlain> {
public ContainerAlveary(InventoryPlayer player, TileAlvearyPlain tile) {
super(tile, player, 8, 108);
ContainerBeeHelper.addSlots(this, tile, false);
}
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
PacketGuiUpdate packet = new PacketGuiUpdate(tile);
sendPacketToCrafters(packet);
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE2_ast/src/cide/gast/ASTStringNode.java | 1275 | /**
Copyright 2010 Christian Kästner
This file is part of CIDE.
CIDE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
CIDE 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 CIDE. If not, see <http://www.gnu.org/licenses/>.
See http://www.fosd.de/cide/ for further information.
*/
package cide.gast;
import java.util.ArrayList;
public class ASTStringNode extends ASTNode {
private String value;
public ASTStringNode(String value, IToken token) {
super(new ArrayList<Property>(), token, token);
this.value = value;
}
public String getValue() {
return value;
}
public String toString() {
return value;
}
@Override
public IASTNode deepCopy() {
return new ASTStringNode(new String(value), firstToken);
}
@Override
public String render() {
return getValue();
}
}
| gpl-3.0 |
Token3/books-source-code | corejava9/src/main/java/v2ch10/compiler/ByteArrayJavaClass.java | 656 | package v2ch10.compiler;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import javax.tools.SimpleJavaFileObject;
/**
* A Java class that holds the byte codes in a byte array. Created by ZHEN on 16/9/18.
*/
public class ByteArrayJavaClass extends SimpleJavaFileObject {
private ByteArrayOutputStream stream;
public ByteArrayJavaClass(String name) {
super(URI.create("bytes:///" + name), Kind.CLASS);
this.stream = new ByteArrayOutputStream();
}
public OutputStream openOutputStream() {
return stream;
}
public byte[] getBytes() {
return stream.toByteArray();
}
}
| gpl-3.0 |
jfinkels/jeffraytracer | src/test/java/jeffraytracer/surfaces/BoxTest.java | 3385 | /**
* BoxTest.java - test for the Box class
*
* Copyright 2011 Jeffrey Finkelstein
*
* This file is part of jeffraytracer.
*
* jeffraytracer 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.
*
* jeffraytracer 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
* jeffraytracer. If not, see <http://www.gnu.org/licenses/>.
*/
package jeffraytracer.surfaces;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import jeffraytracer.Ray;
import jeffraytracer.Vector3D;
import org.junit.Test;
/**
* Test for the Box class.
*
* @author Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>
* @since Spring 2011
*/
public class BoxTest {
/**
* Test method for
* {@link jeffraytracer.surfaces.Box#interceptWith(jeffraytracer.Ray)}.
*/
@Test
public void testInterceptWith() {
final Box b = new Box();
b.setPosition(new Vector3D(0, 0, 10));
b.setDimensions(new Vector3D(1, 3, 5));
b.setOrientation(Orientation.STANDARD_BASIS);
// must compile before checking intersections
b.compile();
// the front face
final Ray r = new Ray();
r.setPosition(new Vector3D(0, 0, 0));
r.setDirection(new Vector3D(0, 0, 1));
Intercept i = b.interceptWith(r);
assertNotNull(i);
assertEquals(7.5, i.time(), 0);
assertSame(b, i.surfaceObject());
// the rear face
r.setPosition(new Vector3D(0, 0, 20));
r.setDirection(new Vector3D(0, 0, -1));
i = b.interceptWith(r);
assertNotNull(i);
assertEquals(7.5, i.time(), 0);
assertSame(b, i.surfaceObject());
// the right face
r.setPosition(new Vector3D(5, 0, 10));
r.setDirection(new Vector3D(-1, 0, 0));
i = b.interceptWith(r);
assertNotNull(i);
assertEquals(4.5, i.time(), 0);
assertSame(b, i.surfaceObject());
// the left face
r.setPosition(new Vector3D(-5, 0, 10));
r.setDirection(new Vector3D(1, 0, 0));
i = b.interceptWith(r);
assertNotNull(i);
assertEquals(4.5, i.time(), 0);
assertSame(b, i.surfaceObject());
// the top face
r.setPosition(new Vector3D(0, 10, 10));
r.setDirection(new Vector3D(0, -1, 0));
i = b.interceptWith(r);
assertNotNull(i);
assertEquals(8.5, i.time(), 0);
assertSame(b, i.surfaceObject());
// the bottom face
r.setPosition(new Vector3D(0, -10, 10));
r.setDirection(new Vector3D(0, 1, 0));
i = b.interceptWith(r);
assertNotNull(i);
assertEquals(8.5, i.time(), 0);
assertSame(b, i.surfaceObject());
// rays that should miss
r.setPosition(Vector3D.ORIGIN);
r.setDirection(new Vector3D(1, 1, 0).normalized());
i = b.interceptWith(r);
assertNull(i);
r.setPosition(new Vector3D(20, 20, 20));
r.setDirection(new Vector3D(1, 1, 1).normalized());
i = b.interceptWith(r);
assertNull(i);
}
}
| gpl-3.0 |
CardiacAtlasProject/xpacs-web | src/main/java/org/cardiacatlas/xpacs/repository/PatientInfoRepository.java | 348 | package org.cardiacatlas.xpacs.repository;
import org.cardiacatlas.xpacs.domain.PatientInfo;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the PatientInfo entity.
*/
@SuppressWarnings("unused")
public interface PatientInfoRepository extends JpaRepository<PatientInfo,Long> {
}
| gpl-3.0 |
GotoLink/AncientWarfare2 | src/main/java/net/shadowmage/ancientwarfare/automation/container/ContainerWarehouseStorage.java | 7239 | package net.shadowmage.ancientwarfare.automation.container;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import net.shadowmage.ancientwarfare.automation.tile.warehouse2.IWarehouseStorageTile;
import net.shadowmage.ancientwarfare.automation.tile.warehouse2.TileControlled;
import net.shadowmage.ancientwarfare.automation.tile.warehouse2.TileWarehouseStorage;
import net.shadowmage.ancientwarfare.automation.tile.warehouse2.WarehouseStorageFilter;
import net.shadowmage.ancientwarfare.core.container.ContainerBase;
import net.shadowmage.ancientwarfare.core.container.ContainerTileBase;
import net.shadowmage.ancientwarfare.core.inventory.ItemQuantityMap;
import net.shadowmage.ancientwarfare.core.inventory.ItemQuantityMap.ItemHashEntry;
import java.util.ArrayList;
import java.util.List;
public class ContainerWarehouseStorage extends ContainerTileBase<TileWarehouseStorage> {
public int guiHeight;
public int areaSize;
int playerSlotsSize;
int playerSlotsY;
boolean shouldSynch = true;
public ItemQuantityMap itemMap = new ItemQuantityMap();
public ItemQuantityMap cache = new ItemQuantityMap();
public List<WarehouseStorageFilter> filters = new ArrayList<WarehouseStorageFilter>();
public ContainerWarehouseStorage(EntityPlayer player, int x, int y, int z) {
super(player, x, y, z);
tileEntity.addViewer(this);
areaSize = 5 * 18 + 16;
playerSlotsY = 148 + 8;
playerSlotsSize = 8 + 4 + 4 * 18;
guiHeight = playerSlotsY + playerSlotsSize;
filters.addAll(tileEntity.getFilters());
addPlayerSlots(8, playerSlotsY, 4);
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotClickedIndex) {
if (player.worldObj.isRemote) {
return null;
}
Slot slot = this.getSlot(slotClickedIndex);
if (slot == null || !slot.getHasStack()) {
return null;
}
ItemStack stack = slot.getStack();
stack = tileEntity.tryAdd(stack);
if (stack == null) {
slot.putStack(null);
}
detectAndSendChanges();
return null;
}
public void handleClientRequestSpecific(ItemStack stack, boolean isShiftClick) {
NBTTagCompound tag = new NBTTagCompound();
if (stack != null) {
tag.setTag("reqItem", stack.writeToNBT(new NBTTagCompound()));
}
tag.setBoolean("isShiftClick", isShiftClick);
NBTTagCompound pktTag = new NBTTagCompound();
pktTag.setTag("slotClick", tag);
sendDataToServer(pktTag);
}
@Override
public void sendInitData() {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("filterList", WarehouseStorageFilter.writeFilterList(filters));
sendDataToClient(tag);
}
public void sendFiltersToServer() {
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("filterList", WarehouseStorageFilter.writeFilterList(filters));
sendDataToServer(tag);
}
@Override
public void handlePacketData(NBTTagCompound tag) {
if (tag.hasKey("filterList")) {
List<WarehouseStorageFilter> filters = WarehouseStorageFilter.readFilterList(tag.getTagList("filterList", Constants.NBT.TAG_COMPOUND), new ArrayList<WarehouseStorageFilter>());
if (player.worldObj.isRemote) {
this.filters.clear();
this.filters.addAll(filters);
refreshGui();
} else {
tileEntity.setFilters(filters);
}
}
if (tag.hasKey("slotClick")) {
NBTTagCompound reqTag = tag.getCompoundTag("slotClick");
ItemStack item = null;
if (reqTag.hasKey("reqItem")) {
item = ItemStack.loadItemStackFromNBT(reqTag.getCompoundTag("reqItem"));
}
tileEntity.handleSlotClick(player, item, reqTag.getBoolean("isShiftClick"));
}
if (tag.hasKey("changeList")) {
handleChangeList(tag.getTagList("changeList", Constants.NBT.TAG_COMPOUND));
refreshGui();
}
super.handlePacketData(tag);
}
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
if (shouldSynch) {
synchItemMaps();
shouldSynch = false;
}
}
private void handleChangeList(NBTTagList changeList) {
NBTTagCompound tag;
int qty;
ItemHashEntry wrap = null;
for (int i = 0; i < changeList.tagCount(); i++) {
tag = changeList.getCompoundTagAt(i);
wrap = ItemHashEntry.readFromNBT(tag);
qty = tag.getInteger("qty");
if (qty == 0) {
itemMap.remove(wrap);
} else {
itemMap.put(wrap, qty);
}
}
}
private void synchItemMaps() {
/**
*
* need to loop through this.itemMap and compare quantities to warehouse.itemMap
* add any changes to change-list
* need to loop through warehouse.itemMap and find new entries
* add any new entries to change-list
*/
cache.clear();
tileEntity.addItems(cache);
ItemQuantityMap warehouseItemMap = cache;
int qty;
NBTTagList changeList = new NBTTagList();
NBTTagCompound tag;
for (ItemHashEntry wrap : this.itemMap.keySet()) {
qty = this.itemMap.getCount(wrap);
if (qty != warehouseItemMap.getCount(wrap)) {
qty = warehouseItemMap.getCount(wrap);
tag = wrap.writeToNBT(new NBTTagCompound());
tag.setInteger("qty", qty);
changeList.appendTag(tag);
this.itemMap.put(wrap, qty);
}
}
for (ItemHashEntry entry : warehouseItemMap.keySet()) {
if (!itemMap.contains(entry)) {
qty = warehouseItemMap.getCount(entry);
tag = ItemHashEntry.writeToNBT(entry, new NBTTagCompound());
tag.setInteger("qty", qty);
changeList.appendTag(tag);
this.itemMap.put(entry, qty);
}
}
if (changeList.tagCount() > 0) {
tag = new NBTTagCompound();
tag.setTag("changeList", changeList);
sendDataToClient(tag);
}
}
public void onStorageInventoryUpdated() {
shouldSynch = true;
}
public void onFilterListUpdated() {
this.filters.clear();
this.filters.addAll(tileEntity.getFilters());
sendInitData();
}
@Override
public void onContainerClosed(EntityPlayer par1EntityPlayer) {
tileEntity.removeViewer(this);
super.onContainerClosed(par1EntityPlayer);
}
}
| gpl-3.0 |
am910021/YuriMS | src/server/maps/MapleTVEffect.java | 2984 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.maps;
import java.rmi.RemoteException;
import java.util.List;
import client.MapleCharacter;
import java.util.ArrayList;
import net.world.remote.WorldChannelInterface;
import server.TimerManager;
import tools.MaplePacketCreator;
/*
* MapleTVEffect
* @author MrXotic
*/
public class MapleTVEffect {
private List<String> message = new ArrayList<String>(5);
private MapleCharacter user;
private static boolean active;
private int type;
private MapleCharacter partner;
public MapleTVEffect(MapleCharacter user_, MapleCharacter partner_, List<String> msg, int type_) {
this.message = msg;
this.user = user_;
this.type = type_;
this.partner = partner_;
broadcastTV(true);
}
public static boolean isActive() {
return active;
}
private void setActive(boolean set) {
active = set;
}
private void broadcastTV(boolean active_) {
WorldChannelInterface wci = user.getClient().getChannelServer().getWorldInterface();
setActive(active_);
try {
if (active_) {
wci.broadcastMessage(null, MaplePacketCreator.enableTV().getBytes());
wci.broadcastMessage(null, MaplePacketCreator.sendTV(user, message, type <= 2 ? type : type - 3, partner).getBytes());
int delay = 15000;
if (type == 4) {
delay = 30000;
} else if (type == 5) {
delay = 60000;
}
TimerManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
broadcastTV(false);
}
}, delay);
} else {
wci.broadcastMessage(null, MaplePacketCreator.removeTV().getBytes());
}
} catch (RemoteException re) {
user.getClient().getChannelServer().reconnectWorld();
}
}
}
| gpl-3.0 |
slub/urnlib | src/main/java/de/slub/urn/URNSyntaxError.java | 4308 | /*
* Copyright (C) 2017 Saxon State and University Library Dresden (SLUB)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.slub.urn;
/**
* An Exception which is thrown if a URN or any part of a URN cannot be parsed due to violations of the URN syntax.
* <p>
* It supports three different syntax errors and stores a reference to the RFC that has been violated.
*
* @author Ralf Claussnitzer
*/
public class URNSyntaxError extends Exception {
private ErrorTypes error;
private RFC violatedRfc;
/**
* Construct a new syntax error exception.
*
* @param msg Error message
* @param error The identified violation error
* @param violatedRfc The violated RFC
*/
public URNSyntaxError(String msg, ErrorTypes error, RFC violatedRfc) {
super(msg);
this.error = error;
this.violatedRfc = violatedRfc;
}
/**
* @see Exception#Exception(String)
*/
public URNSyntaxError(String msg) {
super(msg);
}
/**
* @see Exception#Exception(String, Throwable)
*/
public URNSyntaxError(String msg, Throwable t) {
super(msg, t);
}
/**
* Create a new syntax error representing a `reserved identifier` error.
*
* @param rfc The violated RFC
* @param nid The namespace identifier
* @return URNSyntaxError exception for throwing
*/
public static URNSyntaxError reservedIdentifier(RFC rfc, String nid) {
return new URNSyntaxError(
String.format("Namespace identifier can not be '%s'", nid),
ErrorTypes.RESERVED,
rfc);
}
/**
* Create a new syntax error representing a `syntactically invalid identifier` error.
*
* @param rfc The violated RFC
* @param msg A detailed error message
* @return URNSyntaxError exception for throwing
*/
public static URNSyntaxError syntaxError(RFC rfc, String msg) {
return new URNSyntaxError(msg, ErrorTypes.SYNTAX_ERROR, rfc);
}
/**
* Create a new syntax error representing a `length` error.
*
* @param rfc The violated RFC
* @param nid The namespace identifier
* @return URNSyntaxError exception for throwing
*/
public static URNSyntaxError lengthError(RFC rfc, String nid) {
return new URNSyntaxError(
String.format("Namespace Identifier '%s' is too long. Only 32 characters are allowed.", nid),
ErrorTypes.LENGTH_ERROR,
rfc);
}
public ErrorTypes getError() {
return error;
}
public RFC getViolatedRfc() {
return violatedRfc;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s [Error %3d]\n\nThis is probably a violation of %s",
getMessage(), error.getCode(), violatedRfc.name()));
if (!error.getViolatedRfcSection().isEmpty()) {
sb.append(", section ").append(error.getViolatedRfcSection());
}
sb.append("\nSee ").append(violatedRfc.url());
return sb.toString();
}
public enum ErrorTypes {
RESERVED(10, "2.1"),
SYNTAX_ERROR(15, ""),
LENGTH_ERROR(20, "2");
private final int code;
private final String violatedRfcSection;
ErrorTypes(int code, String violatedRfcSection) {
this.code = code;
this.violatedRfcSection = violatedRfcSection;
}
public int getCode() {
return code;
}
public String getViolatedRfcSection() {
return violatedRfcSection;
}
}
}
| gpl-3.0 |
ConsideredHamster/YetAnotherPixelDungeon | app/src/main/java/com/consideredhamster/yetanotherpixeldungeon/levels/traps/AlarmTrap.java | 1902 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Yet Another Pixel Dungeon
* Copyright (C) 2015-2016 Considered Hamster
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.consideredhamster.yetanotherpixeldungeon.levels.traps;
import com.consideredhamster.yetanotherpixeldungeon.actors.Actor;
import com.consideredhamster.yetanotherpixeldungeon.actors.Char;
import com.watabou.noosa.audio.Sample;
import com.consideredhamster.yetanotherpixeldungeon.visuals.Assets;
import com.consideredhamster.yetanotherpixeldungeon.Dungeon;
import com.consideredhamster.yetanotherpixeldungeon.actors.mobs.Mob;
import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.CellEmitter;
import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.Speck;
import com.consideredhamster.yetanotherpixeldungeon.misc.utils.GLog;
public class AlarmTrap extends Trap {
// 0xDD3333
public static void trigger( int pos, Char ch ) {
for (Mob mob : Dungeon.level.mobs) {
if (mob.pos != pos) {
mob.beckon( pos );
}
}
if (Dungeon.visible[pos]) {
GLog.w( "The trap emits a piercing sound that echoes throughout the dungeon!" );
CellEmitter.center( pos ).start( Speck.factory( Speck.SCREAM ), 0.3f, 3 );
}
Sample.INSTANCE.play( Assets.SND_ALERT );
}
}
| gpl-3.0 |
ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/DataTypePointInTime.java | 786 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>DataTypePointInTimeのJavaクラス。
*
* <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
* <p>
* <pre>
* <simpleType name="DataTypePointInTime">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="TS"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "DataTypePointInTime")
@XmlEnum
public enum DataTypePointInTime {
TS;
public String value() {
return name();
}
public static DataTypePointInTime fromValue(String v) {
return valueOf(v);
}
}
| gpl-3.0 |
Escapecraft/FalseBook | src/main/java/com/bukkit/gemo/FalseBook/Cart/utils/FBInventory.java | 1292 | package com.bukkit.gemo.FalseBook.Cart.utils;
import net.minecraft.server.v1_6_R3.Container;
import net.minecraft.server.v1_6_R3.EntityHuman;
import net.minecraft.server.v1_6_R3.InventoryCrafting;
import net.minecraft.server.v1_6_R3.ItemStack;
public class FBInventory extends InventoryCrafting {
private ItemStack[] items = new ItemStack[9];
public FBInventory(Container container, int i, int j) {
super(container, i, j);
}
public FBInventory() {
super((Container)null, 3, 3);
}
public ItemStack[] getContents() {
return this.items;
}
public int getSize() {
return 1;
}
public ItemStack getItem(int i) {
return this.items[i];
}
public String getName() {
return "Result";
}
public ItemStack splitStack(int i, int j) {
if(this.items[i] != null) {
ItemStack itemstack = this.items[i];
this.items[i] = null;
return itemstack;
} else {
return null;
}
}
public void setItem(int i, ItemStack itemstack) {
this.items[i] = itemstack;
}
public int getMaxStackSize() {
return 64;
}
public void update() {}
public boolean a(EntityHuman entityhuman) {
return true;
}
public void f() {}
public void g() {}
}
| gpl-3.0 |
Joshua-Barclay/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WVideo.java | 21133 | package com.github.bordertech.wcomponents;
import com.github.bordertech.wcomponents.util.Util;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* WVideo is used to display video content on the client.
*
* @author Yiannis Paschalidis
* @since 1.0.0
*/
public class WVideo extends AbstractWComponent implements Targetable, AjaxTarget, Disableable {
/**
* The logger instance for this class.
*/
private static final Log LOG = LogFactory.getLog(WVideo.class);
/**
* This request parameter is used to determine which video clip to serve up.
*/
private static final String VIDEO_INDEX_REQUEST_PARAM_KEY = "WVideo.videoIndex";
/**
* This request parameter is used to determine which track to serve up.
*/
private static final String TRACK_INDEX_REQUEST_PARAM_KEY = "WVideo.trackIndex";
/**
* This request parameter is used to request the poster image.
*/
private static final String POSTER_REQUEST_PARAM_KEY = "WVideo.poster";
/**
* This is used to indicate whether pre-loading of content should occur before the clip is played.
*/
public enum Preload {
/**
* Do not pre-load any data.
*/
NONE,
/**
* Preload meta-data only.
*/
META_DATA,
/**
* Let the client determine what to load.
*/
AUTO
}
/**
* This is used to indicate which playback controls to display for the video.
*
* <p>
* <strong>Note:</strong>
* Advancements in video support in clients since this API was first implemented means that most of this is now
* redundant. Under most circumstances the UI will display their native video controls. Where a particular WVideo
* does not have any source which is able to be played by the client then links to all sources will be provided.
* This enum is not worthless as the values NONE and PLAY_PAUSE are used to turn off native video controls in the
* client. The value NONE however causes major problems and is incompatible with autoplay for a11y reasons so it
* basically makes the media worthless. This enum may be replaced in the future with a simple boolean to trigger
* native controls or play/pause only (see https://github.com/BorderTech/wcomponents/issues/503).
* </p>
*/
public enum Controls {
/**
* Do not display any controls: not recommended. May be incompatible with any of {@link #isAutoplay()} == true,
* {@link #isMuted()} == true or {@link #isLoop()} == true. If this value is set then the WVideo control
* <strong>MAY NOT WORK AT ALL</strong>.
* @deprecated since 1.1.1 as this is incompatible with WCAG requirements.
*/
NONE,
/**
* Display all controls.
* @deprecated since 1.1.1 as themes use native video controls.
*/
ALL,
/**
* A combined play/pause button.
*/
PLAY_PAUSE,
/**
* Displays the "default" set of controls for the theme.
* @deprecated since 1.1.1 as themes use native video controls.
*/
DEFAULT,
/**
* Displays the client's native set of controls.
*/
NATIVE
}
/**
* Creates a WVideo with no video clips. Video clips must be added later by calling one of the setVideo(...)
* methods.
*/
public WVideo() {
}
/**
* Creates a WVideo with the given video clip.
*
* @param video the video clip.
*/
public WVideo(final Video video) {
this(new Video[]{video});
}
/**
* <p>
* Creates a WVideo with the given static content. This is provided as a convenience method for when the video file
* is included as static content in the class path rather than in the web application's resources.
* </p>
* <p>
* The mime type for the video clip is looked up from the "mimeType.*" mapping configuration parameters using the
* resource's file extension.
* </p>
*
* @param resource the resource path to the video file.
*/
public WVideo(final String resource) {
this(new VideoResource(resource));
}
/**
* Creates a WVideo with the given video clip in multiple formats. The client will try to load the first video clip,
* and if it fails or isn't supported, it will move on to the next video clip. Only the first clip which can be
* played on the client will be used.
*
* @param video multiple formats for the same the video clip.
*/
public WVideo(final Video[] video) {
setVideo(video);
}
/**
* Sets the video clip.
*
* @param video the video clip.
*/
public void setVideo(final Video video) {
setVideo(new Video[]{video});
}
/**
* Sets the video clip in multiple formats. The client will try to load the first video clip, and if it fails or
* isn't supported, it will move on to the next video clip. Only the first clip which can be played on the client
* will be used.
*
* @param video multiple formats for the same the video clip.
*/
public void setVideo(final Video[] video) {
List<Video> list = video == null ? null : Arrays.asList(video);
getOrCreateComponentModel().video = list;
}
/**
* Retrieves the video clips associated with this WVideo.
*
* @return the video clips, may be null.
*/
public Video[] getVideo() {
List<Video> list = getComponentModel().video;
return list == null ? null : list.toArray(new Video[]{});
}
/**
* Indicates whether the video component is disabled.
*
* @return true if the component is disabled, otherwise false.
*/
@Override
public boolean isDisabled() {
return isFlagSet(ComponentModel.DISABLED_FLAG);
}
/**
* Sets whether the video component is disabled.
*
* @param disabled if true, the component is disabled. If false, it is enabled.
*/
@Override
public void setDisabled(final boolean disabled) {
setFlag(ComponentModel.DISABLED_FLAG, disabled);
}
/**
* @return true if the clip should start playing automatically, false for a manual start.
*/
public boolean isAutoplay() {
return getComponentModel().autoplay;
}
/**
* Sets whether the clip should play automatically.
*
* @param autoplay true to start playing automatically, false for a manual start.
*/
public void setAutoplay(final boolean autoplay) {
getOrCreateComponentModel().autoplay = autoplay;
}
/**
* @return the media group name.
*/
public String getMediaGroup() {
return getComponentModel().mediaGroup;
}
/**
* Sets the media group.
*
* @param mediaGroup The media group name.
*/
public void setMediaGroup(final String mediaGroup) {
getOrCreateComponentModel().mediaGroup = mediaGroup;
}
/**
* Indicates whether the video clip playback should loop.
*
* @return true to loop, false to stop at the end.
*/
public boolean isLoop() {
return getComponentModel().loop;
}
/**
* Sets whether the video clip playback should loop or stop at the end.
*
* @param loop true to loop, false to stop at the end.
*/
public void setLoop(final boolean loop) {
getOrCreateComponentModel().loop = loop;
}
/**
* Indicates whether the video's audio should initially be muted.
*
* @return true if muted, false otherwise.
*/
public boolean isMuted() {
return getComponentModel().muted;
}
/**
* Sets whether the video's audio should initially be muted.
*
* @param muted true to mute the audio, false to play normally.
*/
public void setMuted(final boolean muted) {
getOrCreateComponentModel().muted = muted;
}
/**
* Indicates which playback controls (e.g. stop/start/pause) to display on the video component.
*
* @return the playback controls to display.
*/
public Controls getControls() {
return getComponentModel().controls;
}
/**
* Sets which playback controls (e.g. stop/start/pause) to display on the video component. The values of
* {@link Controls#NONE} and {@link Controls#ALL} take precedence over all other values. Passing a null or empty set
* of controls will cause the client's default set of controls to be used.
*
* @param controls the playback controls to display.
*/
public void setControls(final Controls controls) {
getOrCreateComponentModel().controls = controls;
}
/**
* Indicates how pre-loading of content should occur before the clip is played.
*
* @return the pre-loading mode.
*/
public Preload getPreload() {
return getComponentModel().preload;
}
/**
* Sets how pre-loading of content should occur before the clip is played.
*
* @param preload the pre-loading mode.
*/
public void setPreload(final Preload preload) {
getOrCreateComponentModel().preload = preload;
}
/**
* @return alternative text to display when the video clip can not be played.
*/
public String getAltText() {
return getComponentModel().altText;
}
/**
* Sets the alternative text to display when the video clip can not be played.
*
* @param altText the text to set.
*/
public void setAltText(final String altText) {
getOrCreateComponentModel().altText = altText;
}
/**
* @return the width of the video playback region on the client, in pixels.
*/
public int getWidth() {
return getComponentModel().width;
}
/**
* Sets the width of the video playback region on the client.
*
* @param width the width of the video playback region, in pixels.
*/
public void setWidth(final int width) {
getOrCreateComponentModel().width = width;
}
/**
* @return the height of the video playback region on the client, in pixels.
*/
public int getHeight() {
return getComponentModel().height;
}
/**
* Sets the height of the video playback region on the client.
*
* @param height the height of the video playback region, in pixels.
*/
public void setHeight(final int height) {
getOrCreateComponentModel().height = height;
}
/**
* Retrieves the default poster image. The poster image is displayed by the client when the video is not playing.
*
* @return the default poster image.
*/
public Image getPoster() {
return getComponentModel().poster;
}
/**
* Sets the default poster image. The poster image is displayed by the client when the video is not playing.
*
* @param poster the default poster image.
*/
public void setPoster(final Image poster) {
getOrCreateComponentModel().poster = poster;
}
/**
* Sets the tracks for the video. The tracks are used to provide additional information relating to the video, for
* example subtitles.
*
* @param tracks additional tracks relating to the video.
*/
public void setTracks(final Track[] tracks) {
List<Track> list = tracks == null ? null : Arrays.asList(tracks);
getOrCreateComponentModel().tracks = list;
}
/**
* Retrieves additional tracks associated with the video. The tracks provide additional information relating to the
* video, for example subtitles.
*
* @return the video clips, may be null.
*/
public Track[] getTracks() {
List<Track> list = getComponentModel().tracks;
return list == null ? null : list.toArray(new Track[]{});
}
/**
* Creates dynamic URLs that the video clips can be loaded from. In fact the URL points to the main application
* servlet, but includes a non-null for the parameter associated with this WComponent (ie, its label). The
* handleRequest method below detects this when the browser requests a file.
*
* @return the urls to load the video files from, or null if there are no clips defined.
*/
public String[] getVideoUrls() {
Video[] video = getVideo();
if (video == null || video.length == 0) {
return null;
}
String[] urls = new String[video.length];
// this variable needs to be set in the portlet environment.
String url = getEnvironment().getWServletPath();
Map<String, String> parameters = getBaseParameterMap();
for (int i = 0; i < urls.length; i++) {
parameters.put(VIDEO_INDEX_REQUEST_PARAM_KEY, String.valueOf(i));
urls[i] = WebUtilities.getPath(url, parameters, true);
}
return urls;
}
/**
* Creates dynamic URLs that the video clips can be loaded from. In fact the URL points to the main application
* servlet, but includes a non-null for the parameter associated with this WComponent (ie, its label). The
* handleRequest method below detects this when the browser requests a file.
*
* @return the urls to load the video files from, or null if there are no clips defined.
*/
public String[] getTrackUrls() {
Track[] tracks = getTracks();
if (tracks == null || tracks.length == 0) {
return null;
}
String[] urls = new String[tracks.length];
// this variable needs to be set in the portlet environment.
String url = getEnvironment().getWServletPath();
Map<String, String> parameters = getBaseParameterMap();
for (int i = 0; i < urls.length; i++) {
parameters.put(TRACK_INDEX_REQUEST_PARAM_KEY, String.valueOf(i));
urls[i] = WebUtilities.getPath(url, parameters, true);
}
return urls;
}
/**
* Creates a dynamic URL that the poster can be loaded from. In fact the URL points to the main application servlet,
* but includes a non-null for the parameter associated with this WComponent (ie, its label). The handleRequest
* method below detects this when the browser requests a file.
*
* @return the url to load the poster from, or null if there is no poster defined.
*/
public String getPosterUrl() {
Image poster = getComponentModel().poster;
if (poster == null) {
return null;
}
// this variable needs to be set in the portlet environment.
String url = getEnvironment().getWServletPath();
Map<String, String> parameters = getBaseParameterMap();
parameters.put(POSTER_REQUEST_PARAM_KEY, "x");
return WebUtilities.getPath(url, parameters, true);
}
/**
* Retrieves the base parameter map for serving content (videos + tracks).
*
* @return the base map for serving content.
*/
private Map<String, String> getBaseParameterMap() {
Environment env = getEnvironment();
Map<String, String> parameters = env.getHiddenParameters();
parameters.put(Environment.TARGET_ID, getTargetId());
if (Util.empty(getCacheKey())) {
// Add some randomness to the URL to prevent caching
String random = WebUtilities.generateRandom();
parameters.put(Environment.UNIQUE_RANDOM_PARAM, random);
} else {
// Remove step counter as not required for cached content
parameters.remove(Environment.STEP_VARIABLE);
parameters.remove(Environment.SESSION_TOKEN_VARIABLE);
// Add the cache key
parameters.put(Environment.CONTENT_CACHE_KEY, getCacheKey());
}
return parameters;
}
/**
* Override isVisible to also return false if there are no video clips to play.
*
* @return true if this component is visible in the given context, otherwise false.
*/
@Override
public boolean isVisible() {
if (!super.isVisible()) {
return false;
}
Video[] video = getVideo();
return video != null && video.length > 0;
}
/**
* When an video element is rendered to the client, the browser will make a second request to get the video content.
* The handleRequest method has been overridden to detect whether the request is the "content fetch" request by
* looking for the parameter that we encode in the content url.
*
* @param request the request being responded to.
*/
@Override
public void handleRequest(final Request request) {
super.handleRequest(request);
String targ = request.getParameter(Environment.TARGET_ID);
boolean contentReqested = (targ != null && targ.equals(getTargetId()));
if (contentReqested && request.getParameter(POSTER_REQUEST_PARAM_KEY) != null) {
handlePosterRequest();
}
if (isDisabled()) {
return;
}
if (contentReqested) {
if (request.getParameter(VIDEO_INDEX_REQUEST_PARAM_KEY) != null) {
handleVideoRequest(request);
} else if (request.getParameter(TRACK_INDEX_REQUEST_PARAM_KEY) != null) {
handleTrackRequest(request);
}
}
}
/**
* Handles a request for the poster.
*/
private void handlePosterRequest() {
Image poster = getComponentModel().poster;
if (poster != null) {
ContentEscape escape = new ContentEscape(poster);
escape.setCacheable(!Util.empty(getCacheKey()));
throw escape;
} else {
LOG.warn("Client requested non-existant poster");
}
}
/**
* Handles a request for a video.
*
* @param request the request being responded to.
*/
private void handleVideoRequest(final Request request) {
String videoRequested = request.getParameter(VIDEO_INDEX_REQUEST_PARAM_KEY);
int videoFileIndex = 0;
try {
videoFileIndex = Integer.parseInt(videoRequested);
} catch (NumberFormatException e) {
LOG.error("Failed to parse video index: " + videoFileIndex);
}
Video[] video = getVideo();
if (video != null && videoFileIndex >= 0 && videoFileIndex < video.length) {
ContentEscape escape = new ContentEscape(video[videoFileIndex]);
escape.setCacheable(!Util.empty(getCacheKey()));
throw escape;
} else {
LOG.warn("Client requested invalid video clip: " + videoFileIndex);
}
}
/**
* Handles a request for an auxillary track.
*
* @param request the request being responded to.
*/
private void handleTrackRequest(final Request request) {
String trackRequested = request.getParameter(TRACK_INDEX_REQUEST_PARAM_KEY);
int trackIndex = 0;
try {
trackIndex = Integer.parseInt(trackRequested);
} catch (NumberFormatException e) {
LOG.error("Failed to parse track index: " + trackIndex);
}
Track[] tracks = getTracks();
if (tracks != null && trackIndex >= 0 && trackIndex < tracks.length) {
ContentEscape escape = new ContentEscape(tracks[trackIndex]);
escape.setCacheable(!Util.empty(getCacheKey()));
throw escape;
} else {
LOG.warn("Client requested invalid track: " + trackIndex);
}
}
/**
* @return the cacheKey
*/
public String getCacheKey() {
return getComponentModel().cacheKey;
}
/**
* @param cacheKey the cacheKey to set.
*/
public void setCacheKey(final String cacheKey) {
getOrCreateComponentModel().cacheKey = cacheKey;
}
/**
* Returns the id to use to target this component.
*
* @return this component's target id.
*/
@Override
public String getTargetId() {
return getId();
}
/**
* @return a String representation of this component, for debugging purposes.
*/
@Override
public String toString() {
String text = getAltText();
return toString(text == null ? null : ('"' + text + '"'));
}
// --------------------------------
// Extrinsic state management
/**
* Creates a new component model appropriate for this component.
*
* @return a new VideoModel.
*/
@Override
protected VideoModel newComponentModel() {
return new VideoModel();
}
/**
* {@inheritDoc}
*/
@Override
// For type safety only
protected VideoModel getComponentModel() {
return (VideoModel) super.getComponentModel();
}
/**
* {@inheritDoc}
*/
@Override
// For type safety only
protected VideoModel getOrCreateComponentModel() {
return (VideoModel) super.getOrCreateComponentModel();
}
/**
* Holds the extrinsic state information of a WVideo.
*/
public static class VideoModel extends ComponentModel {
/**
* The various video clips.
*/
private List<Video> video;
/**
* Additional tracks relating to the video, e.g. subtitles.
*/
private List<Track> tracks;
/**
* The cache key used to control client-side caching.
*/
private String cacheKey;
/**
* Indicates whether the video should play immediately after page load.
*/
private boolean autoplay;
/**
* Indicates whether playback of the video clip should be looped.
*/
private boolean loop;
/**
* Indicates whether audio should initially be muted.
*/
private boolean muted;
/**
* Indicates which playback controls to display.
*/
private Controls controls;
/**
* Indicates whether pre-loading of content should occur before the clip is played.
*/
private Preload preload = Preload.NONE;
/**
* Alternate text to display if the video clip can not be played.
*/
private String altText;
/**
* The width of the video playback region on the client, in pixels.
*/
private int width;
/**
* The height of the video playback region on the client, in pixels.
*/
private int height;
/**
* The poster image is displayed in place of the video, until it is loaded.
*/
private Image poster;
/**
* This is used to group related media together, for example to synchronize tracks.
*/
private String mediaGroup;
}
}
| gpl-3.0 |
moltam89/OWXP | modules/micro-maintainance-outdated-task/src/main/java/com/liferay/micro/maintainance/configuration/OutdatedTaskConfiguration.java | 533 | package com.liferay.micro.maintainance.configuration;
import aQute.bnd.annotation.metatype.Meta;
/**
* @author Rimi Saadou
* @author Laszlo Hudak
*/
@Meta.OCD(
id = "com.liferay.micro.maintainance.configuration.OutdatedTaskConfiguration"
)
public interface OutdatedTaskConfiguration {
@Meta.AD(deflt = "14", required = false)
public int votingPeriodDays();
@Meta.AD(deflt = "5", required = false)
public int requiredVotingPercentage();
@Meta.AD(deflt = "5", required = false)
public int requiredYesVotesPercentage();
} | gpl-3.0 |
ccrama/Slide | app/src/main/java/me/ccrama/redditslide/Activities/MakeExternal.java | 972 | package me.ccrama.redditslide.Activities;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import java.net.MalformedURLException;
import java.net.URL;
import me.ccrama.redditslide.SettingValues;
/**
* Created by ccrama on 9/28/2015.
*/
public class MakeExternal extends Activity {
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
String url = getIntent().getStringExtra("url");
if (url != null) {
try {
URL u = new URL(url);
SettingValues.alwaysExternal.add(u.getHost());
SharedPreferences.Editor e = SettingValues.prefs.edit();
e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
e.apply();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
finish();
}
}
| gpl-3.0 |
ccem-dev/otus-api | source/otus-persistence/src/main/java/br/org/otus/laboratory/project/builder/ExamResultQueryBuilder.java | 2339 | package br.org.otus.laboratory.project.builder;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.google.gson.GsonBuilder;
public class ExamResultQueryBuilder {
private ArrayList<Bson> pipeline;
public ExamResultQueryBuilder() {
this.pipeline = new ArrayList<>();
}
public List<Bson> build() {
return this.pipeline;
}
public ExamResultQueryBuilder getExamResultsWithAliquotValid() {
pipeline.add(this.parseQuery("{$match:{\"objectType\":\"ExamResults\",\"isValid\":true}}"));
return this;
}
public ExamResultQueryBuilder getSortingByExamName() {
pipeline.add(this.parseQuery("{$sort:{\"resultName\":1}}"));
return this;
}
public ExamResultQueryBuilder getSortingByRecruitmentNumber() {
pipeline.add(this.parseQuery("{$sort:{\"recruitmentNumber\":1}}"));
return this;
}
public ExamResultQueryBuilder getGroupOfExamResultsToExtraction() {
Document group = this.parseQuery("{\n" +
" $group: {\n" +
" _id: \"$recruitmentNumber\",\n" +
" results:{\n" +
" $push:{\n" +
" \"recruitmentNumber\":\"$recruitmentNumber\",\n" +
" \"code\":\"$code\",\n" +
" \"examName\":\"$examName\",\n" +
" \"resultName\":\"$resultName\",\n" +
" \"value\":\"$value\",\n" +
" \"releaseDate\":\"$releaseDate\",\n" +
" \"realizationDate\":\"$realizationDate\",\n" +
" \"observations\":\"$observations\",\n" +
" \"cutOffValue\":\"$cutOffValue\",\n" +
" \"extraVariables\":\"$extraVariables\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }");
pipeline.add(group);
return this;
}
public ExamResultQueryBuilder getProjectionOfExamResultsToExtraction() {
Document project = this.parseQuery("{\n" +
" $project: {\n" +
" recruitmentNumber: \"$_id\",\n" +
" _id: 0,\n" +
" results:\"$results\"\n" +
" }\n" +
" }");
pipeline.add(project);
return this;
}
private Document parseQuery(String query) {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create().fromJson(query, Document.class);
}
}
| gpl-3.0 |
onycom-ankus/ankus_analyzer_G | trunk_web/ankus-web-services/src/main/java/org/ankus/core/repository/PersistentRepository.java | 1895 | /**
* This file is part of ankus.
*
* ankus 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.
*
* ankus 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 ankus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ankus.core.repository;
/**
* Persistence Object의 공통 CRUD를 정의한 Repository.
*
* @author Edward KIM
* @since 0.3
*/
public interface PersistentRepository<D, P> {
/**
* 새로운 객체를 저장한다.
*
* @param object 저장할 객체
* @param
* @param runcase
* @return 저장한 건수
*/
int insert(D object);
/**
* 지정한 객체의 정보를 업데이트한다.
*
* @param object 업데이트할 객객체
* @param runcase
* @return 업데이트 건수
*/
int update(D object);
/**
* 지정한 식별자에 해당하는 객체를 삭제한다.
*
* @param identifier 식별자
* @return 삭제한 건수
*/
int delete(P identifier);
/**
* 지정한 식별자에 해당하는 객체를 조회한다.
*
* @param identifier 식별자
* @return 식별자로 식별하는 객체
*/
D select(P identifier);
/**
* 지정한 식별자에 해당하는 객체가 존재하는지 확인한다.
*
* @param identifier 식별자
* @return 존재하는 경우 <tt>true</tt>
*/
boolean exists(P identifier);
} | gpl-3.0 |
Greymerk/minecraft-roguelike | src/main/java/greymerk/roguelike/dungeon/settings/SettingsResolver.java | 4942 | package greymerk.roguelike.dungeon.settings;
import java.util.Collection;
import java.util.Random;
import greymerk.roguelike.config.RogueConfig;
import greymerk.roguelike.util.WeightedChoice;
import greymerk.roguelike.util.WeightedRandomizer;
import greymerk.roguelike.worldgen.Coord;
import greymerk.roguelike.worldgen.IWorldEditor;
public class SettingsResolver {
private ISettingsContainer settings;
public SettingsResolver(ISettingsContainer settings) throws Exception{
this.settings = settings;
}
// called from Dungeon class
public ISettings getSettings(IWorldEditor editor, Random rand, Coord pos) throws Exception{
if(RogueConfig.getBoolean(RogueConfig.RANDOM)) return new SettingsRandom(rand);
DungeonSettings builtin = this.getBuiltin(editor, rand, pos);
DungeonSettings custom = this.getCustom(editor, rand, pos);
// there are no valid dungeons for this location
if(builtin == null && custom == null) return null;
DungeonSettings exclusive = (custom != null) ? custom : builtin;
DungeonSettings complete = applyInclusives(exclusive, editor, rand, pos);
return complete;
}
public ISettings getWithName(String name, IWorldEditor editor, Random rand, Coord pos) throws Exception{
if(name.equals("random")) return new SettingsRandom(rand);
DungeonSettings byName = this.getByName(name);
if(byName == null) return null;
DungeonSettings withInclusives = applyInclusives(byName, editor, rand, pos);
return new DungeonSettings(new SettingsBlank(), withInclusives);
}
public static DungeonSettings processInheritance(DungeonSettings toProcess, ISettingsContainer settings) throws Exception{
DungeonSettings setting = new SettingsBlank();
if(toProcess == null) throw new Exception("Process Inheritance called with null settings object");
for(SettingIdentifier id : toProcess.getInherits()){
if(settings.contains(id)){
DungeonSettings inherited = new DungeonSettings(settings.get(id));
if(!inherited.getInherits().isEmpty()){
inherited = processInheritance(inherited, settings);
}
setting = new DungeonSettings(setting, inherited);
} else {
throw new Exception("Setting not found: " + id.toString());
}
}
return new DungeonSettings(setting, toProcess);
}
public ISettings getDefaultSettings(){
return new DungeonSettings(settings.get(new SettingIdentifier(SettingsContainer.BUILTIN_NAMESPACE, "base")));
}
private DungeonSettings getByName(String name) throws Exception{
SettingIdentifier id;
try{
id = new SettingIdentifier(name);
} catch (Exception e){
throw new Exception("Malformed Setting ID String: " + name);
}
if(!this.settings.contains(id)) return null;
DungeonSettings setting = new DungeonSettings(this.settings.get(id));
return processInheritance(setting, this.settings);
}
private DungeonSettings getBuiltin(IWorldEditor editor, Random rand, Coord pos) throws Exception{
if(!RogueConfig.getBoolean(RogueConfig.SPAWNBUILTIN)) return null;
WeightedRandomizer<DungeonSettings> settingsRandomizer = new WeightedRandomizer<DungeonSettings>();
for(DungeonSettings setting : settings.getBuiltinSettings()){
if(setting.isValid(editor, pos)){
settingsRandomizer.add(new WeightedChoice<DungeonSettings>(setting, setting.criteria.weight));
}
}
if(settingsRandomizer.isEmpty()) return null;
DungeonSettings chosen = settingsRandomizer.get(rand);
return processInheritance(chosen, settings);
}
private DungeonSettings getCustom(IWorldEditor editor, Random rand, Coord pos) throws Exception{
WeightedRandomizer<DungeonSettings> settingsRandomizer = new WeightedRandomizer<DungeonSettings>();
for(DungeonSettings setting : settings.getCustomSettings()){
if(setting.isValid(editor, pos) && setting.isExclusive()){
settingsRandomizer.add(new WeightedChoice<DungeonSettings>(setting, setting.criteria.weight));
}
}
DungeonSettings chosen = settingsRandomizer.get(rand);
if(chosen == null) return null;
return processInheritance(chosen, settings);
}
private DungeonSettings applyInclusives(DungeonSettings setting, IWorldEditor editor, Random rand, Coord pos) throws Exception{
DungeonSettings toReturn = new DungeonSettings(setting);
for(DungeonSettings s : settings.getCustomSettings()){
if(!s.isValid(editor, pos)) continue;
if(s.isExclusive()) continue;
toReturn = new DungeonSettings(toReturn, processInheritance(s, settings));
}
return toReturn;
}
public String toString(String namespace){
Collection<DungeonSettings> byNamespace = this.settings.getByNamespace(namespace);
if(byNamespace.isEmpty()) return "";
String toReturn = "";
for(DungeonSettings setting : byNamespace){
toReturn += setting.id.toString() + " ";
}
return toReturn;
}
@Override
public String toString(){
return this.settings.toString();
}
}
| gpl-3.0 |
claesn/ir2017 | ir2017/src/main/java/de/uni_koeln/spinfo/textengineering/ir/eval/GoldStandard.java | 1252 | package de.uni_koeln.spinfo.textengineering.ir.eval;
import java.util.ArrayList;
import java.util.List;
import de.uni_koeln.spinfo.textengineering.ir.basic.Work;
import de.uni_koeln.spinfo.textengineering.ir.boole.PositionalIndex;
import de.uni_koeln.spinfo.textengineering.ir.preprocess.Preprocessor;
/*
* Erstellung eines Dummy-Goldstandards auf Grundlage unseres Shakespeare-Korpus
*/
public class GoldStandard {
public static List<Integer> create(PositionalIndex index, String query) {
List<Integer> result = new ArrayList<Integer>();
Preprocessor p = new Preprocessor();
List<String> q = p.tokenize(query);
int docId = 0;
for (Work d : index.getWorks()) {
/*
* Für unsere Experimente mit P, R und F betrachten wir ein Dokument immer dann als relevant, wenn ein Term
* der Anfrage im Titel des Dokuments enthalten ist:
*/
if (containsAny(d.getTitle(), q)) {
result.add(docId);
}
docId++;
}
return result;
}
private static boolean containsAny(String title, List<String> query) {
for (String q : query) {
/* Wir geben true zurück wenn ein Element der Anfrage im Titel enthalten ist: */
if (title.toLowerCase().contains(q.toLowerCase())) {
return true;
}
}
return false;
}
}
| gpl-3.0 |
ahmadaghazadeh/recyclerviewcardview | app/src/main/java/ahmad/aghazadeh/recyclerviewcardview/logic/BindingCustom.java | 2117 | package ahmad.aghazadeh.recyclerviewcardview.logic;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.graphics.Palette;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
/**
* Created by 890683 on 1/10/2016.
*/
public class BindingCustom {
@BindingAdapter("fontName")
public static void setFontName(TextView view, @Nullable String fontName) {
String fontPath = "/fonts/" + fontName;
view.setTypeface(Project.getTypeFace(view.getContext(),fontPath));
}
@BindingAdapter({"imageUrl", "error", "paletteResId"})
public static void loadImage(final ImageView view, String url, @Nullable Drawable error, @Nullable final int paletteResId) {
com.squareup.picasso.Callback callback = new Callback() {
@Override
public void onSuccess() {
Bitmap photo = Project.drawableToBitmap(view.getDrawable());
Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
int mutedLight = palette.getMutedColor(view.getContext().getResources().getColor(android.R.color.white));
View paletteLayout = (view.getRootView()).findViewById(paletteResId);
if(paletteLayout!=null){
paletteLayout.setBackgroundColor(mutedLight);
}
}
});
}
@Override
public void onError() {
}
};
Picasso.with(view.getContext()).load(url).error(error).into(view, callback);
}
}
| gpl-3.0 |
rockoutwill/LetsModReboot | src/main/java/com/rockoutwill/letsmodreboot/proxy/ServerProxy.java | 95 | package com.rockoutwill.letsmodreboot.proxy;
public class ServerProxy extends CommonProxy {
}
| gpl-3.0 |
ingenitor/BlockEnvy | src/main/java/com/ingenitor/blockenvy/proxy/CommonProxy.java | 203 | /**
*
*/
package com.ingenitor.blockenvy.proxy;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
/**
* @author ingenitor
*
*/
public abstract class CommonProxy implements IProxy {
}
| gpl-3.0 |
tavomaciel/games-for-enterprise-programmers | core/src/com/gustavomaciel/enterprise/CollisionResolver.java | 1986 | package com.gustavomaciel.enterprise;
import com.badlogic.gdx.utils.Array;
import com.gustavomaciel.enterprise.CollisionGroups.CollisionGroup;
/**
* Created by Gustavo on 5/22/2016.
*/
public class CollisionResolver {
public static void checkAndResolve(Array<Entity> entities) {
for(int i = 0, s = entities.size; i < s; ++i) {
Entity first = entities.get(i);
if(first.isMarkedForDeletion() || first.isCollisionDisabled()) continue;
for(int j = i+1; j < s; ++j) {
Entity second = entities.get(j);
if(second.isMarkedForDeletion() || second.isCollisionDisabled()) continue;
check(first, second);
}
}
}
private static void check(Entity first, Entity second) {
final CollisionGroup firstCG = first.getCollisionGroup();
final CollisionGroup secondCG = second.getCollisionGroup();
boolean firstInterested = firstCG.matches(secondCG);
boolean secondInterested = secondCG.matches(firstCG);
if(firstInterested || secondInterested) {
if(first.position.x < second.position.x + second.size.x && first.position.x + first.size.x > second.position.x
&& first.position.y < second.position.y + second.size.y && first.position.y + first.size.y > second.position.y) {
float intersectionX = 0.5f * (Math.max(first.position.x, second.position.x) + Math.min(first.position.x + first.size.x, second.position.x + second.size.x));
float intersectionY = 0.5f * (Math.max(first.position.y, second.position.y) + Math.min(first.position.y + first.size.y, second.position.y + second.size.y));
if(firstInterested) {
first.onCollision(second, intersectionX, intersectionY);
}
if(secondInterested) {
second.onCollision(first, intersectionX, intersectionY);
}
}
}
}
}
| gpl-3.0 |
DannyHui/Article | src/service/ArticleService.java | 1058 | package service;
import java.util.List;
import java.util.Map;
import util.DataBaseUtils;
public class ArticleService {
/**
* 通过类别获取文章列表
* @param categoryId
* @param start
* @param end
*/
public List<Map<String,Object>> getArticlesByCategoryId(Integer categoryId,Integer start,Integer end){
String sql = "select id,header,name,author,"
+ "description from t_article where 1 = 1 "
+ " and is_delete = 0"
+ " and is_published = 1"
+ " and category_id = ?"
+ " order by update_time desc limit ?,?";
return DataBaseUtils.queryForList(sql, categoryId,start,end);
}
/**
* 通过文章id获取文章内容
* @param id
* @return
*/
public Map<String,Object> getContentByArticleId(String id){
String sql = "select a.id,a.name,a.content,a.create_time,a.author,b.name as category_name from t_article a inner join t_category b on a.category_id = b.id where a.id = ?";
return DataBaseUtils.queryForList(sql,id).get(0);
}
}
| gpl-3.0 |
OpenBD/openbd-core | src/com/naryx/tagfusion/cfm/xml/ws/dynws/StubInfo.java | 4431 | /*
* Copyright (C) 2000 - 2008 TagServlet Ltd
*
* This file is part of Open BlueDragon (OpenBD) CFML Server Engine.
*
* OpenBD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* Free Software Foundation,version 3.
*
* OpenBD 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 OpenBD. If not, see http://www.gnu.org/licenses/
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with any of the JARS listed in the README.txt (or a modified version of
* (that library), containing parts covered by the terms of that JAR, the
* licensors of this Program grant you additional permission to convey the
* resulting work.
* README.txt @ http://www.openbluedragon.org/license/README.txt
*
* http://www.openbluedragon.org/
*/
/*
* Created on Jan 8, 2005
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.naryx.tagfusion.cfm.xml.ws.dynws;
import java.io.Serializable;
/**
* Value object to hold operation and parameter information for web service
* Stubs.
*/
public class StubInfo implements Serializable {
private static final long serialVersionUID = 1L;
protected StubInfo.Operation[] operations = null;
protected String lName = null;
protected String sName = null;
protected String portName = null;
protected String wsdlSum = null;
public StubInfo() {}
public StubInfo(String lName, String sName, String wsdlSum, String portName, StubInfo.Operation[] operations) {
this.lName = lName;
this.sName = sName;
this.portName = portName;
this.operations = operations;
this.wsdlSum = wsdlSum;
}
public String getLocatorName() {
return this.lName;
}
public void setLocatorName(String pVal) {
this.lName = pVal;
}
public String getStubName() {
return this.sName;
}
public void setStubName(String pVal) {
this.sName = pVal;
}
public String getWSDLSum() {
return this.wsdlSum;
}
public void setWSDLSum(String pVal) {
this.wsdlSum = pVal;
}
public String getPortName() {
return this.portName;
}
public void setPortName(String pVal) {
this.portName = pVal;
}
public StubInfo.Operation[] getOperations() {
return this.operations;
}
public void setOperations(StubInfo.Operation[] pVal) {
this.operations = pVal;
}
public static class Operation implements Serializable {
private static final long serialVersionUID = 1L;
protected String name = null;
protected StubInfo.Parameter[] parameters = null;
protected StubInfo.Parameter[] subParameters = null;
public Operation() {
}
public Operation(String name, StubInfo.Parameter[] parms) {
this.name = name;
this.parameters = parms;
}
public String getName() {
return this.name;
}
public void setName(String pVal) {
this.name = pVal;
}
public StubInfo.Parameter[] getParameters() {
return this.parameters;
}
public void setParameters(StubInfo.Parameter[] pVal) {
this.parameters = pVal;
}
public StubInfo.Parameter[] getSubParameters() {
return this.subParameters;
}
public void setSubParameters(StubInfo.Parameter[] pVal) {
this.subParameters = pVal;
}
}
public static class Parameter implements Serializable {
private static final long serialVersionUID = 1L;
protected String name = null;
protected boolean nillable = false;
protected boolean omittable = false;
public Parameter() {
}
public Parameter(String name, boolean nillable, boolean omittable) {
this.name = name;
this.omittable = omittable;
this.nillable = nillable;
}
public String getName() {
return this.name;
}
public void setName(String pVal) {
this.name = pVal;
}
public boolean getNillable() {
return this.nillable;
}
public void setNillable(boolean pVal) {
this.nillable = pVal;
}
public boolean getOmittable() {
return this.omittable;
}
public void setOmittable(boolean pVal) {
this.omittable = pVal;
}
}
}
| gpl-3.0 |
Infernalized/InfernalUtils | src/main/java/net/infernalized/infernalutils/client/gui/GuiFactory.java | 681 | package net.infernalized.infernalutils.client.gui;
import cpw.mods.fml.client.IModGuiFactory;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import java.util.Set;
public class GuiFactory implements IModGuiFactory {
@Override
public void initialize(Minecraft minecraftInstance) {
}
@Override
public Class<? extends GuiScreen> mainConfigGuiClass() {
return null;
}
@Override
public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() {
return null;
}
@Override
public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) {
return null;
}
}
| gpl-3.0 |
apruden/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/presenter/RequestAdministrationPermissionEvent.java | 1805 | /*******************************************************************************
* Copyright (c) 2012 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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 org.obiba.opal.web.gwt.app.client.administration.presenter;
import org.obiba.opal.web.gwt.rest.client.authorization.HasAuthorization;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Fire this event to have all administration presenters authorize themselves and callback on this
* {@code HasAuthorization}.
* <p/>
* This allows decoupling a link to the administration section from the section's content.
*/
public class RequestAdministrationPermissionEvent extends GwtEvent<RequestAdministrationPermissionEvent.Handler> {
public interface Handler extends EventHandler {
void onAdministrationPermissionRequest(RequestAdministrationPermissionEvent event);
}
private static final Type<Handler> TYPE = new Type<Handler>();
private final HasAuthorization authorization;
public RequestAdministrationPermissionEvent(HasAuthorization authorization) {
this.authorization = authorization;
}
public HasAuthorization getHasAuthorization() {
return authorization;
}
public static Type<Handler> getType() {
return TYPE;
}
@Override
protected void dispatch(Handler handler) {
handler.onAdministrationPermissionRequest(this);
}
@Override
public GwtEvent.Type<Handler> getAssociatedType() {
return getType();
}
}
| gpl-3.0 |
autentia/TNTConcept | tntconcept-core/src/main/java/com/autentia/tnt/businessobject/InventaryType.java | 862 | /**
* TNTConcept Easy Enterprise Management by Autentia Real Bussiness Solution S.L.
* Copyright (C) 2007 Autentia Real Bussiness Solution S.L.
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.autentia.tnt.businessobject;
public enum InventaryType {
PC, LAPTOP, BOOK, KEY, CARD, CAR
} | gpl-3.0 |
guiguilechat/EveOnline | model/esi/JCESI/src/generated/java/fr/guiguilechat/jcelechat/model/jcesi/compiler/compiled/responses/R_get_universe_systems_system_id.java | 2884 | package fr.guiguilechat.jcelechat.model.jcesi.compiler.compiled.responses;
public class R_get_universe_systems_system_id {
/**
* The constellation this solar system is in
*/
public int constellation_id;
/**
* name string
*/
public String name;
/**
* planets array
*/
public get_universe_systems_system_id_planets[] planets;
/**
* position object
*/
public M_3_xnumber_ynumber_znumber position;
/**
* security_class string
*/
public String security_class;
/**
* security_status number
*/
public float security_status;
/**
* star_id integer
*/
public int star_id;
/**
* stargates array
*/
public int[] stargates;
/**
* stations array
*/
public int[] stations;
/**
* system_id integer
*/
public int system_id;
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other == null)||(other.getClass()!= getClass())) {
return false;
}
R_get_universe_systems_system_id othersame = ((R_get_universe_systems_system_id) other);
if (constellation_id!= othersame.constellation_id) {
return false;
}
if ((name!= othersame.name)&&((name == null)||(!name.equals(othersame.name)))) {
return false;
}
if ((planets!= othersame.planets)&&((planets == null)||(!planets.equals(othersame.planets)))) {
return false;
}
if ((position!= othersame.position)&&((position == null)||(!position.equals(othersame.position)))) {
return false;
}
if ((security_class!= othersame.security_class)&&((security_class == null)||(!security_class.equals(othersame.security_class)))) {
return false;
}
if (security_status!= othersame.security_status) {
return false;
}
if (star_id!= othersame.star_id) {
return false;
}
if ((stargates!= othersame.stargates)&&((stargates == null)||(!stargates.equals(othersame.stargates)))) {
return false;
}
if ((stations!= othersame.stations)&&((stations == null)||(!stations.equals(othersame.stations)))) {
return false;
}
if (system_id!= othersame.system_id) {
return false;
}
return true;
}
public int hashCode() {
return (((((((((constellation_id +((name == null)? 0 :name.hashCode()))+((planets == null)? 0 :planets.hashCode()))+((position == null)? 0 :position.hashCode()))+((security_class == null)? 0 :security_class.hashCode()))+ Double.hashCode(security_status))+ star_id)+((stargates == null)? 0 :stargates.hashCode()))+((stations == null)? 0 :stations.hashCode()))+ system_id);
}
}
| gpl-3.0 |
Inux/nebsynch | SW13/src/sw13/executorNegative/WorkerCallable.java | 603 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sw13.executorNegative;
import java.util.concurrent.Callable;
/**
*
* @author Steve Ineichen
*/
public class WorkerCallable implements Callable {
final private Worker worker;
public WorkerCallable(Worker worker) {
this.worker = worker;
}
@Override
public Integer call() throws InterruptedException {
worker.doWork();
return worker.getResult();
}
} | gpl-3.0 |
taky/ray | src/com/gmail/altakey/ray/EnqueueActivity.java | 10120 | package com.gmail.altakey.ray;
import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import android.net.Uri;
import android.content.Intent;
import android.widget.Toast;
import android.util.Log;
import android.net.http.AndroidHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.*;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import java.util.*;
public class EnqueueActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String action = getIntent().getAction();
final Bundle extras = getIntent().getExtras();
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
new EnqueueTaskInvoker((Uri)extras.getParcelable(Intent.EXTRA_STREAM)).invokeOnFriend();
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
for (Parcelable p : extras.getParcelableArrayList(Intent.EXTRA_STREAM)) {
new EnqueueTaskInvoker((Uri)p).invokeOnFriend();
}
}
} else {
finish();
}
}
private class EnqueueTaskInvoker {
private Uri mmForUri;
private List<String> mmOptions = new LinkedList<String>();
public EnqueueTaskInvoker(Uri forUri) {
mmForUri = forUri;
mmOptions.add("(local)");
mmOptions.add("10.0.0.50");
mmOptions.add("10.0.0.52");
mmOptions.add("192.168.1.15");
mmOptions.add("192.168.1.17");
mmOptions.add("Other...");
}
public void invokeOnFriend() {
AlertDialog.Builder builder = new AlertDialog.Builder(EnqueueActivity.this);
builder
.setTitle(R.string.dialog_title_send_to)
.setOnCancelListener(new CancelAction())
.setItems(mmOptions.toArray(new String[0]), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String choice = mmOptions.get(which);
if (choice != null) {
if ("Other...".equals(choice)) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(
R.layout.friend,
(ViewGroup)findViewById(R.id.root));
AlertDialog.Builder builder = new AlertDialog.Builder(EnqueueActivity.this);
EditText field = (EditText)layout.findViewById(R.id.name);
builder
.setTitle(R.string.dialog_title_send_to)
.setView(layout)
.setOnCancelListener(new CancelAction())
.setNegativeButton(android.R.string.cancel, new CancelAction())
.setPositiveButton(android.R.string.ok, new ConfirmAction(field));
dialog.dismiss();
builder.create().show();
} else if ("(local)".equals(choice)) {
dialog.dismiss();
new EnqueueToFriendTask("localhost:8080", mmForUri).execute();
finish();
} else {
dialog.dismiss();
new EnqueueToFriendTask(String.format("%s:8080", choice), mmForUri).execute();
finish();
}
} else {
dialog.dismiss();
}
}
});
builder.create().show();
}
private class CancelAction implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
@Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
finish();
}
}
private class ConfirmAction implements DialogInterface.OnClickListener {
private EditText mmmField;
public ConfirmAction(EditText field) {
mmmField = field;
}
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mmmField.getText().toString();
dialog.dismiss();
new EnqueueToFriendTask(name, mmForUri).execute();
finish();
}
}
}
private class EnqueueToFriendTask extends AsyncTask<Void, Void, Throwable> {
private Uri mmUri;
private String mmFriendAddress;
public EnqueueToFriendTask(String friendAddress, Uri uri) {
mmUri = uri;
mmFriendAddress = friendAddress;
}
@Override
public void onPreExecute() {
Toast.makeText(EnqueueActivity.this, "Sending...", Toast.LENGTH_LONG).show();
}
@Override
public Throwable doInBackground(Void... args) {
File tempFile = null;
try {
tempFile = new Cacher().cache();
new Enqueuer(tempFile).enqueue();
return null;
} catch (IOException e) {
Log.e("EA", "Cannot send to remote playlist", e);
return e;
} finally {
if (tempFile != null) {
tempFile.delete();
}
}
}
@Override
public void onPostExecute(Throwable ret) {
if (ret == null) {
Toast.makeText(EnqueueActivity.this, "Sent to remote playlist.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(EnqueueActivity.this, "Cannot send to remote playlist", Toast.LENGTH_SHORT).show();
}
}
private class Enqueuer {
private AndroidHttpClient mmmHttpClient;
private File mmmBlob;
public Enqueuer(File blob) {
mmmHttpClient = AndroidHttpClient.newInstance(getUserAgent());
mmmBlob = blob;
}
private String getUserAgent() {
return String.format("%s/%s", getString(R.string.app_name), "0.0.1");
}
public void enqueue() throws IOException {
HttpPost req = new HttpPost(String.format("http://%s", mmFriendAddress));
MultipartEntity entity = new MultipartEntity();
entity.addPart("stream", new FileBody(mmmBlob, "application/octet-stream"));
req.setEntity(entity);
int code = mmmHttpClient.execute(req).getStatusLine().getStatusCode();
Log.d("EA", String.format("posted, code=%d", code));
}
}
private class Cacher {
public File cache() throws IOException {
FileChannel src = null;
FileChannel dest = null;
File destFile = null;
try {
destFile = new File(root(), randomName());
src = new FileInputStream(getContentResolver().openFileDescriptor(mmUri, "r").getFileDescriptor()).getChannel();
dest = new FileOutputStream(destFile).getChannel();
dest.transferFrom(src, 0, Integer.MAX_VALUE);
Log.d("MA", String.format("cached %s as %s", mmUri.toString(), destFile.getName()));
return destFile;
} catch (IOException e) {
Log.e("MA", "cannot cache", e);
destFile.delete();
throw e;
} finally {
if (src != null) {
try {
src.close();
} catch (IOException e) {
}
}
if (dest != null) {
try {
dest.close();
} catch (IOException e) {
}
}
}
}
private String randomName() {
byte[] buffer = new byte[32];
new Random().nextBytes(buffer);
StringBuilder sb = new StringBuilder();
try {
for (byte b : MessageDigest.getInstance("MD5").digest(buffer)) {
sb.append(Integer.toHexString(((int)b) & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private File root() {
return getExternalFilesDir(null);
}
}
}
}
| gpl-3.0 |
sergioramossilva/Sistema-Pagamento-RU | src/main/java/br/edu/utfpr/cm/pi/controller/LoginUsuarioServlet.java | 1740 | package br.edu.utfpr.cm.pi.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.edu.utfpr.cm.pi.beans.UsuarioSistema;
import br.edu.utfpr.cm.pi.ldap.LoginLDAP;
@WebServlet(name = "LoginUsuarioServlet", urlPatterns = { "/LoginUsuarioServlet" })
public class LoginUsuarioServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginUsuarioServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LoginLDAP ldap = new LoginLDAP();
String login = request.getParameter("login");
String senha = request.getParameter("senha");
UsuarioSistema usuario = ldap.logarNoLDAP(login, senha);
if (usuario != null) {
HttpSession sessao = request.getSession(true);
sessao.setAttribute("usuario", usuario);
response.sendRedirect("bemvindoUsuario.jsp");
} else {
response.sendRedirect("loginInvalidoUsuario.jsp");
}
}
} | gpl-3.0 |
Gurgy/Cypher | src/main/java/com/github/cypher/gui/root/roomcollection/RoomCollectionView.java | 154 | package com.github.cypher.gui.root.roomcollection;
import com.airhacks.afterburner.views.FXMLView;
public class RoomCollectionView extends FXMLView {
}
| gpl-3.0 |
mini890/2D-Computer-Graphics | src/Aula_4/Carro/RodaAros.java | 818 | package Aula_4.Carro;
import java.awt.Graphics2D;
public class RodaAros extends Roda {
int n;
public RodaAros(int n, int raio, int xi, int yi) {
super(raio, xi, yi, 0);
this.n = n;
}
/*public RodaAros(int xi, int yi) {
super(17, xi, yi, 0);
n = 8;
raio = 17;
}*/
public void draw(Graphics2D g2d) {
double ang_inc = 2 * Math.PI / n;
for (int i = 0; i < n; i++) {
g2d.drawLine(xi, yi, (int) (Math.cos(ang_inicial) * raio + xi), (int) (Math.sin(ang_inicial) * raio + yi));
ang_inicial += ang_inc;
}
g2d.drawOval(xi - raio, yi - raio, raio * 2, raio * 2);
}
public void avanca(int npixel) {
xi -= npixel;
ang_inicial -= Math.toRadians(10);
}
public void recua(int npixel) {
xi += npixel;
ang_inicial += Math.toRadians(10);
}
} | gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/apps/Camera2/tests/src/com/android/camera/stress/CameraLatency.java | 7032 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.stress;
import com.android.camera.CameraActivity;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.Environment;
import android.provider.MediaStore;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
import android.view.KeyEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
* Junit / Instrumentation test case for camera test
*
*/
public class CameraLatency extends ActivityInstrumentationTestCase2 <CameraActivity> {
private String TAG = "CameraLatency";
private static final int TOTAL_NUMBER_OF_IMAGECAPTURE = 20;
private static final long WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN = 4000;
private static final String CAMERA_TEST_OUTPUT_FILE =
Environment.getExternalStorageDirectory().toString() + "/mediaStressOut.txt";
private long mTotalAutoFocusTime;
private long mTotalShutterLag;
private long mTotalShutterToPictureDisplayedTime;
private long mTotalPictureDisplayedToJpegCallbackTime;
private long mTotalJpegCallbackFinishTime;
private long mTotalFirstPreviewTime;
private long mAvgAutoFocusTime;
private long mAvgShutterLag = mTotalShutterLag;
private long mAvgShutterToPictureDisplayedTime;
private long mAvgPictureDisplayedToJpegCallbackTime;
private long mAvgJpegCallbackFinishTime;
private long mAvgFirstPreviewTime;
public CameraLatency() {
super(CameraActivity.class);
}
@Override
protected void setUp() throws Exception {
// Make sure camera starts with still picture capturing mode
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(getInstrumentation().getTargetContext(),
CameraActivity.class);
setActivityIntent(intent);
getActivity();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testImageCapture() {
Log.v(TAG, "start testImageCapture test");
Instrumentation inst = getInstrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
try {
for (int i = 0; i < TOTAL_NUMBER_OF_IMAGECAPTURE; i++) {
Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
//skip the first measurement
if (i != 0) {
CameraActivity c = getActivity();
// if any of the latency var accessor methods return -1 then the
// camera is set to a different module other than PhotoModule so
// skip the shot and try again
if (c.getAutoFocusTime() != -1) {
mTotalAutoFocusTime += c.getAutoFocusTime();
mTotalShutterLag += c.getShutterLag();
mTotalShutterToPictureDisplayedTime +=
c.getShutterToPictureDisplayedTime();
mTotalPictureDisplayedToJpegCallbackTime +=
c.getPictureDisplayedToJpegCallbackTime();
mTotalJpegCallbackFinishTime += c.getJpegCallbackFinishTime();
mTotalFirstPreviewTime += c.getFirstPreviewTime();
}
else {
i--;
continue;
}
}
}
} catch (Exception e) {
Log.v(TAG, "Got exception", e);
}
//ToDO: yslau
//1) Need to get the baseline from the cupcake so that we can add the
//failure condition of the camera latency.
//2) Only count those number with succesful capture. Set the timer to invalid
//before capture and ignore them if the value is invalid
int numberofRun = TOTAL_NUMBER_OF_IMAGECAPTURE - 1;
mAvgAutoFocusTime = mTotalAutoFocusTime / numberofRun;
mAvgShutterLag = mTotalShutterLag / numberofRun;
mAvgShutterToPictureDisplayedTime =
mTotalShutterToPictureDisplayedTime / numberofRun;
mAvgPictureDisplayedToJpegCallbackTime =
mTotalPictureDisplayedToJpegCallbackTime / numberofRun;
mAvgJpegCallbackFinishTime =
mTotalJpegCallbackFinishTime / numberofRun;
mAvgFirstPreviewTime =
mTotalFirstPreviewTime / numberofRun;
try {
FileWriter fstream = null;
fstream = new FileWriter(CAMERA_TEST_OUTPUT_FILE, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Camera Latency : \n");
out.write("Number of loop: " + TOTAL_NUMBER_OF_IMAGECAPTURE + "\n");
out.write("Avg AutoFocus = " + mAvgAutoFocusTime + "\n");
out.write("Avg mShutterLag = " + mAvgShutterLag + "\n");
out.write("Avg mShutterToPictureDisplayedTime = "
+ mAvgShutterToPictureDisplayedTime + "\n");
out.write("Avg mPictureDisplayedToJpegCallbackTime = "
+ mAvgPictureDisplayedToJpegCallbackTime + "\n");
out.write("Avg mJpegCallbackFinishTime = " +
mAvgJpegCallbackFinishTime + "\n");
out.write("Avg FirstPreviewTime = " +
mAvgFirstPreviewTime + "\n");
out.close();
fstream.close();
} catch (Exception e) {
fail("Camera Latency write output to file");
}
Log.v(TAG, "The Image capture wait time = " +
WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
Log.v(TAG, "Avg AutoFocus = " + mAvgAutoFocusTime);
Log.v(TAG, "Avg mShutterLag = " + mAvgShutterLag);
Log.v(TAG, "Avg mShutterToPictureDisplayedTime = "
+ mAvgShutterToPictureDisplayedTime);
Log.v(TAG, "Avg mPictureDisplayedToJpegCallbackTime = "
+ mAvgPictureDisplayedToJpegCallbackTime);
Log.v(TAG, "Avg mJpegCallbackFinishTime = " + mAvgJpegCallbackFinishTime);
Log.v(TAG, "Avg FirstPreviewTime = " + mAvgFirstPreviewTime);
}
}
| gpl-3.0 |
Amagi82/KerbalSpaceApp | src/com/amagi82/kerbalspaceapp/MissionPlanner.java | 17210 | /*
* Kerbal Space App
*
* Copyright (C) 2014 Jim Pekarek (Amagi82)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amagi82.kerbalspaceapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MissionPlanner extends Activity {
StableArrayAdapter mAdapter;
ListView mListView;
BackgroundContainer mBackgroundContainer;
ArrayList<MissionData> missionData = new ArrayList<MissionData>();
HashMap<Long, Integer> mItemIdTopMap = new HashMap<Long, Integer>();
boolean mSwiping = false, mItemPressed = false;
int totalDeltaV;
TextView tvTotalDeltaV;
private static final int SWIPE_DURATION = 250;
private static final int MOVE_DURATION = 150;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission_planner);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
getActionBar().setTitle(R.string.title_activity_mission_planner);
if (savedInstanceState == null) {
// Load saved missionData if available.
try {
FileInputStream inStream = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator + "MissionData");
ObjectInputStream objectInStream = new ObjectInputStream(inStream);
int count = objectInStream.readInt();
for (int i = 0; i < count; i++)
missionData.add((MissionData) objectInStream.readObject());
objectInStream.close();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// if the list is empty, add the default planet
if (missionData.size() == 0) {
missionData = setFirstMissionData();
}
} else {
missionData = savedInstanceState.getParcelableArrayList("key");
}
mBackgroundContainer = (BackgroundContainer) findViewById(R.id.listViewBackground);
mListView = (ListView) findViewById(R.id.list);
tvTotalDeltaV = (TextView) findViewById(R.id.tvTotalDeltaV);
mAdapter = new StableArrayAdapter(this, missionData, mTouchListener);
// add the newDestination button as a footer below the listview
ImageView newDestination = new ImageView(this);
newDestination.setImageResource(R.drawable.ic_plus);
mListView.addFooterView(newDestination);
newDestination.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int possibleIconState = 0; // Lets MissionDestination know which icons it's allowed to use
if (missionData.size() < 1) {
possibleIconState = 1;
}
Intent intent = new Intent(MissionPlanner.this, MissionDestination.class);
intent.putExtra("possibleIconState", possibleIconState);
intent.putExtra("isNewItem", true); // Places the result as a new item in the listview
startActivityForResult(intent, 0);
}
});
mListView.setAdapter(mAdapter);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("key", missionData);
super.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
// This is in onResume so it refreshes deltaV when the user returns from adjusting settings
SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
int mClearanceValue = prefs.getInt("mClearanceValue", 1000);
int mMarginsValues = prefs.getInt("mMarginsValue", 10);
int mInclinationValues = prefs.getInt("mInclinationValue", 30);
float mMarginsValue = (float) mMarginsValues / 100 + 1;
float mInclinationValue = (float) mInclinationValues / 100;
// Update OrbitalMechanics with the new values
OrbitalMechanics.mClearanceValue = mClearanceValue;
OrbitalMechanics.mMarginsValue = mMarginsValue;
OrbitalMechanics.mInclinationValue = mInclinationValue;
refreshDeltaV();
}
// This method calculates the total delta V and displays it at the bottom
private void refreshDeltaV() {
totalDeltaV = 0;
for (int i = 0; i < missionData.size(); i++) {
int takeoffDeltaV = 0, transferDeltaV = 0, landingDeltaV = 0;
if (missionData.get(i).getIconStatus() == 3) {
takeoffDeltaV = OrbitalMechanics.getToOrbit(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(),
missionData.get(i).getOrbitAltitude());
}
if (missionData.get(i).getLanding()) {
landingDeltaV = OrbitalMechanics.getLandingDeltaV(missionData.get(i).getPlanetId(),
missionData.get(i).getTakeoffAltitude(), missionData.get(i).getOrbitAltitude());
}
if (missionData.get(i).getToOrbit() && missionData.get(i).getLanding()) {
takeoffDeltaV = OrbitalMechanics.getToOrbit(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(),
missionData.get(i).getOrbitAltitude());
}
if (i != 0) {
transferDeltaV = OrbitalMechanics.getTransferDeltaV(missionData.get(i - 1).getPlanetId(), missionData.get(i).getPlanetId(),
missionData.get(i - 1).getOrbitAltitude(), missionData.get(i).getOrbitAltitude());
}
totalDeltaV = totalDeltaV + takeoffDeltaV + transferDeltaV + landingDeltaV;
}
String value = NumberFormat.getNumberInstance(Locale.getDefault()).format(totalDeltaV);
tvTotalDeltaV.setText(value + " m/s");
}
// Save missionData on pause
@Override
public void onPause() {
super.onPause();
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "MissionData");
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
ObjectOutputStream objectOutStream = new ObjectOutputStream(outStream);
objectOutStream.writeInt(missionData.size());
for (MissionData r : missionData)
objectOutStream.writeObject(r);
objectOutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Handles touch events to fade/move dragged items as they are swiped out
private final View.OnTouchListener mTouchListener = new View.OnTouchListener() {
float mDownX;
private int mSwipeSlop = -1;
@Override
public boolean onTouch(final View v, MotionEvent event) {
if (mSwipeSlop < 0) {
mSwipeSlop = ViewConfiguration.get(MissionPlanner.this).getScaledTouchSlop();
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mItemPressed) {
// Multi-item swipes not handled
return false;
}
mItemPressed = true;
mDownX = event.getX();
break;
case MotionEvent.ACTION_CANCEL:
v.setAlpha(1);
v.setTranslationX(0);
mItemPressed = false;
break;
case MotionEvent.ACTION_MOVE: {
float x = event.getX() + v.getTranslationX();
float deltaX = x - mDownX;
float deltaXAbs = Math.abs(deltaX);
if (!mSwiping) {
if (deltaXAbs > mSwipeSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
mBackgroundContainer.showBackground(v.getTop(), v.getHeight());
}
}
if (mSwiping) {
v.setTranslationX((x - mDownX));
v.setAlpha(1 - deltaXAbs / v.getWidth());
}
}
break;
case MotionEvent.ACTION_UP: {
// User let go - figure out whether to animate the view out, or back into place
if (mSwiping) {
float x = event.getX() + v.getTranslationX();
float deltaX = x - mDownX;
float deltaXAbs = Math.abs(deltaX);
float fractionCovered = 0;
float endX;
float endAlpha;
final boolean remove;
if (deltaXAbs > v.getWidth() / 4) {
// Greater than a quarter of the width - animate it out
fractionCovered = deltaXAbs / v.getWidth();
endX = deltaX < 0 ? -v.getWidth() : v.getWidth();
endAlpha = 0;
remove = true;
} else {
// Not far enough - animate it back
fractionCovered = 1 - (deltaXAbs / v.getWidth());
endX = 0;
endAlpha = 1;
remove = false;
}
// Animate position and alpha of swiped item
long duration = (int) ((1 - fractionCovered) * SWIPE_DURATION);
mListView.setEnabled(false);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.animate().setDuration(duration).alpha(endAlpha).translationX(endX).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Restore animated values
v.setAlpha(1);
v.setTranslationX(0);
if (remove) {
animateRemoval(mListView, v);
} else {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
}
});
} else {
v.animate().setDuration(duration).alpha(endAlpha).translationX(endX).withEndAction(new Runnable() {
@Override
public void run() {
// Restore animated values
v.setAlpha(1);
v.setTranslationX(0);
if (remove) {
animateRemoval(mListView, v);
} else {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
}
});
}
mItemPressed = false;
break;
}
}
// Item was clicked - allow user to edit list item
mItemPressed = false;
int position = mListView.getPositionForView(v);
int possibleIconState = 0;
if (position == 0) {
possibleIconState = 1;
}
Intent intent = new Intent(MissionPlanner.this, MissionDestination.class);
intent.putExtra("listItem", (Parcelable) missionData.get(position));
intent.putExtra("possibleIconState", possibleIconState);
intent.putExtra("isNewItem", false);
startActivityForResult(intent, position);
break;
default:
return false;
}
return true;
}
};
/**
* This method animates all other views in the ListView container (not including ignoreView) into their final positions. It is called
* after ignoreView has been removed from the adapter, but before layout has been run. The approach here is to figure out where
* everything is now, then allow layout to run, then figure out where everything is after layout, and then to run animations between all
* of those start/end positions.
*/
private void animateRemoval(final ListView listview, View viewToRemove) {
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
View child = listview.getChildAt(i);
if (child != viewToRemove) {
int position = firstVisiblePosition + i;
long itemId = mAdapter.getItemId(position);
mItemIdTopMap.put(itemId, child.getTop());
}
}
// Delete the item from the adapter
int position = mListView.getPositionForView(viewToRemove);
mAdapter.remove(mAdapter.getItem(position));
mAdapter.notifyDataSetChanged();
refreshDeltaV();
final ViewTreeObserver observer = listview.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
observer.removeOnPreDrawListener(this);
boolean firstAnimation = true;
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
final View child = listview.getChildAt(i);
int position = firstVisiblePosition + i;
long itemId = mAdapter.getItemId(position);
Integer startTop = mItemIdTopMap.get(itemId);
int top = child.getTop();
if (startTop != null) {
if (startTop != top) {
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
child.animate().setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
} else {
child.animate().withEndAction(new Runnable() {
@Override
public void run() {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
firstAnimation = false;
}
}
}
} else {
// Animate new views along with the others. The catch is that they did not
// exist in the start state, so we must calculate their starting position
// based on neighboring views.
int childHeight = child.getHeight() + listview.getDividerHeight();
startTop = top + (i > 0 ? childHeight : -childHeight);
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
child.animate().setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
} else {
child.animate().withEndAction(new Runnable() {
@Override
public void run() {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
firstAnimation = false;
}
}
}
}
mItemIdTopMap.clear();
return true;
}
});
}
// Inflate the menu; this adds items to the action bar if it is present.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mission_planner, menu);
return true;
}
// Action bar functionality
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
break;
case R.id.action_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.action_delete:
missionData.clear();
setFirstMissionData();
mAdapter.notifyDataSetChanged();
refreshDeltaV();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (Settings.language == null) {
Settings.language = Locale.getDefault();
} else if (!config.locale.equals(Settings.language) && !Locale.getDefault().equals(Settings.language)) {
config.locale = Settings.language;
Locale.setDefault(config.locale);
getBaseContext().getResources().updateConfiguration(config, getResources().getDisplayMetrics());
recreate();
}
}
// Grab the parcel from MissionDestination, and either add a new listview item or update an existing one
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
MissionData result = data.getParcelableExtra("returnItem");
if (data.getBooleanExtra("isNewItem", true)) {
missionData.add(result);
} else {
missionData.set(requestCode, result);
}
mAdapter.notifyDataSetChanged();
refreshDeltaV();
}
if (resultCode == RESULT_CANCELED) {
}
}
// Adds Kerbin as the default departure planet
private ArrayList<MissionData> setFirstMissionData() {
MissionData a = new MissionData(4, false, 0, true, 100000, 3);
missionData.add(a);
return missionData;
}
} | gpl-3.0 |
Adaptivity/BetterLoadingScreen | src/main/java/alexiil/mods/load/json/subtypes/JsonImagePanorama.java | 1195 | package alexiil.mods.load.json.subtypes;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import net.minecraft.util.ResourceLocation;
import alexiil.mods.load.baked.func.BakedFunction;
import alexiil.mods.load.baked.func.FunctionBaker;
import alexiil.mods.load.baked.insn.BakedInstruction;
import alexiil.mods.load.baked.render.BakedPanoramaRender;
import alexiil.mods.load.json.JsonImage;
public class JsonImagePanorama extends JsonImage {
public JsonImagePanorama(ResourceLocation resourceLocation, String image) {
super("", image, null, null, null, null, null, null, null);
this.resourceLocation = resourceLocation;
}
@Override
protected JsonImagePanorama actuallyConsolidate() {
return this;
}
@Override
protected BakedPanoramaRender actuallyBake(Map<String, BakedFunction<?>> functions) {
BakedFunction<Double> angle = FunctionBaker.bakeFunctionDouble("seconds * 40", functions);
return new BakedPanoramaRender(angle, image);
}
@Override
public List<BakedInstruction> bakeInstructions(Map<String, BakedFunction<?>> functions) {
return Collections.emptyList();
}
}
| gpl-3.0 |
waikato-datamining/adams-base | adams-core/src/test/java/adams/flow/sink/RemoteCommandWriterTest.java | 4366 | /*
* 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/>.
*/
/*
* RemoteCommandWriterTest.java
* Copyright (C) 2016 University of Waikato, Hamilton, New Zealand
*/
package adams.flow.sink;
import adams.core.io.PlaceholderFile;
import adams.core.option.AbstractArgumentOption;
import adams.env.Environment;
import adams.flow.AbstractFlowTest;
import adams.flow.control.Flow;
import adams.flow.core.AbstractActor;
import adams.flow.core.Actor;
import adams.flow.execution.NullListener;
import adams.flow.source.NewRemoteCommand;
import adams.scripting.command.basic.SystemInfo;
import adams.scripting.connection.DefaultConnection;
import adams.test.TmpFile;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.util.ArrayList;
import java.util.List;
/**
* Test for RemoteCommandWriter actor.
*
* @author fracpete
* @author adams.core.option.FlowJUnitTestProducer (code generator)
* @version $Revision$
*/
public class RemoteCommandWriterTest
extends AbstractFlowTest {
/**
* Initializes the test.
*
* @param name the name of the test
*/
public RemoteCommandWriterTest(String name) {
super(name);
}
/**
* Called by JUnit before each test method.
*
* @throws Exception if an error occurs.
*/
protected void setUp() throws Exception {
super.setUp();
m_TestHelper.deleteFileFromTmp("dumpfile.txt");
}
/**
* Called by JUnit after each test method.
*
* @throws Exception if tear-down fails
*/
protected void tearDown() throws Exception {
m_TestHelper.deleteFileFromTmp("dumpfile.txt");
super.tearDown();
}
/**
* Performs a regression test, comparing against previously generated output.
*/
public void testRegression() {
performRegressionTest(
new TmpFile[]{
new TmpFile("dumpfile.txt")
});
}
/**
*
* Returns a test suite.
*
* @return the test suite
*/
public static Test suite() {
return new TestSuite(RemoteCommandWriterTest.class);
}
/**
* Used to create an instance of a specific actor.
*
* @return a suitably configured <code>AbstractActor</code> value
*/
public AbstractActor getActor() {
AbstractArgumentOption argOption;
Flow flow = new Flow();
try {
List<Actor> actors = new ArrayList<Actor>();
// Flow.NewRemoteCommand
NewRemoteCommand newremotecommand = new NewRemoteCommand();
SystemInfo systeminfo = new SystemInfo();
DefaultConnection defaultconnection = new DefaultConnection();
systeminfo.setResponseConnection(defaultconnection);
newremotecommand.setCommand(systeminfo);
actors.add(newremotecommand);
// Flow.RemoteCommandWriter
RemoteCommandWriter remotecommandwriter = new RemoteCommandWriter();
argOption = (AbstractArgumentOption) remotecommandwriter.getOptionManager().findByProperty("outputFile");
remotecommandwriter.setOutputFile((PlaceholderFile) argOption.valueOf("${TMP}/dumpfile.txt"));
actors.add(remotecommandwriter);
flow.setActors(actors.toArray(new Actor[0]));
NullListener nulllistener = new NullListener();
flow.setFlowExecutionListener(nulllistener);
}
catch (Exception e) {
fail("Failed to set up actor: " + e);
}
return flow;
}
/**
* Returns the ignored line indices to use in the regression test.
*
* @return the setups
*/
@Override
protected int[] getRegressionIgnoredLineIndices() {
return new int[]{0};
}
/**
* Runs the test from commandline.
*
* @param args ignored
*/
public static void main(String[] args) {
Environment.setEnvironmentClass(adams.env.Environment.class);
runTest(suite());
}
}
| gpl-3.0 |
rdnz/UnaGo | unagoclient/partner/PartnerSendQuestion.java | 1804 | package unagoclient.partner;
import unagoclient.Global;
import unagoclient.gui.*;
import javax.swing.*;
/**
* Displays a send dialog, when the partner presses "Send" in the GoFrame. The
* message is appended to the PartnerFrame.
*/
public class PartnerSendQuestion extends CloseDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
PartnerGoFrame F;
JTextField T;
PartnerFrame PF;
public PartnerSendQuestion(PartnerGoFrame f, PartnerFrame pf) {
super(f, Global.resourceString("Send"), false);
this.F = f;
this.PF = pf;
this.add("North", new MyLabel(Global.resourceString("Message_")));
this.add("Center", this.T = new GrayTextField(25));
final JPanel p = new MyPanel();
p.add(new ButtonAction(this, Global.resourceString("Say")));
p.add(new ButtonAction(this, Global.resourceString("Cancel")));
this.add("South", new Panel3D(p));
Global.setpacked(this, "partnersend", 200, 150);
this.validate();
this.setVisible(true);
}
@Override
public void doAction(String o) {
Global.notewindow(this, "partnersend");
if (Global.resourceString("Say").equals(o)) {
if (!this.T.getText().equals("")) {
this.PF.out(this.T.getText());
this.F.addComment(Global.resourceString("Said__")
+ this.T.getText());
}
this.setVisible(false);
this.dispose();
} else if (Global.resourceString(Global.resourceString("Cancel"))
.equals(o)) {
this.setVisible(false);
this.dispose();
} else {
super.doAction(o);
}
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java | 278 | package com.baeldung.reflect;
public class Person {
private String fullName;
public Person(String fullName) {
this.fullName = fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
}
| gpl-3.0 |
StarTux/LinkPortal | src/main/java/com/winthier/linkportal/LinkPortalPlugin.java | 997 | package com.winthier.linkportal;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import lombok.Getter;
import org.bukkit.plugin.java.JavaPlugin;
@Getter
public final class LinkPortalPlugin extends JavaPlugin {
private final LinkPortalListener listener = new LinkPortalListener(this);
private final LinkPortals portals = new LinkPortals(this);
private boolean debugMode;
Set<UUID> serverPortal = new HashSet<>();
@Override
public void onEnable() {
saveDefaultConfig();
loadConf();
getServer().getPluginManager().registerEvents(listener, this);
getCommand("linkportal").setExecutor(new LinkPortalCommand(this));
getServer().getScheduler().runTaskTimer(this, listener::tick, 1L, 1L);
}
void loadConf() {
reloadConfig();
this.debugMode = getConfig().getBoolean("debug");
if (this.debugMode) {
getLogger().info("Debug mode enabled in config.yml!");
}
}
}
| gpl-3.0 |
aleatorio12/ProVentasConnector | jasperreports-6.2.1-project/jasperreports-6.2.1/demo/samples/csvdatasource/src/CsvDataSourceApp.java | 15435 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.data.JRCsvDataSource;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.oasis.JROdsExporter;
import net.sf.jasperreports.engine.export.oasis.JROdtExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.AbstractSampleApp;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleOdsReportConfiguration;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
*/
public class CsvDataSourceApp extends AbstractSampleApp
{
/**
*
*/
public static void main(String[] args)
{
main(new CsvDataSourceApp(), args);
}
/**
*
*/
public void test() throws JRException
{
fill();
pdf();
xmlEmbed();
xml();
html();
rtf();
xls();
jxl();
csv();
odt();
ods();
docx();
xlsx();
pptx();
xhtml();
}
/**
*
*/
public void fill() throws JRException
{
long start = System.currentTimeMillis();
// data source filling
{
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ReportTitle", "Address Report");
parameters.put("DataFile", "CsvDataSource.txt - CSV data source");
Set<String> states = new HashSet<String>();
states.add("Active");
states.add("Trial");
parameters.put("IncludedStates", states);
String[] columnNames = new String[]{"city", "id", "name", "address", "state"};
JRCsvDataSource dataSource = new JRCsvDataSource(JRLoader.getLocationInputStream("data/CsvDataSource.txt"));
dataSource.setRecordDelimiter("\r\n");
// dataSource.setUseFirstRowAsHeader(true);
dataSource.setColumnNames(columnNames);
JasperFillManager.fillReportToFile("build/reports/CsvDataSourceReport.jasper", parameters, dataSource);
System.err.println("Report : CsvDataSourceReport.jasper. Filling time : " + (System.currentTimeMillis() - start));
}
// query executer filling
{
start = System.currentTimeMillis();
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ReportTitle", "Address Report");
parameters.put("DataFile", "CsvDataSource.txt - CSV query executer");
Set<String> states = new HashSet<String>();
states.add("Active");
states.add("Trial");
parameters.put("IncludedStates", states);
JasperFillManager.fillReportToFile("build/reports/CsvQueryExecuterReport.jasper", parameters);
System.err.println("Report : CsvQueryExecuterReport.jasper. Filling time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void print() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
File reportFile = files[i];
long start = System.currentTimeMillis();
JasperPrintManager.printReport(reportFile.getAbsolutePath(), true);
System.err.println("Report : " + reportFile + ". Printing time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void pdf() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
File reportFile = files[i];
long start = System.currentTimeMillis();
JasperExportManager.exportReportToPdfFile(reportFile.getAbsolutePath());
System.err.println("Report : " + reportFile + ". PDF creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void xml() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
File reportFile = files[i];
long start = System.currentTimeMillis();
JasperExportManager.exportReportToXmlFile(reportFile.getAbsolutePath(), false);
System.err.println("Report : " + reportFile + ". XML creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void xmlEmbed() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
File reportFile = files[i];
long start = System.currentTimeMillis();
JasperExportManager.exportReportToXmlFile(reportFile.getAbsolutePath(), true);
System.err.println("Report : " + reportFile + ". XML creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void html() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
File reportFile = files[i];
long start = System.currentTimeMillis();
JasperExportManager.exportReportToHtmlFile(reportFile.getAbsolutePath());
System.err.println("Report : " + reportFile + ". HTML creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void rtf() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".rtf");
JRRtfExporter exporter = new JRRtfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(destFile));
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". RTF creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void xls() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".xls");
JRXlsExporter exporter = new JRXlsExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
configuration.setOnePagePerSheet(false);
exporter.setConfiguration(configuration);
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". XLS creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
@SuppressWarnings("deprecation")
public void jxl() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".jxl.xls");
net.sf.jasperreports.engine.export.JExcelApiExporter exporter =
new net.sf.jasperreports.engine.export.JExcelApiExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
net.sf.jasperreports.export.SimpleJxlReportConfiguration configuration =
new net.sf.jasperreports.export.SimpleJxlReportConfiguration();
configuration.setOnePagePerSheet(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". XLS creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void csv() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".csv");
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(destFile));
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". CSV creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void odt() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".odt");
JROdtExporter exporter = new JROdtExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". ODT creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void ods() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".ods");
JROdsExporter exporter = new JROdsExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
SimpleOdsReportConfiguration configuration = new SimpleOdsReportConfiguration();
configuration.setOnePagePerSheet(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". ODS creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void docx() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".docx");
JRDocxExporter exporter = new JRDocxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". DOCX creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void xlsx() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".xlsx");
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
configuration.setOnePagePerSheet(false);
exporter.setConfiguration(configuration);
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". XLSX creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
public void pptx() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".pptx");
JRPptxExporter exporter = new JRPptxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". PPTX creation time : " + (System.currentTimeMillis() - start));
}
}
/**
*
*/
@SuppressWarnings("deprecation")
public void xhtml() throws JRException
{
File[] files = getFiles(new File("build/reports"), "jrprint");
for(int i = 0; i < files.length; i++)
{
long start = System.currentTimeMillis();
File sourceFile = files[i];
JasperPrint jasperPrint = (JasperPrint)JRLoader.loadObject(sourceFile);
File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".x.html");
net.sf.jasperreports.engine.export.JRXhtmlExporter exporter =
new net.sf.jasperreports.engine.export.JRXhtmlExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleHtmlExporterOutput(destFile));
exporter.exportReport();
System.err.println("Report : " + sourceFile + ". XHTML creation time : " + (System.currentTimeMillis() - start));
}
}
}
| gpl-3.0 |
matthiasjordan/piRSS | src/de/codefu/android/rss/updateservice/ServiceComm.java | 8607 | /**
* Copyright (C) 2011 Matthias Jordan <matthias.jordan@googlemail.com>
*
* This file is part of piRSS.
*
* piRSS 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.
*
* piRSS 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 piRSS. If not, see <http://www.gnu.org/licenses/>.
*/
package de.codefu.android.rss.updateservice;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import de.codefu.android.rss.CursorChangedReceiver;
import de.codefu.android.rss.db.ItemProvider;
/**
* Helper that defines the communication between the Activities and Services.
* <p>
* One important thing covered here are insert intents. An insert intent is an
* intent whose receiver is the {@link InsertService} and that communicates that
* some RSS feed data should be inserted into the database. This intent has two
* different forms:
* <ul>
* <li>One uses the {@link #CONTENT}</li> extra whose value is the data that was
* downloaded from the RSS feed. </li>
* <li>The other form uses the {@link #CONTENT_REF} extra whose value is the ID
* of a row in an auxiliary database table that has the data that was downloaded
* from the RSS feed.</li>
* </ul>
* The reason for this intent having two different kinds of behavior is that
* normally passing the RSS feed data directly is better in terms of CPU cycles.
* But an intent is passed using RPC and for RPC data there is a maximum size.
* So whenever feed data is larger than that maximum size {@link ServiceComm}
* stores it in the database and passes the ID of that database entry using the
* {@link #CONTENT_REF} extra.
*
* @author mj
*/
public class ServiceComm {
/**
* The key for the extra hat has the ID of the feed whose data is attached
* or referenced.
*/
public static final String FEED_ID = "feedid";
/**
* The key for the extra that has the RSS feed data.
*/
private static final String CONTENT = "content";
/**
* The key for the extra that has the ID of the row in the auxiliary table
* where the RSS feed data is stored.
*/
private static final String CONTENT_REF = "contentid";
/**
* Wrapper for the information extracted from the insert intent.
*/
public static class IntentContent {
/**
* The data to insert.
*/
public String content;
/**
* The ID of the feed for which to insert the data.
*/
public long feedId;
}
/**
* The maximum size of data that can be stored in an intent.
*/
// TODO: Get correct max size
private static final int MAX_RPC_SIZE = 50 * 1024;
/**
* Name of a broadcast that is sent when polling starts.
*/
public static final String POLLING_STARTED = "pollingstarted";
/**
* Name of a broadcast that is sent when there are problems during polling.
*/
public static final String POLLING_PROBLEM = "pollingproblem";
/**
* Creates an insert intent.
* <p>
* If the data given is too large for the RPC system (larger than
* {@link #MAX_RPC_SIZE}) the data is stored in a database and the ID of
* that data in the database is stored in the intent. Otherwise the data
* itself is stored in the intent.
*
* @param c
* the context to create the intent for
* @param feedId
* the ID of the feed whose data is in body
* @param body
* the data of the RSS feed
* @return an intent object ready for sending
*/
public static Intent createInsertIntent(Context c, long feedId, String body) {
final Intent i = new Intent(c, InsertService.class);
if (body.length() > MAX_RPC_SIZE) {
final Uri uri = ItemProvider.CONTENT_URI_AUX;
final ContentValues cv = new ContentValues();
cv.put("content", body);
final Uri id = c.getContentResolver().insert(uri, cv);
i.putExtra(CONTENT_REF, id);
}
else {
i.putExtra(CONTENT, body);
}
i.putExtra(FEED_ID, feedId);
Log.d("ServComm", "Created " + i);
return i;
}
/**
* Takes an insert intent created with
* {@link #createInsertIntent(Context, long, String)} and retrieves the data
* in it.
* <p>
* The handling of the data in the intent (reference or directly attached
* data) is totally transparent. The caller also does not have to care about
* the maintenance of the auxiliary table.
*
* @param c
* the content to use for a possible database access
* @param intent
* the intent to read from
* @return the object with the data and feed ID read from the intent.
*/
public static IntentContent getInsertContent(Context c, Intent intent) {
final IntentContent ic = new IntentContent();
final Bundle extras = intent.getExtras();
final Object contentRefO = extras.get(CONTENT_REF);
ic.feedId = extras.getLong(FEED_ID);
if (contentRefO != null) {
if (contentRefO instanceof Uri) {
final Uri contentRef = (Uri) contentRefO;
final Cursor cursor = c.getContentResolver().query(contentRef, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
ic.content = cursor.getString(cursor.getColumnIndex(ItemProvider.AUX_COL_CONTENT));
}
cursor.close();
}
c.getContentResolver().delete(contentRef, null, null);
}
Log.i("ServComm", "Read intent for feed " + ic.feedId + " from aux table");
}
else {
ic.content = extras.getString(CONTENT);
Log.i("ServComm", "Read intent for feed " + ic.feedId);
}
return ic;
}
private static void sendBroadcast(Context context, String action) {
final Intent intent = new Intent(action);
intent.setPackage(CursorChangedReceiver.PACKAGE_NAME);
context.sendBroadcast(intent);
}
/**
* Sends a broadcast to announce that the data in the DB has changed.
*
* @param context
* the content to use for sending the intent
*/
public static void sendDataChangedBroadcast(Context context) {
sendBroadcast(context, CursorChangedReceiver.DATA_CHANGED);
}
/**
* Sends a broadcast to announce that polling has stated.
*
* @param context
* the content to use for sending the intent
*/
public static void sendPollingStartedBroadcast(Context context) {
sendBroadcast(context, POLLING_STARTED);
}
/**
* Sends a broadcast to announce that there was a problem during the
* download for a given feed.
*
* @param context
* the content to use for sending the intent
* @param feedId
* the ID of the feed that was attempted to poll
*/
public static void sendPollingProblemBroadcast(Context context, long feedId) {
final Intent intent = new Intent(POLLING_PROBLEM);
intent.setPackage(CursorChangedReceiver.PACKAGE_NAME);
intent.putExtra(FEED_ID, feedId);
context.sendBroadcast(intent);
}
public static void sendPollIntent(Context context, long feedId) {
final Intent i = new Intent(context, UpdateService.class);
i.putExtra(ServiceComm.FEED_ID, feedId);
context.startService(i);
}
/**
* Sends an intent to the {@link AutoPollService} to trigger polling the
* feeds for which automatic polling is configured.
*
* @param context
* the context to use for sending the intent
*/
public static void sendAutoPollIntent(Context context) {
final Intent i = new Intent(context, AutoPollService.class);
context.startService(i);
}
}
| gpl-3.0 |
wachsmuth/freeWarOnTerror | src/freeWarOnTerror/cards/IEDs.java | 1521 | /*
* Copyright (C) 2014 Emil
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package freeWarOnTerror.cards;
import static freeWarOnTerror.Game.getCurrentPlayer;
import static freeWarOnTerror.Game.getMuslimCountries;
import static freeWarOnTerror.Game.getUS;
import freeWarOnTerror.MuslimCountry;
import freeWarOnTerror.abClasses.Card;
import freeWarOnTerror.helpers.CardLookup;
/**
*
* @author Emil
*/
public class IEDs extends Card {
public IEDs(){
super(CardLookup.IEDS);
}
@Override
public Boolean getPlayable(){
for (MuslimCountry c : getMuslimCountries()){
if (c.getRegimeChange() > 0 && c.hasCells()){
return true;
}
}
return false;
}
@Override
public void playEvent(){
getCurrentPlayer().discard(getUS().getRandomCard());
}
}
| gpl-3.0 |
AnDwHaT5/PixelUtilities | src/main/java/com/pixelutilitys/commands/PokecheckmeCommand.java | 1217 | package com.pixelutilitys.commands;
import com.pixelmonmod.pixelmon.Pixelmon;
import com.pixelmonmod.pixelmon.enums.EnumGui;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
public class PokecheckmeCommand extends CommandBase {
@Override
public String getCommandName() {
return "pokecheckme";
}
@Override
public int getRequiredPermissionLevel() {
return 2;
}
@Override
public String getCommandUsage(ICommandSender icommandsender) {
return "/pokecheckme";
}
@Override
public void processCommand(ICommandSender sender, String[] astring) {
// TODO Auto-generated method stub
EntityPlayer player = (EntityPlayer) sender;
player.openGui(Pixelmon.instance, EnumGui.PC.getIndex(), null, 0, 0, 0);
ChatComponentTranslation success = new ChatComponentTranslation("You have successfuly opened your pc files!");
sender.addChatMessage(success);
}
@Override
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}
}
| gpl-3.0 |
IntellectualSites/PlotSquared | Core/src/main/java/com/plotsquared/core/events/PlotChangeOwnerEvent.java | 3957 | /*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2014 - 2022 IntellectualSites
*
* 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 <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.events;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotId;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public class PlotChangeOwnerEvent extends PlotEvent implements CancellablePlotEvent {
private final PlotPlayer<?> initiator;
@Nullable
private final UUID oldOwner;
private final boolean hasOldOwner;
@Nullable
private UUID newOwner;
private Result eventResult;
/**
* PlotChangeOwnerEvent: Called when a plot's owner is change.
*
* @param initiator The player attempting to set the plot's owner
* @param plot The plot having its owner changed
* @param oldOwner The old owner of the plot or null
* @param newOwner The new owner of the plot or null
* @param hasOldOwner If the plot has an old owner
*/
public PlotChangeOwnerEvent(
PlotPlayer<?> initiator, Plot plot, @Nullable UUID oldOwner,
@Nullable UUID newOwner, boolean hasOldOwner
) {
super(plot);
this.initiator = initiator;
this.newOwner = newOwner;
this.oldOwner = oldOwner;
this.hasOldOwner = hasOldOwner;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
/**
* Get the change-owner initiator
*
* @return Player
*/
public PlotPlayer<?> getInitiator() {
return this.initiator;
}
/**
* Get the old owner of the plot. Null if not exists.
*
* @return UUID
*/
public @Nullable UUID getOldOwner() {
return this.oldOwner;
}
/**
* Get the new owner of the plot
*
* @return UUID
*/
public @Nullable UUID getNewOwner() {
return this.newOwner;
}
/**
* Set the new owner of the plot. Null for no owner.
*
* @param newOwner the new owner or null
*/
public void setNewOwner(@Nullable UUID newOwner) {
this.newOwner = newOwner;
}
/**
* Get if the plot had an old owner
*
* @return boolean
*/
public boolean hasOldOwner() {
return this.hasOldOwner;
}
@Override
public Result getEventResult() {
return eventResult;
}
@Override
public void setEventResult(Result e) {
this.eventResult = e;
}
}
| gpl-3.0 |
tobiasschuelke/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/SettingsKeyserverFragment.java | 13816 | /*
* Copyright (C) 2012-2015 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2015 Adithya Abraham Philip <adithyaphilip@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.ui;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.ui.dialog.AddEditKeyserverDialogFragment;
import org.sufficientlysecure.keychain.ui.util.FormattingUtils;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.recyclerview.ItemTouchHelperAdapter;
import org.sufficientlysecure.keychain.ui.util.recyclerview.ItemTouchHelperDragCallback;
import org.sufficientlysecure.keychain.ui.util.recyclerview.ItemTouchHelperViewHolder;
import org.sufficientlysecure.keychain.ui.util.recyclerview.RecyclerItemClickListener;
import org.sufficientlysecure.keychain.keyimport.ParcelableHkpKeyserver;
import org.sufficientlysecure.keychain.util.Preferences;
import java.util.ArrayList;
import java.util.Collections;
public class SettingsKeyserverFragment extends Fragment implements RecyclerItemClickListener.OnItemClickListener {
private static final String ARG_KEYSERVER_ARRAY = "arg_keyserver_array";
private ItemTouchHelper mItemTouchHelper;
private ArrayList<ParcelableHkpKeyserver> mKeyservers;
private KeyserverListAdapter mAdapter;
public static SettingsKeyserverFragment newInstance(ArrayList<ParcelableHkpKeyserver> keyservers) {
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_KEYSERVER_ARRAY, keyservers);
SettingsKeyserverFragment fragment = new SettingsKeyserverFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.settings_keyserver_fragment, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mKeyservers = getArguments().getParcelableArrayList(ARG_KEYSERVER_ARRAY);
mAdapter = new KeyserverListAdapter(mKeyservers);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.keyserver_recycler_view);
// recyclerView.setHasFixedSize(true); // the size of the first item changes
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
ItemTouchHelper.Callback callback = new ItemTouchHelperDragCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
// for clicks
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this));
// can't use item decoration because it doesn't move with drag and drop
// recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.keyserver_pref_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add_keyserver:
startAddKeyserverDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startAddKeyserverDialog() {
// keyserver and position have no meaning
startEditKeyserverDialog(AddEditKeyserverDialogFragment.DialogAction.ADD, null, -1);
}
private void startEditKeyserverDialog(AddEditKeyserverDialogFragment.DialogAction action,
ParcelableHkpKeyserver keyserver, final int position) {
Handler returnHandler = new Handler() {
@Override
public void handleMessage(Message message) {
Bundle data = message.getData();
switch (message.what) {
case AddEditKeyserverDialogFragment.MESSAGE_OKAY: {
boolean deleted =
data.getBoolean(AddEditKeyserverDialogFragment.MESSAGE_KEYSERVER_DELETED
, false);
if (deleted) {
Notify.create(getActivity(),
getActivity().getString(
R.string.keyserver_preference_deleted, mKeyservers.get(position)),
Notify.Style.OK)
.show();
deleteKeyserver(position);
return;
}
boolean verified =
data.getBoolean(AddEditKeyserverDialogFragment.MESSAGE_VERIFIED);
if (verified) {
Notify.create(getActivity(),
R.string.add_keyserver_connection_verified, Notify.Style.OK).show();
} else {
Notify.create(getActivity(),
R.string.add_keyserver_without_verification,
Notify.Style.WARN).show();
}
ParcelableHkpKeyserver keyserver = data.getParcelable(
AddEditKeyserverDialogFragment.MESSAGE_KEYSERVER);
AddEditKeyserverDialogFragment.DialogAction dialogAction
= (AddEditKeyserverDialogFragment.DialogAction) data.getSerializable(
AddEditKeyserverDialogFragment.MESSAGE_DIALOG_ACTION);
switch (dialogAction) {
case ADD:
addKeyserver(keyserver);
break;
case EDIT:
editKeyserver(keyserver, position);
break;
}
break;
}
}
}
};
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(returnHandler);
AddEditKeyserverDialogFragment dialogFragment = AddEditKeyserverDialogFragment
.newInstance(messenger, action, keyserver, position);
dialogFragment.show(getFragmentManager(), "addKeyserverDialog");
}
private void addKeyserver(ParcelableHkpKeyserver keyserver) {
mKeyservers.add(keyserver);
mAdapter.notifyItemInserted(mKeyservers.size() - 1);
saveKeyserverList();
}
private void editKeyserver(ParcelableHkpKeyserver newKeyserver, int position) {
mKeyservers.set(position, newKeyserver);
mAdapter.notifyItemChanged(position);
saveKeyserverList();
}
private void deleteKeyserver(int position) {
if (mKeyservers.size() == 1) {
Notify.create(getActivity(), R.string.keyserver_preference_cannot_delete_last,
Notify.Style.ERROR).show();
return;
}
mKeyservers.remove(position);
// we use this
mAdapter.notifyItemRemoved(position);
if (position == 0 && mKeyservers.size() > 0) {
// if we deleted the first item, we need the adapter to redraw the new first item
mAdapter.notifyItemChanged(0);
}
saveKeyserverList();
}
private void saveKeyserverList() {
Preferences.getPreferences(getActivity()).setKeyServers(mKeyservers);
}
@Override
public void onItemClick(View view, int position) {
startEditKeyserverDialog(AddEditKeyserverDialogFragment.DialogAction.EDIT,
mKeyservers.get(position), position);
}
public class KeyserverListAdapter extends RecyclerView.Adapter<KeyserverListAdapter.ViewHolder>
implements ItemTouchHelperAdapter {
private final ArrayList<ParcelableHkpKeyserver> mKeyservers;
public KeyserverListAdapter(ArrayList<ParcelableHkpKeyserver> keyservers) {
mKeyservers = keyservers;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.settings_keyserver_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.keyserverUrl.setText(mKeyservers.get(position).getUrl());
// Start a drag whenever the handle view it touched
holder.dragHandleView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mItemTouchHelper.startDrag(holder);
}
return false;
}
});
selectUnselectKeyserver(holder, position);
}
private void selectUnselectKeyserver(ViewHolder holder, int position) {
if (position == 0) {
holder.showAsSelectedKeyserver();
} else {
holder.showAsUnselectedKeyserver();
}
}
@Override
public void onItemMove(RecyclerView.ViewHolder source, RecyclerView.ViewHolder target,
int fromPosition, int toPosition) {
Collections.swap(mKeyservers, fromPosition, toPosition);
saveKeyserverList();
selectUnselectKeyserver((ViewHolder) target, fromPosition);
// we don't want source to change color while dragging, therefore we just set
// isSelectedKeyserver instead of selectUnselectKeyserver
((ViewHolder) source).isSelectedKeyserver = toPosition == 0;
notifyItemMoved(fromPosition, toPosition);
}
@Override
public int getItemCount() {
return mKeyservers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
public final ViewGroup outerLayout;
public final TextView selectedServerLabel;
public final TextView keyserverUrl;
public final ImageView dragHandleView;
private boolean isSelectedKeyserver = false;
public ViewHolder(View itemView) {
super(itemView);
outerLayout = (ViewGroup) itemView.findViewById(R.id.outer_layout);
selectedServerLabel = (TextView) itemView.findViewById(
R.id.selected_keyserver_title);
keyserverUrl = (TextView) itemView.findViewById(R.id.keyserver_tv);
dragHandleView = (ImageView) itemView.findViewById(R.id.drag_handle);
itemView.setClickable(true);
}
public void showAsSelectedKeyserver() {
isSelectedKeyserver = true;
selectedServerLabel.setVisibility(View.VISIBLE);
outerLayout.setBackgroundColor(FormattingUtils.getColorFromAttr(getContext(), R.attr.colorPrimaryDark));
}
public void showAsUnselectedKeyserver() {
isSelectedKeyserver = false;
selectedServerLabel.setVisibility(View.GONE);
outerLayout.setBackgroundColor(0);
}
@Override
public void onItemSelected() {
selectedServerLabel.setVisibility(View.GONE);
itemView.setBackgroundColor(FormattingUtils.getColorFromAttr(getContext(), R.attr.colorBrightToolbar));
}
@Override
public void onItemClear() {
if (isSelectedKeyserver) {
showAsSelectedKeyserver();
} else {
showAsUnselectedKeyserver();
}
}
}
}
}
| gpl-3.0 |
PhantomBot/PhantomBot | source/tv/phantombot/event/discord/channel/DiscordChannelPartEvent.java | 1025 | /*
* Copyright (C) 2016-2022 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tv.phantombot.event.discord.channel;
import discord4j.core.object.entity.User;
public class DiscordChannelPartEvent extends DiscordChannelEvent {
/**
* Class constructor.
*
* @param {IUser} user
*/
public DiscordChannelPartEvent(User user) {
super(user);
}
}
| gpl-3.0 |
MTK6580/walkie-talkie | ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/development/samples/Support7Demos/src/com/example/android/supportv7/app/ToolbarDisplayOptions.java | 4827 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.supportv7.app;
import com.example.android.supportv7.R;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Toast;
/**
* This demo shows how various action bar display option flags can be combined and their effects
* when used on a Toolbar-provided Action Bar
*/
public class ToolbarDisplayOptions extends ActionBarActivity
implements View.OnClickListener {
private View mCustomView;
private ActionBar.LayoutParams mCustomViewLayoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toolbar_display_options);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.toggle_home_as_up).setOnClickListener(this);
findViewById(R.id.toggle_show_home).setOnClickListener(this);
findViewById(R.id.toggle_use_logo).setOnClickListener(this);
findViewById(R.id.toggle_show_title).setOnClickListener(this);
findViewById(R.id.toggle_show_custom).setOnClickListener(this);
findViewById(R.id.cycle_custom_gravity).setOnClickListener(this);
findViewById(R.id.toggle_visibility).setOnClickListener(this);
// Configure several action bar elements that will be toggled by display options.
mCustomView = getLayoutInflater().inflate(R.layout.action_bar_display_options_custom, null);
mCustomViewLayoutParams = new ActionBar.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_options_actions, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
@Override
public void onClick(View v) {
final ActionBar bar = getSupportActionBar();
int flags = 0;
switch (v.getId()) {
case R.id.toggle_home_as_up:
flags = ActionBar.DISPLAY_HOME_AS_UP;
break;
case R.id.toggle_show_home:
flags = ActionBar.DISPLAY_SHOW_HOME;
break;
case R.id.toggle_use_logo:
flags = ActionBar.DISPLAY_USE_LOGO;
getSupportActionBar().setLogo(R.drawable.ic_media_play);
break;
case R.id.toggle_show_title:
flags = ActionBar.DISPLAY_SHOW_TITLE;
break;
case R.id.toggle_show_custom:
flags = ActionBar.DISPLAY_SHOW_CUSTOM;
break;
case R.id.cycle_custom_gravity: {
ActionBar.LayoutParams lp = mCustomViewLayoutParams;
int newGravity = 0;
switch (lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.LEFT:
newGravity = Gravity.CENTER_HORIZONTAL;
break;
case Gravity.CENTER_HORIZONTAL:
newGravity = Gravity.RIGHT;
break;
case Gravity.RIGHT:
newGravity = Gravity.LEFT;
break;
}
lp.gravity = lp.gravity & ~Gravity.HORIZONTAL_GRAVITY_MASK | newGravity;
bar.setCustomView(mCustomView, lp);
return;
}
case R.id.toggle_visibility:
if (bar.isShowing()) {
bar.hide();
} else {
bar.show();
}
return;
}
int change = bar.getDisplayOptions() ^ flags;
bar.setDisplayOptions(change, flags);
}
}
| gpl-3.0 |
MinecoloniesDevs/Minecolonies | src/test/java/com/minecolonies/inventory/InventoryTest.java | 1801 | package com.minecolonies.inventory;
import com.minecolonies.colony.buildings.Building;
import com.minecolonies.colony.materials.MaterialStore;
import com.minecolonies.colony.materials.MaterialSystem;
import com.minecolonies.tileentities.TileEntityColonyBuilding;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class InventoryTest
{
private IInventory inventory;
private MaterialSystem materialSystem;
private MaterialStore materialStore;
@Before
public void setupInventories()
{
this.materialSystem = new MaterialSystem();
TileEntityColonyBuilding colonyBuilding = new TileEntityColonyBuilding();
this.materialStore = new MaterialStore(MaterialStore.Type.CHEST, materialSystem);
Building mockBuilding = mock(Building.class);
when(mockBuilding.getMaterialStore()).thenReturn(this.materialStore);
colonyBuilding.setBuilding(mockBuilding);
this.inventory = colonyBuilding;
}
@Test
public void emptyInventoryTest()
{
for (int i = 0; i < inventory.getSizeInventory(); i++)
{
assertThat(inventory.getStackInSlot(i), is(nullValue()));
}
}
@Test
public void addStackTest()
{
Item testItem = mock(Item.class);
final ItemStack stuff = new ItemStack(testItem, 3);
inventory.setInventorySlotContents(0, stuff);
//assertThat(inventory.getStackInSlot(0), is(stuff));
}
}
| gpl-3.0 |
Drakmord2/rec-compiler | Compilador/src/compiler/Compiler.java | 3268 | package compiler;
import checker.Checker;
import checker.SemanticException;
import encoder.Encoder;
import parser.Parser;
import parser.SyntacticException;
import scanner.LexicalException;
import util.FileException;
import util.AST.Programa;
/**
* Compiler driver
* @version 2010-september-04
* @discipline Compiladores
* @author Gustavo H P Carvalho
* @email gustavohpcarvalho@ecomp.poli.br
*/
public class Compiler {
/**
* Compiler start point
* @param args - none
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
String location = Compiler.validateInput(args);
String[] file = location.split("/");
String out = location.split(".rec")[0];
Compiler.printHeader(file);
Parser p = new Parser(location);
Programa astRoot = null;
astRoot = p.parse();
System.out.println("\nAnálise Lexica - PASS");
System.out.println("Análise Sintatica - PASS");
if ( astRoot != null ) {
Checker c = new Checker();
astRoot = c.check(astRoot);
System.out.println("Análise Semantica - PASS");
out = out+".asm";
Encoder e = new Encoder(astRoot, location, out);
e.encode();
Compiler.printBody(astRoot, out);
}
}
catch (LexicalException e) {
System.out.println(e.toString());
} catch (SyntacticException e) {
System.out.println(e.toString());
} catch (SemanticException e) {
System.out.println(e.toString());
} catch (FileException e) {
System.out.println(e.toString());
}
}
public static String validateInput(String[] arg) throws FileException {
if (arg.length == 0) {
String message = "Path do codigo-fonte é inválido";
throw new FileException(message);
}
String location = arg[0];
String[] ext = location.split("[.]");
int i = ext.length;
try {
if (! ext[i-1].equals("rec")) {
String message = "Código-fonte não é da linguagem REC.";
throw new FileException(message);
}
} catch (ArrayIndexOutOfBoundsException e) {
String message = "Código-fonte não é da linguagem REC.";
throw new FileException(message);
}
return location;
}
public static void printHeader(String[] file) {
System.out.println("\nREC Compiler\nVersão 0.9 - 2017\nRubens Carneiro - rec2@ecomp.poli.br");
System.out.println("\nCompilando código-fonte [ " + file[file.length-1] + " ]\n");
System.out.println("-----------------------------------------------------------------------------------------");
}
public static void printBody(Programa astRoot, String out) {
System.out.println("Gerador de Código - PASS\n");
System.out.println("-----------------------------------------------------------------------------------------");
System.out.println("\n\t-- AST Decorada --\n");
System.out.println( astRoot.toString(0));
System.out.println("-----------------------------------------------------------------------------------------\n");
System.out.println("Código Assembly (NASM) criado em [ "+out+" ]\n");
System.out.println("-----------------------------------------------------------------------------------------\n");
}
}
| gpl-3.0 |
mariotaku/harmony | src/org/mariotaku/harmony/app/HarmonyApplication.java | 1908 | package org.mariotaku.harmony.app;
import android.app.Application;
import android.content.Context;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.download.HttpClientImageDownloader;
import java.io.File;
import org.mariotaku.harmony.Constants;
import org.mariotaku.harmony.util.ImageLoaderWrapper;
import org.mariotaku.harmony.util.ImageMemoryCache;
import org.mariotaku.harmony.util.URLFileNameGenerator;
public class HarmonyApplication extends Application implements Constants {
private ImageLoaderWrapper mImageLoaderWrapper;
private ImageLoader mImageLoader;
public ImageLoader getImageLoader() {
if (mImageLoader != null) return mImageLoader;
final File cache_dir = new File(getCacheDir(), CACHE_DIR_NAME_ALBUMART);
if (!cache_dir.exists()) {
cache_dir.mkdirs();
}
final ImageLoader loader = ImageLoader.getInstance();
final ImageLoaderConfiguration.Builder cb = new ImageLoaderConfiguration.Builder(this);
cb.threadPoolSize(8);
cb.memoryCache(new ImageMemoryCache(40));
cb.discCache(new UnlimitedDiscCache(cache_dir, new URLFileNameGenerator()));
cb.imageDownloader(new BaseImageDownloader(this));
loader.init(cb.build());
return mImageLoader = loader;
}
public ImageLoaderWrapper getImageLoaderWrapper() {
if (mImageLoaderWrapper != null) return mImageLoaderWrapper;
return mImageLoaderWrapper = new ImageLoaderWrapper(getImageLoader());
}
public static HarmonyApplication getInstance(final Context context) {
final Context app = context != null ? context.getApplicationContext() : null;
return app instanceof HarmonyApplication ? (HarmonyApplication) app : null;
}
}
| gpl-3.0 |
marevalo/FlowsManager | app/src/main/java/net/marevalo/flowsmanager/CollectionAdapter.java | 1955 | package net.marevalo.flowsmanager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CollectionAdapter extends BaseAdapter {
// private static final String LOGTAG = "CollectionAdapter";
Context context;
ArrayList<Entity> collection;
public CollectionAdapter(Context context, ArrayList<Entity> list) {
this.context = context;
collection = list;
}
@Override
public int getCount() {
return collection.size();
}
@Override
public Object getItem(int position) {
return collection.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
//Log.d(LOGTAG, "Recreating view" );
Entity entity = collection.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_entity, null);
}
// Set the icon
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.iconImageView );
ivIcon.setImageDrawable(
context.getResources().getDrawable(entity.getIconResource() ) );
// Set the name and ID
TextView tvName = (TextView) convertView.findViewById(R.id.tv_entity_name);
String name = entity.getDisplayName() ;
tvName.setText( name );
TextView tvId = (TextView) convertView.findViewById(R.id.tv_entity_id);
String id = entity.getIdName();
tvId.setText(((name == id) ? "" : id));
return convertView;
}
}
| gpl-3.0 |
kostovhg/SoftUni | Java_DBFundamentals-Jan18/DBAdvanced_HibernateSpring/s_Practical_Exam/Skeleton/src/test/java/org.softuni.mostwanted/entity/CarEntityTests.java | 5858 | package org.softuni.mostwanted.entity;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.softuni.mostwanted.util.ReflectionUtil;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
@RunWith(SpringJUnit4ClassRunner.class)
public class CarEntityTests {
private static final String CLASS_NAME = "Car";
private Class<?> entityClass;
@Before
public void setUp() {
entityClass = new ReflectionUtil().getTestClass(CLASS_NAME);
}
@Test
public void carEntity_ShouldHaveIdAnnotation() {
Field[] entityFields = entityClass.getDeclaredFields();
Method[] entityMethods = entityClass.getDeclaredMethods();
boolean hasId =
Arrays.stream(entityFields)
.anyMatch(ef -> ef.isAnnotationPresent(Id.class) && ef.getName().equals("id"))
||
Arrays.stream(entityMethods)
.anyMatch(em -> em.isAnnotationPresent(Id.class) && em.getName().equals("getId"));
Assert.assertTrue("No Id annotation detected on " + CLASS_NAME + " binding.", hasId);
}
@Test
public void carEntity_BrandFieldShouldBeRequired() {
Field[] entityFields = entityClass.getDeclaredFields();
Method[] entityMethods = entityClass.getDeclaredMethods();
String fieldName = "brand";
String getterName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
boolean hasNameRequired =
Arrays.stream(entityFields)
.anyMatch(ef -> ef.isAnnotationPresent(Column.class)
&& !ef.getAnnotation(Column.class).nullable()
&& ef.getName().equals(fieldName))
||
Arrays.stream(entityMethods)
.anyMatch(em -> em.isAnnotationPresent(Column.class)
&& !em.getAnnotation(Column.class).nullable()
&& em.getName().equals(getterName));
Assert.assertTrue("No Required configuration on \"" + fieldName + "\" field detected in " + CLASS_NAME + " binding.", hasNameRequired);
}
@Test
public void carEntity_ModelFieldShouldBeRequired() {
Field[] entityFields = entityClass.getDeclaredFields();
Method[] entityMethods = entityClass.getDeclaredMethods();
String fieldName = "model";
String getterName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
boolean hasNameRequired =
Arrays.stream(entityFields)
.anyMatch(ef -> ef.isAnnotationPresent(Column.class)
&& !ef.getAnnotation(Column.class).nullable()
&& ef.getName().equals(fieldName))
||
Arrays.stream(entityMethods)
.anyMatch(em -> em.isAnnotationPresent(Column.class)
&& !em.getAnnotation(Column.class).nullable()
&& em.getName().equals(getterName));
Assert.assertTrue("No Required configuration on \"" + fieldName + "\" field detected in " + CLASS_NAME + " binding.", hasNameRequired);
}
@Test
public void carEntity_YearOfProductionFieldShouldBeRequired() {
Field[] entityFields = entityClass.getDeclaredFields();
Method[] entityMethods = entityClass.getDeclaredMethods();
String fieldName = "yearOfProduction";
String getterName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
boolean hasNameRequired =
Arrays.stream(entityFields)
.anyMatch(ef -> ef.isAnnotationPresent(Column.class)
&& !ef.getAnnotation(Column.class).nullable()
&& ef.getName().equals(fieldName))
||
Arrays.stream(entityMethods)
.anyMatch(em -> em.isAnnotationPresent(Column.class)
&& !em.getAnnotation(Column.class).nullable()
&& em.getName().equals(getterName));
Assert.assertTrue("No Required configuration on \"" + fieldName + "\" field detected in " + CLASS_NAME + " binding.", hasNameRequired);
}
@Test
public void carEntity_RacerFieldShouldHaveRelationshipAnnotation() {
Field[] entityFields = entityClass.getDeclaredFields();
Method[] entityMethods = entityClass.getDeclaredMethods();
String fieldName = "racer";
String getterName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
Class relationshipClass = ManyToOne.class;
boolean hasNameRequired =
Arrays.stream(entityFields)
.anyMatch(ef -> ef.isAnnotationPresent(relationshipClass)
&& ef.getName().equals(fieldName))
||
Arrays.stream(entityMethods)
.anyMatch(em ->
em.isAnnotationPresent(relationshipClass)
&& em.getName().equals(getterName));
Assert.assertTrue("No Relationship configuration on \"" + fieldName + "\" field detected in " + CLASS_NAME + " binding.", hasNameRequired);
}
}
| gpl-3.0 |
kostovhg/SoftUni | JavaWeb/JavaWebDevelopmentBasics/f_serverpages/demo/src/main/java/web/HomeServlet.java | 3142 | package web;
import entities.User;
import services.UserService;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
@WebServlet("/")
public class HomeServlet extends HttpServlet {
private final UserService userService;
@Inject
public HomeServlet(UserService userService){
this.userService = userService;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String html = getHtml();
resp.getWriter().write(html);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String body = req.getReader().lines()
.collect(Collectors.joining());
User user = new User();
Arrays.stream(body.split("&"))
.map(pairString -> pairString.split("="))
.forEach(pair -> {
switch (pair[0]){
case "name":
user.setName(pair[1].replace('+', ' ').trim());
break;
case "age":
user.setAge(pair[1].trim());
}
});
userService.add(user);
String result = getHtml();
resp.getWriter().write(result);
}
public String getUserList() {
return String.format("<ul>%s</ul>",
this.userService.getAllUsers().stream()
.map(user ->
String.format("<li>%s %s</li>", user.getName(), user.getAge())).collect(Collectors.joining(System.lineSeparator())));
}
public String getForm() {
return "<form action=\"/\" method=\"post\">\n" +
" <label for=\"name\">\n" +
" <input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Enter your name\" required>\n" +
" </label>\n" +
"<label for=\"age\">\n" +
" <input type=\"number\" id=\"age\" name=\"age\" placeholder=\"Enter your age\" required>\n" +
" </label>\n" +
" <button>Submit</button>\n" +
"</form>\n";
}
public String getHtml() {
String form = getForm();
String userList = getUserList();
return "<!DOCTYPE html>\n" +
" <html lang=\"en\">\n" +
" <head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>Title</title>\n" +
" </head>\n" +
" <body>\n" +
form + "<br />" +
userList +
"</body>\n" +
"</html>";
}
}
| gpl-3.0 |
AnimeniacYuuto/QuantumElectronics | src/main/java/yuuto/quantumelectronics/transport/routing/IItemDestination.java | 250 | package yuuto.quantumelectronics.transport.routing;
import net.minecraft.item.ItemStack;
public interface IItemDestination extends IItemRouter{
ItemStack insertItem(ItemStack stack, boolean simulate, boolean supplier);
boolean isSupplier();
}
| gpl-3.0 |
notsyncing/lightfur | lightfur-integration-jdbc/src/main/java/io/github/notsyncing/lightfur/integration/jdbc/ReflectDataMapper.java | 2099 | package io.github.notsyncing.lightfur.integration.jdbc;
import io.github.notsyncing.lightfur.annotations.entity.Column;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ReflectDataMapper extends JdbcDataMapper
{
private <T> T mapCurrentRow(Class<T> clazz, ResultSet result) throws IllegalAccessException, InstantiationException, SQLException {
T instance = clazz.newInstance();
List<Field> fields = new ArrayList<>();
fields.addAll(Arrays.asList(clazz.getFields()));
if (clazz.getDeclaredFields().length > 0) {
Stream.of(clazz.getDeclaredFields())
.filter(f -> Modifier.isPrivate(f.getModifiers()))
.forEach(f -> {
f.setAccessible(true);
fields.add(f);
});
}
for (Field f : fields) {
if (!f.isAnnotationPresent(Column.class)) {
continue;
}
Column c = f.getAnnotation(Column.class);
int colIndex;
try {
colIndex = result.findColumn(c.value());
} catch (SQLException e) {
continue;
}
f.set(instance, valueToType(f.getType(), result.getObject(colIndex)));
}
return instance;
}
@Override
public <T> T map(Class<T> clazz, ResultSet results) throws IllegalAccessException, InstantiationException, SQLException {
if (!results.next()) {
return null;
}
return mapCurrentRow(clazz, results);
}
@Override
public <T> List<T> mapToList(Class<T> clazz, ResultSet results) throws InstantiationException, IllegalAccessException, SQLException {
List<T> list = new ArrayList<>();
while (results.next()) {
list.add(mapCurrentRow(clazz, results));
}
return list;
}
}
| gpl-3.0 |
t08094a/ffManagementSuite | src/main/java/de/leif/ffmanagementsuite/service/UserService.java | 10089 | package de.leif.ffmanagementsuite.service;
import de.leif.ffmanagementsuite.domain.Authority;
import de.leif.ffmanagementsuite.domain.User;
import de.leif.ffmanagementsuite.repository.AuthorityRepository;
import de.leif.ffmanagementsuite.config.Constants;
import de.leif.ffmanagementsuite.repository.UserRepository;
import de.leif.ffmanagementsuite.security.AuthoritiesConstants;
import de.leif.ffmanagementsuite.security.SecurityUtils;
import de.leif.ffmanagementsuite.service.util.RandomUtil;
import de.leif.ffmanagementsuite.service.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
* Service class for managing users.
*/
@Service
@Transactional
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
private final CacheManager cacheManager;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authorityRepository = authorityRepository;
this.cacheManager = cacheManager;
}
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400)))
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
cacheManager.getCache("users").evict(user.getLogin());
return user;
});
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository.findOneByEmailIgnoreCase(mail)
.filter(User::getActivated)
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
cacheManager.getCache("users").evict(user.getLogin());
return user;
});
}
public User createUser(String login, String password, String firstName, String lastName, String email,
String imageUrl, String langKey) {
User newUser = new User();
Authority authority = authorityRepository.findOne(AuthoritiesConstants.USER);
Set<Authority> authorities = new HashSet<>();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(login);
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
newUser.setEmail(email);
newUser.setImageUrl(imageUrl);
newUser.setLangKey(langKey);
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
authorities.add(authority);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
log.debug("Created Information for User: {}", newUser);
return newUser;
}
public User createUser(UserDTO userDTO) {
User user = new User();
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
if (userDTO.getLangKey() == null) {
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
} else {
user.setLangKey(userDTO.getLangKey());
}
if (userDTO.getAuthorities() != null) {
Set<Authority> authorities = new HashSet<>();
userDTO.getAuthorities().forEach(
authority -> authorities.add(authorityRepository.findOne(authority))
);
user.setAuthorities(authorities);
}
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
user.setPassword(encryptedPassword);
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
user.setActivated(true);
userRepository.save(user);
log.debug("Created Information for User: {}", user);
return user;
}
/**
* Update basic information (first name, last name, email, language) for the current user.
*
* @param firstName first name of user
* @param lastName last name of user
* @param email email id of user
* @param langKey language key
* @param imageUrl image URL of user
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Changed Information for User: {}", user);
});
}
/**
* Update all information for a specific user, and return the modified user.
*
* @param userDTO user to update
* @return updated user
*/
public Optional<UserDTO> updateUser(UserDTO userDTO) {
return Optional.of(userRepository
.findOne(userDTO.getId()))
.map(user -> {
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO.getAuthorities().stream()
.map(authorityRepository::findOne)
.forEach(managedAuthorities::add);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Changed Information for User: {}", user);
return user;
})
.map(UserDTO::new);
}
public void deleteUser(String login) {
userRepository.findOneByLogin(login).ifPresent(user -> {
userRepository.delete(user);
cacheManager.getCache("users").evict(login);
log.debug("Deleted User: {}", user);
});
}
public void changePassword(String password) {
userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> {
String encryptedPassword = passwordEncoder.encode(password);
user.setPassword(encryptedPassword);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public User getUserWithAuthorities(Long id) {
return userRepository.findOneWithAuthoritiesById(id);
}
@Transactional(readOnly = true)
public User getUserWithAuthorities() {
return userRepository.findOneWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin()).orElse(null);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS));
for (User user : users) {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
cacheManager.getCache("users").evict(user.getLogin());
}
}
/**
* @return a list of all the authorities
*/
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
}
| gpl-3.0 |
chrxn/wsdot-mobile-app | src/main/java/gov/wa/wsdot/mobile/client/activities/trafficmap/expresslanes/SeattleExpressLanesView.java | 1634 | /*
* Copyright (c) 2014 Washington State Department of Transportation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package gov.wa.wsdot.mobile.client.activities.trafficmap.expresslanes;
import gov.wa.wsdot.mobile.shared.ExpressLaneItem;
import java.util.List;
import com.google.gwt.user.client.ui.IsWidget;
import com.googlecode.mgwt.ui.client.widget.base.HasRefresh;
import com.googlecode.mgwt.ui.client.widget.panel.pull.PullArrowWidget;
import com.googlecode.mgwt.ui.client.widget.panel.pull.PullPanel.Pullhandler;
public interface SeattleExpressLanesView extends IsWidget {
public void setPresenter(Presenter presenter);
public interface Presenter {
public void onDoneButtonPressed();
}
public void render(List<ExpressLaneItem> createPostList);
public void showProgressIndicator();
public void hideProgressIndicator();
public void refresh();
public void setHeaderPullHandler(Pullhandler pullHandler);
public PullArrowWidget getPullHeader();
public HasRefresh getPullPanel();
}
| gpl-3.0 |
alfonsodou/javaLeagueBootstrap | src/org/javahispano/javaleague/client/event/UpdateTacticEvent.java | 721 | /**
*
*/
package org.javahispano.javaleague.client.event;
import org.javahispano.javaleague.shared.domain.TacticUser;
import com.google.gwt.event.shared.GwtEvent;
/**
* @author adou
*
*/
public class UpdateTacticEvent extends GwtEvent<UpdateTacticEventHandler> {
public static Type<UpdateTacticEventHandler> TYPE = new Type<UpdateTacticEventHandler>();
private final TacticUser userTactic;
public UpdateTacticEvent(TacticUser result) {
this.userTactic = result;
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<UpdateTacticEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(UpdateTacticEventHandler handler) {
handler.onUpdateTactic(this);
}
}
| gpl-3.0 |
Cubeville/HawkEye-Redux | api/src/main/java/org/cubeville/hawkeye/config/ConfigurationNode.java | 7970 | /*
* HawkEye Redux
* Copyright (C) 2012-2013 Cubeville <http://www.cubeville.org> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cubeville.hawkeye.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Configuration implementation backed by a nested map
*/
public class ConfigurationNode implements Configuration {
protected Map<String, Object> root;
private boolean writeDefaults;
public ConfigurationNode(Map<String, Object> root) {
this(root, false);
}
public ConfigurationNode(Map<String, Object> root, boolean writeDefaults) {
this.root = root;
this.writeDefaults = writeDefaults;
}
/**
* Gets the configuration's backing map
*
* @return Map of keys and values
*/
public Map<String, Object> getRoot() {
return root;
}
@Override
public void clear() {
root.clear();
}
@SuppressWarnings("unchecked")
@Override
public Object get(String node) {
// Process dot notation
String[] path = node.split("\\.");
Object val = null;
Map<String, Object> tmp = root;
// Loop through map to get nested values
for (int i = 0; i < path.length; i++) {
val = tmp.get(path[i]);
// Path doesn't exist
if (val == null) return null;
// Last piece of path
if (i == path.length - 1) break;
try {
// Get next level of nested map
tmp = (Map<String, Object>) val;
} catch (ClassCastException ex) {
// Nested map doesn't exist
return null;
}
}
return val;
}
@Override
public Object get(String path, Object def) {
Object val = get(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@SuppressWarnings("unchecked")
@Override
public void set(String node, Object value) {
// Process dot notation
String[] path = node.split("\\.");
Map<String, Object> tmp = root;
for (int i = 0; i < path.length; i++) {
// Last level of nesting reached
if (i == path.length - 1) {
tmp.put(path[i], value);
return;
}
Object val = tmp.get(path[i]);
if (val == null || !(val instanceof Map)) {
// Create a map if it isn't already there
val = new HashMap<String, Object>();
tmp.put(path[i], val);
}
tmp = (Map<String, Object>) val;
}
}
@Override
public String getString(String path) {
Object val = get(path);
return val == null ? null : val.toString();
}
@Override
public String getString(String path, String def) {
String val = getString(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public Integer getInt(String path) {
Object val = get(path);
if (val instanceof Number) {
return ((Number) val).intValue();
} else {
return null;
}
}
@Override
public int getInt(String path, int def) {
Integer val = getInt(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public Double getDouble(String path) {
Object val = get(path);
if (val instanceof Number) {
return ((Number) val).doubleValue();
} else {
return null;
}
}
@Override
public double getDouble(String path, double def) {
Double val = getDouble(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public Boolean getBoolean(String path) {
Object val = get(path);
if (val instanceof Boolean) {
return (Boolean) val;
} else {
return null;
}
}
@Override
public boolean getBoolean(String path, boolean def) {
Boolean val = getBoolean(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public List<String> getStringList(String path) {
Object val = get(path);
List<String> list = new ArrayList<String>();
if (!(val instanceof List)) {
return list;
}
@SuppressWarnings("unchecked")
List<Object> raw = (List<Object>) val;
for (Object obj : raw) {
if (obj != null) list.add(obj.toString());
}
return list;
}
@Override
public List<String> getStringList(String path, List<String> def) {
List<String> val = getStringList(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public List<Integer> getIntList(String path) {
Object val = get(path);
List<Integer> list = new ArrayList<Integer>();
if (!(val instanceof List)) {
return list;
}
@SuppressWarnings("unchecked")
List<Object> raw = (List<Object>) val;
for (Object obj : raw) {
if (obj instanceof Number) list.add(((Number) obj).intValue());
}
return list;
}
@Override
public List<Integer> getIntList(String path, List<Integer> def) {
List<Integer> val = getIntList(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public List<Double> getDoubleList(String path) {
Object val = get(path);
List<Double> list = new ArrayList<Double>();
if (!(val instanceof List)) {
return list;
}
@SuppressWarnings("unchecked")
List<Object> raw = (List<Object>) val;
for (Object obj : raw) {
if (obj instanceof Number) list.add(((Number) obj).doubleValue());
}
return list;
}
@Override
public List<Double> getDoubleList(String path, List<Double> def) {
List<Double> val = getDoubleList(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public boolean writeDefaults() {
return writeDefaults;
}
@Override
public void setWriteDefaults(boolean writeDefaults) {
this.writeDefaults = writeDefaults;
}
@Override public Object get(Variable path) { return get(path.getPath()); }
@Override public Object get(Variable path, Object def) { return get(path.getPath(), def); }
@Override public void set(Variable path, Object value) { set(path.getPath(), value); }
@Override public String getString(Variable path) { return getString(path.getPath()); }
@Override public String getString(Variable path, String def) { return getString(path.getPath(), def); }
@Override public Integer getInt(Variable path) { return getInt(path.getPath()); }
@Override public int getInt(Variable path, int def) { return getInt(path.getPath(), def); }
@Override public Double getDouble(Variable path) { return getDouble(path.getPath()); }
@Override public double getDouble(Variable path, double def) { return getDouble(path.getPath(), def); }
@Override public Boolean getBoolean(Variable path) { return getBoolean(path.getPath()); }
@Override public boolean getBoolean(Variable path, boolean def) { return getBoolean(path.getPath(), def); }
@Override public List<String> getStringList(Variable path) { return getStringList(path.getPath()); }
@Override public List<String> getStringList(Variable path, List<String> def) { return getStringList(path.getPath(), def); }
@Override public List<Integer> getIntList(Variable path) { return getIntList(path.getPath()); }
@Override public List<Integer> getIntList(Variable path, List<Integer> def) { return getIntList(path.getPath(), def); }
@Override public List<Double> getDoubleList(Variable path) { return getDoubleList(path.getPath()); }
@Override public List<Double> getDoubleList(Variable path, List<Double> def) { return getDoubleList(path.getPath(), def); }
}
| gpl-3.0 |
paolopavan/cfr | src/weka/gui/BEANS/TestSetEvent.java | 2331 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* TestSetEvent.java
* Copyright (C) 2002 Mark Hall
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.core.Instances;
/**
* Event encapsulating a test set
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision: 1.2 $
*/
public class TestSetEvent extends EventObject {
/**
* The test set instances
*/
protected Instances m_testSet;
private boolean m_structureOnly;
/**
* what number is this test set (ie fold 2 of 10 folds)
*/
protected int m_setNumber;
/**
* Maximum number of sets (ie 10 in a 10 fold)
*/
protected int m_maxSetNumber;
public TestSetEvent(Object source, Instances testSet) {
super(source);
m_testSet = testSet;
if (m_testSet != null && m_testSet.numInstances() == 0) {
m_structureOnly = true;
}
}
/**
* Get the test set instances
*
* @return an <code>Instances</code> value
*/
public Instances getTestSet() {
return m_testSet;
}
/**
* Get the test set number (eg. fold 2 of a 10 fold split)
*
* @return an <code>int</code> value
*/
public int getSetNumber() {
return m_setNumber;
}
/**
* Get the maximum set number
*
* @return an <code>int</code> value
*/
public int getMaxSetNumber() {
return m_maxSetNumber;
}
/**
* Returns true if the encapsulated instances
* contain just header information
*
* @return true if only header information is
* available in this DataSetEvent
*/
public boolean isStructureOnly() {
return m_structureOnly;
}
}
| gpl-3.0 |
donatellosantoro/Llunatic | lunaticEngine/src/it/unibas/lunatic/model/chase/chasede/operators/mainmemory/MainMemoryReplaceDatabase.java | 2579 | package it.unibas.lunatic.model.chase.chasede.operators.mainmemory;
import it.unibas.lunatic.Scenario;
import it.unibas.lunatic.model.chase.chasede.operators.IReplaceDatabase;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import speedy.model.algebra.operators.ITupleIterator;
import speedy.model.algebra.operators.mainmemory.MainMemoryInsertTuple;
import speedy.model.database.Cell;
import speedy.model.database.IDatabase;
import speedy.model.database.Tuple;
import speedy.model.database.mainmemory.MainMemoryDB;
import speedy.model.database.mainmemory.MainMemoryTable;
import speedy.model.database.mainmemory.MainMemoryVirtualDB;
import speedy.model.database.mainmemory.MainMemoryVirtualTable;
public class MainMemoryReplaceDatabase implements IReplaceDatabase {
private final static Logger logger = LoggerFactory.getLogger(MainMemoryReplaceDatabase.class);
private final static MainMemoryInsertTuple insert = new MainMemoryInsertTuple();
public void replaceTargetDB(IDatabase newDatabase, Scenario scenario) {
if (newDatabase instanceof MainMemoryDB) {
scenario.setTarget(newDatabase);
return;
}
MainMemoryVirtualDB virtualDB = (MainMemoryVirtualDB) newDatabase;
if (logger.isDebugEnabled()) logger.debug("Copying virtual db\n" + newDatabase);
MainMemoryDB mainMemoryDB = new MainMemoryDB(virtualDB.getDataSource());
for (String tableName : mainMemoryDB.getTableNames()) {
MainMemoryTable table = (MainMemoryTable) mainMemoryDB.getTable(tableName);
emptyTable(table);
insertAllTuples(table, (MainMemoryVirtualTable) virtualDB.getTable(tableName));
}
if (logger.isDebugEnabled()) logger.debug("New db\n" + mainMemoryDB);
scenario.setTarget(mainMemoryDB);
}
private void emptyTable(MainMemoryTable table) {
table.getDataSource().getInstances().get(0).getChildren().clear();
}
private void insertAllTuples(MainMemoryTable table, MainMemoryVirtualTable mainMemoryVirtualTable) {
ITupleIterator it = mainMemoryVirtualTable.getTupleIterator();
while (it.hasNext()) {
Tuple tuple = it.next();
removeOID(tuple);
insert.execute(table, tuple, null, null);
}
}
private void removeOID(Tuple tuple) {
for (Iterator<Cell> it = tuple.getCells().iterator(); it.hasNext();) {
Cell cell = it.next();
if (cell.isOID()) {
it.remove();
}
}
}
}
| gpl-3.0 |
qt-haiku/LibreOffice | qadevOOo/tests/java/ifc/sheet/_XDataPilotTables.java | 5478 | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package ifc.sheet;
import lib.MultiMethodTest;
import lib.Status;
import lib.StatusException;
import com.sun.star.sheet.XDataPilotDescriptor;
import com.sun.star.sheet.XDataPilotTables;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.table.CellAddress;
/**
* Testing <code>com.sun.star.sheet.XDataPilotTables</code>
* interface methods :
* <ul>
* <li><code> createDataPilotDescriptor()</code></li>
* <li><code> insertNewByName()</code></li>
* <li><code> removeByName()</code></li>
* </ul> <p>
* This test needs the following object relations :
* <ul>
* <li> <code>'SHEET'</code> (of type <code>XSpreadsheet</code>):
* to have a spreadsheet document for document content checking</li>
* <ul> <p>
* @see com.sun.star.sheet.XDataPilotTables
*/
public class _XDataPilotTables extends MultiMethodTest {
public XDataPilotTables oObj = null;
XDataPilotDescriptor DPDscr = null;
String name = "XDataPilotTables";
CellAddress CA = new CellAddress((short)0, 9, 8);
XSpreadsheet oSheet = null;
/**
* Retrieves object relations.
* @throws StatusException If one of relations not found.
*/
protected void before() {
oSheet = (XSpreadsheet)tEnv.getObjRelation("SHEET");
if (oSheet == null) throw new StatusException(Status.failed
("Relation 'SHEET' not found"));
}
/**
* Test calls the method, stores returned value and checks returned value.
* <p>Has <b> OK </b> status if returned value isn't null. <p>
*/
public void _createDataPilotDescriptor(){
DPDscr = oObj.createDataPilotDescriptor();
tRes.tested("createDataPilotDescriptor()", DPDscr != null);
}
/**
* Test calls the method inserting new table with new name and then calls
* the method inserting table with existent name. <p>
* Has <b> OK </b> status if the cell content where table was inserted is
* equal to 'Filter' after first call and exception was thrown during
* second call. <p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code> createDataPilotDescriptor() </code> : to have
* <code>XDataPilotDescriptor</code> created by this method</li>
* </ul>
*/
public void _insertNewByName(){
requiredMethod("createDataPilotDescriptor()");
boolean bResult = true;
log.println("Inserting new Table \"" + name + "\"");
try {
oObj.insertNewByName(name, CA, DPDscr);
bResult &= oSheet.getCellByPosition
(CA.Column, CA.Row).getFormula().equals("Filter");
} catch (com.sun.star.uno.Exception e) {
log.println("Exception occurred! " + e);
bResult = false;
}
log.println(bResult ? "OK" : "FAILED");
log.println("Trying to insert element with existent name");
try {
oObj.insertNewByName(name,new CellAddress((short)0, 7, 7), DPDscr);
log.println("No exception! - FAILED");
bResult = false;
} catch (com.sun.star.uno.RuntimeException e) {
log.println("Expected exception - OK " + e);
}
log.println("Inserting new table " + (bResult ? "OK" : "FAILED"));
tRes.tested("insertNewByName()", bResult);
}
/**
* Test calls the method for existent table and for unexistent table. <p>
* Has <b> OK </b> status if the cell where table was removed from is empty
* after first call and exception was thrown during second call. <p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code>insertNewByName()</code>: to have name of existent table</li>
* </ul>
*/
public void _removeByName(){
requiredMethod("insertNewByName()");
boolean bResult = true;
log.println("Remove table with name " + name);
try {
oObj.removeByName(name);
bResult &= oSheet.getCellByPosition
(CA.Column, CA.Row).getFormula().equals("");
} catch (com.sun.star.uno.Exception e) {
log.println("Exception occurred ! " + e);
bResult = false;
}
log.println(bResult ? "OK" : "FAILED");
log.println("Removing unexistent element");
try {
oObj.removeByName(name);
log.println("No exception! - FAILED");
bResult = false;
} catch (com.sun.star.uno.RuntimeException e) {
log.println("Expected exception - OK " + e);
}
log.println("Removing a table " + (bResult ? "OK" : "FAILED"));
tRes.tested("removeByName()", bResult);
}
}
| gpl-3.0 |
autowp/CANreader | app/src/main/java/com/autowp/canreader/UsbDeviceSpinnerAdapter.java | 2360 | package com.autowp.canreader;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by autow on 13.02.2016.
*/
public class UsbDeviceSpinnerAdapter extends ArrayAdapter<UsbDevice> {
public UsbDeviceSpinnerAdapter(Context context, int resource, List<UsbDevice> objects) {
super(context, resource, objects);
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.usbdevice_spinner_item, null);
}
UsbDevice device = getItem(position);
if (device != null) {
TextView tvProductName = (TextView)v.findViewById(R.id.textViewProductName);
TextView tvDeviceInto = (TextView)v.findViewById(R.id.textViewDeviceInfo);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tvProductName.setText(device.getProductName());
String deviceInfo = String.format(
"%s %04X/%04X, %s",
device.getManufacturerName(),
device.getVendorId(),
device.getProductId(),
device.getDeviceName()
);
tvDeviceInto.setText(deviceInfo);
} else {
tvProductName.setText(device.getDeviceName());
String deviceInfo = String.format(
"%04X/%04X",
device.getVendorId(),
device.getProductId()
);
tvDeviceInto.setText(deviceInfo);
}
}
return v;
}
}
| gpl-3.0 |
bengtmartensson/IrpMaster | src/main/java/org/harctoolbox/IrpMaster/Wave.java | 25136 | /*
Copyright (C) 2009-2013 Bengt Martensson.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see http://www.gnu.org/licenses/.
*/
package org.harctoolbox.IrpMaster;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* This class generates (or analyzes) a wave audio file that can be played
* on standard audio equipment and fed to a pair of anti-parallel double IR sending diodes,
* which can thus control IR equipment.
*
*
* @see <a href="http://www.lirc.org/html/audio.html">http://www.lirc.org/html/audio.html</a>
*/
public class Wave {
private static int debug = 0; // presently not used
private static int epsilon8Bit = 2;
private static int epsilon16Bit = 257;
private static JCommander argumentParser;
private static CommandLineArgs commandLineArgs = new CommandLineArgs();
/**
* Returns a line to the audio mixer on the local machine, suitable for sound with
* the parameter values given. When not needed, the user should close the line with its close()-function.
*
* @param audioFormat
* @return open audio line
* @throws LineUnavailableException
*/
public static SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException {
SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat);
line.open(audioFormat);
return line;
}
private static void usage(int exitcode) {
StringBuilder str = new StringBuilder(256);
argumentParser.usage(str);
str.append("\n"
+ "parameters: <protocol> <deviceno> [<subdevice_no>] commandno [<toggle>]\n"
+ " or <Pronto code>\n"
+ " or <importfile>");
(exitcode == IrpUtils.exitSuccess ? System.out : System.err).println(str);
IrpUtils.exit(exitcode);
}
/**
* Provides a command line interface to the export/import functions.
*
* <pre>
* Usage: Wave [options] [parameters]
* Options:
* -c, --config Path to IrpProtocols.ini
* Default: data/IrpProtocols.ini
* -h, --help, -? Display help message
* Default: false
* -m, --macrofile Macro filename
* -1, --nodivide Do not divide modulation frequency
* Default: false
* -t, --omittail Skip silence at end
* Default: false
* -o, --outfile Output filename
* Default: irpmaster.wav
* -p, --play Send the generated wave to the audio device of the
* local machine
* Default: false
* -r, --repeats Number of times to include the repeat sequence
* Default: 0
* -f, --samplefrequency Sample frequency in Hz
* Default: 44100
* -q, --square Modulate with square wave instead of sine
* Default: false
* -S, --stereo Generate two channels in anti-phase
* Default: false
* -v, --version Display version information
* Default: false
* -s, samplesize Sample size in bits
* Default: 8
*
* parameters: <em>protocol</em> <em>deviceno</em> [<em>subdevice_no</em>] <em>commandno</em> [<em>toggle</em>]
* or <em>ProntoCode</em>
* or <em>importfile</em>
* </pre>
* @param args
*/
public static void main(String[] args) {
argumentParser = new JCommander(commandLineArgs);
argumentParser.setProgramName("Wave");
try {
argumentParser.parse(args);
} catch (ParameterException ex) {
System.err.println(ex.getMessage());
usage(IrpUtils.exitUsageError);
}
if (commandLineArgs.helpRequensted)
usage(IrpUtils.exitSuccess);
if (commandLineArgs.versionRequested) {
System.out.println(Version.versionString);
System.out.println("JVM: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + " " + System.getProperty("os.name") + "-" + System.getProperty("os.arch"));
System.out.println();
System.out.println(Version.licenseString);
System.exit(IrpUtils.exitSuccess);
}
if (commandLineArgs.macrofile == null && commandLineArgs.parameters.isEmpty()) {
System.err.println("Parameters missing");
usage(IrpUtils.exitUsageError);
}
try {
if (commandLineArgs.parameters.size() == 1) {
// Exactly one argument left -> input wave file
String inputfile = commandLineArgs.parameters.get(0);
Wave wave = new Wave(new File(inputfile));
ModulatedIrSequence seq = wave.analyze(!commandLineArgs.dontDivide);
//IrSignal irSignal = new
DecodeIR.invoke(seq);
wave.dump(new File(inputfile + ".tsv"));
if (commandLineArgs.play)
wave.play();
} else {
//if (commandLineArgs.macrofile != null) {
//IrSequence irSequence = IrSequence.parseMacro(commandLineArgs.irprotocolsIniFilename, commandLineArgs.macrofile);
//Wave wave = new Wave()
//}
IrSignal irSignal = new IrSignal(commandLineArgs.irprotocolsIniFilename, 0, commandLineArgs.parameters.toArray(new String[commandLineArgs.parameters.size()]));
File file = new File(commandLineArgs.outputfile);
Wave wave = new Wave(irSignal.toModulatedIrSequence(true, commandLineArgs.noRepeats, true), commandLineArgs.sampleFrequency, commandLineArgs.sampleSize,
commandLineArgs.stereo ? 2 : 1, false /* bigEndian */,
commandLineArgs.omitTail, commandLineArgs.square, !commandLineArgs.dontDivide);
wave.export(file);
if (commandLineArgs.play)
wave.play();
}
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException | IrpMasterException ex) {
System.err.println(ex.getMessage());
System.exit(IrpUtils.exitFatalProgramFailure);
}
}
private int noFrames = -1;
private AudioFormat audioFormat;
private byte[] buf;
private Wave() {
}
/**
* Reads a wave file into a Wave object.
*
* @param file Wave file as input.
* @throws UnsupportedAudioFileException
* @throws IOException
*/
public Wave(File file) throws UnsupportedAudioFileException, IOException {
AudioInputStream af = AudioSystem.getAudioInputStream(file);
audioFormat = af.getFormat();
noFrames = (int) af.getFrameLength();
buf = new byte[noFrames*audioFormat.getFrameSize()];
int n = af.read(buf, 0, buf.length);
if (n != buf.length)
System.err.println("Too few bytes read: " + n + " < " + buf.length);
}
/**
* Generates a wave audio file from its arguments.
*
* @param freq Carrier frequency in Hz.
* @param data double array of durations in micro seconds.
* @param sampleFrequency Sample frequency of the generated wave file.
* @param sampleSize Sample size (8 or 16) in bits of the samples.
* @param channels If == 2, generates two channels in perfect anti-phase.
* @param bigEndian if true, use bigendian byte order for 16 bit samples.
* @param omitTail If true, the last trailing gap will be omitted.
* @param square if true, use a square wave for modulation, otherwise a sine.
* @param divide If true, divides the carrier frequency by 2, to be used with full-wave rectifiers, e.g. a pair of IR LEDs in anti-parallel.
* @throws IncompatibleArgumentException
*/
@SuppressWarnings("ValueOfIncrementOrDecrementUsed")
public Wave(double freq, double[] data,
int sampleFrequency, int sampleSize, int channels, boolean bigEndian,
boolean omitTail, boolean square, boolean divide)
throws IncompatibleArgumentException {
if (data == null || data.length == 0)
throw new IncompatibleArgumentException("Cannot create wave file from zero array.");
double sf = sampleFrequency/1000000.0;
int[] durationsInSamplePeriods = new int[omitTail ? data.length-1 : data.length];
int length = 0;
for (int i = 0; i < durationsInSamplePeriods.length; i++) {
durationsInSamplePeriods[i] = (int) Math.round(Math.abs(sf*data[i]));
length += durationsInSamplePeriods[i];
}
double c = sampleFrequency/freq;
buf = new byte[length*sampleSize/8*channels];
int index = 0;
for (int i = 0; i < data.length-1; i += 2) {
// Handle pulse, even index
for (int j = 0; j < durationsInSamplePeriods[i]; j++) {
double t = j/(divide ? 2*c : c);
double fraq = t - (int)t;
double s = square
? (fraq < 0.5 ? -1.0 : 1.0)
: Math.sin(2*Math.PI*(fraq));
if (sampleSize == 8) {
int val = (int) Math.round(Byte.MAX_VALUE*s);
buf[index++] = (byte) val;
if (channels == 2)
buf[index++] = (byte)-val;
} else {
int val = (int) Math.round(Short.MAX_VALUE*s);
byte low = (byte) (val & 0xFF);
byte high = (byte) (val >> 8);
buf[index++] = bigEndian ? high : low;
buf[index++] = bigEndian ? low : high;
if (channels == 2) {
val = -val;
low = (byte) (val & 0xFF);
high = (byte) (val >> 8);
buf[index++] = bigEndian ? high : low;
buf[index++] = bigEndian ? low : high;
}
}
}
// Gap, odd index
if (!omitTail || i < data.length - 2) {
for (int j = 0; j < durationsInSamplePeriods[i + 1]; j++) {
for (int ch = 0; ch < channels; ch++) {
buf[index++] = 0;
if (sampleSize == 16)
buf[index++] = 0;
}
}
}
}
audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleFrequency, sampleSize, channels, sampleSize/8*channels, sampleFrequency, bigEndian);
}
/**
* Generates a wave audio file from its arguments.
*
* @param irSequence ModulatedIrSequence to be used.
* @param sampleFrequency Sample frequency of the generated wave file.
* @param sampleSize Sample size (8 or 16) in bits of the samples.
* @param channels If == 2, generates two channels in perfect anti-phase.
* @param bigEndian if true, use bigendian byte order for 16 bit samples.
* @param omitTail If true, the last trailing gap will be omitted.
* @param square if true, use a square wave for modulation, otherwise a sine.
* @param divide If true, divides the carrier frequency by 2, to be used with full-wave rectifiers, e.g. a pair of IR LEDs in anti-parallel.
* @throws IncompatibleArgumentException
*/
public Wave(ModulatedIrSequence irSequence,
int sampleFrequency, int sampleSize, int channels, boolean bigEndian,
boolean omitTail, boolean square, boolean divide)
throws IncompatibleArgumentException {
this(irSequence.getFrequency(), irSequence.toDoubles(),
sampleFrequency, sampleSize, channels, bigEndian,
omitTail, square, divide);
}
/**
* Generates a wave audio file from its arguments.
*
* @param irSequence ModulatedIrSequence to be used.
* @param audioFormat AudioFormat bundling sampleFrequency, sample size, channels, and bigEndian together.
* @param omitTail If true, the last trailing gap will be omitted.
* @param square if true, use a square wave for modulation, otherwise a sine.
* @param divide If true, divides the carrier frequency by 2, to be used with full-wave rectifiers, e.g. a pair of IR LEDs in anti-parallel.
* @throws IncompatibleArgumentException
*/
public Wave(ModulatedIrSequence irSequence,
AudioFormat audioFormat,
boolean omitTail,
boolean square, boolean divide)
throws IncompatibleArgumentException {
this(irSequence,
(int) audioFormat.getSampleRate(), audioFormat.getSampleSizeInBits(),
audioFormat.getChannels(),
audioFormat.isBigEndian(),
omitTail, square, divide);
}
// set up integer data (left and right channel) from the byte array.
private int[][] computeData() {
int channels = audioFormat.getChannels();
int sampleSize = audioFormat.getSampleSizeInBits();
AudioFormat.Encoding encoding = audioFormat.getEncoding();
boolean bigEndian = audioFormat.isBigEndian();
int[][] data = new int[noFrames][channels];
if (encoding == AudioFormat.Encoding.PCM_UNSIGNED && sampleSize != 8) {
System.err.println("Case not yet implemented");
return null;
}
for (int frame = 0; frame < noFrames; frame++) {
if (sampleSize == 8) {
for (int ch = 0; ch < channels; ch++) {
int val = buf[channels*frame + ch];
if (encoding == AudioFormat.Encoding.PCM_UNSIGNED)
val += (val < 0) ? 128 : -128;
data[frame][ch] = val;
}
} else {
// sampleSize == 16
for (int ch = 0; ch < channels; ch++) {
int baseIndex = 2*(channels*frame + ch);
int high = buf[bigEndian ? baseIndex : baseIndex+1]; // may be negative
int low = buf[bigEndian ? baseIndex+1 : baseIndex]; // consider as unsigned
if (low < 0)
low += 256;
int value = 256*high + low;
data[frame][ch] = value;
}
}
}
return data;
}
/**
* Analyzes the data and computes a ModulatedIrSequence. Generates some messages on stderr.
*
* @param divide consider the carrier as having its frequency halved or not?
* @return ModulatedIrSequence computed from the data.
*/
public ModulatedIrSequence analyze(boolean divide) {
double sampleFrequency = audioFormat.getSampleRate();
int channels = audioFormat.getChannels();
System.err.println("Format is: " + audioFormat.toString() + ".");
System.err.println(String.format("%d frames = %7.6f seconds.", noFrames, noFrames/sampleFrequency));
int[][] data = computeData();
if (channels == 2) {
int noDiffPhase = 0;
int noDiffAntiphase = 0;
int noNonNulls = 0;
for (int i = 0; i < noFrames; i++) {
if (data[i][0] != 0 || data[i][1] != 0) { // do not count nulls
noNonNulls++;
if (data[i][0] != data[i][1])
noDiffPhase++;
if (data[i][0] != -data[i][1])
noDiffAntiphase++;
}
}
System.err.println("This is a 2-channel file. Left and right channel are "
+ (noDiffPhase == 0 ? "perfectly in phase."
: noDiffAntiphase == 0 ? "perfectly in antiphase."
: "neither completely in nor out of phase. Pairs in-phase:"
+ (noNonNulls - noDiffPhase) + ", pairs anti-phase: " + (noNonNulls - noDiffAntiphase)
+ " (out of " + noNonNulls + ")."));
System.err.println("Subsequent analysis will be base on the left channel exclusively.");
}
// Search the largest block of oscillations
ArrayList<Integer> durations = new ArrayList<>(noFrames);
int bestLength = -1; // length of longest block this far
int bestStart = -1;
boolean isInInterestingBlock = true;
int last = -1111111;
int epsilon = audioFormat.getSampleSizeInBits() == 8 ? epsilon8Bit : epsilon16Bit;
int firstNonNullIndex = 0; // Ignore leading silence, it is silly.
while (data[firstNonNullIndex][0] == 0)
firstNonNullIndex++;
if (firstNonNullIndex > 0)
System.err.println("The first " + firstNonNullIndex + " sample(s) are 0, ignored.");
int beg = firstNonNullIndex; // start of current block
for (int i = firstNonNullIndex; i < noFrames; i++) {
int value = data[i][0];
// two consecutive zeros -> interesting block ends
if (((Math.abs(value) <= epsilon && Math.abs(last) <= epsilon) || (i == noFrames - 1)) && isInInterestingBlock) {
isInInterestingBlock = false;
// evaluate just ended block
int currentLength = i - 1 - beg;
if (currentLength > bestLength) {
// longest this far
bestLength = currentLength;
bestStart = beg;
}
durations.add((int)Math.round(currentLength/sampleFrequency*1000000.0));
beg = i;
} else if (Math.abs(value) > epsilon && !isInInterestingBlock) {
// Interesting block starts
isInInterestingBlock = true;
int currentLength = i - 1 - beg;
durations.add((int) Math.round(currentLength/sampleFrequency*1000000.0));
beg = i;
}
last = value;
}
if (!isInInterestingBlock && noFrames - beg > 1)
durations.add((int)Math.round((noFrames - beg)/sampleFrequency*1000000.0));
if (durations.size() % 2 == 1)
durations.add(0);
// Found the longest interesting block, now evaluate frequency
int signchanges = 0;
last = 0;
for (int i = 0; i < bestLength; i++) {
int indx = i + bestStart;
int value = data[indx][0];
if (value != 0) {
if (value*last < 0)
signchanges++;
last = value;
}
}
double carrierFrequency = (divide ? 2 : 1)*sampleFrequency * signchanges/(2*bestLength);
System.err.println("Carrier frequency estimated to " + Math.round(carrierFrequency) + " Hz.");
int arr[] = new int[durations.size()];
int ind = 0;
for (Integer val : durations) {
arr[ind] = val;
ind++;
if (debug > 0)
System.err.print(val + " ");
}
if (debug > 0)
System.err.println();
try {
//return new IrSignal(arr, arr.length/2, 0, (int) Math.round(carrierFrequency));
return new ModulatedIrSequence(arr, carrierFrequency);
} catch (IncompatibleArgumentException ex) {
// cannot happen, we have insured that the data has even size.
return null;
}
}
/**
* Print the channels to a tab separated text file, for example for debugging purposes.
* This file can be imported in a spreadsheet.
*
* @param dumpfile Output file.
* @throws FileNotFoundException
*/
public void dump(File dumpfile) throws FileNotFoundException {
int data[][] = computeData();
double sampleRate = audioFormat.getSampleRate();
int channels = audioFormat.getChannels();
try (PrintStream stream = new PrintStream(dumpfile, IrpUtils.dumbCharsetName)) {
for (int i = 0; i < noFrames; i++) {
stream.print(String.format("%d\t%8.6f\t", i, i / sampleRate));
for (int ch = 0; ch < channels; ch++)
stream.print(data[i][ch] + (ch < channels - 1 ? "\t" : "\n"));
}
} catch (UnsupportedEncodingException ex) {
throw new InternalError();
}
}
/**
* Write the signal to the file given as argument.
* @param file Output File.
*/
public void export(File file) {
ByteArrayInputStream bs = new ByteArrayInputStream(buf);
bs.reset();
AudioInputStream ais = new AudioInputStream(bs, audioFormat, (long) buf.length/audioFormat.getFrameSize());
try {
int result = AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);
if (result <= buf.length)
System.err.println("Wrong number of bytes written: " + result + " < " + buf.length);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/**
* Sends the generated wave to the line in argument, if possible.
* @param line Line to used. Should be open, and remains open. User must make sure AudioFormat is compatible.
* @throws LineUnavailableException
* @throws IOException
*/
public void play(SourceDataLine line) throws LineUnavailableException, IOException {
line.start();
int bytesWritten = line.write(buf, 0, buf.length);
if (bytesWritten != buf.length)
throw new IOException("Not all bytes written");
line.drain();
}
/**
* Sends the generated wave to the local machine's audio system, if possible.
* @throws LineUnavailableException
* @throws IOException
*/
public void play() throws LineUnavailableException, IOException {
try (SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat)) {
line.open(audioFormat);
play(line);
}
}
private final static class CommandLineArgs {
@Parameter(names = {"-1", "--nodivide"}, description = "Do not divide modulation frequency")
boolean dontDivide = false;
@Parameter(names = {"-c", "--config"}, description = "Path to IrpProtocols.ini")
String irprotocolsIniFilename = "data/IrpProtocols.ini";
@Parameter(names = {"-h", "--help", "-?"}, description = "Display help message")
boolean helpRequensted = false;
@Parameter(names = {"-f", "--samplefrequency"}, description = "Sample frequency in Hz")
int sampleFrequency = 44100;
@Parameter(names = {"-m", "--macrofile"}, description = "Macro filename")
String macrofile = null;
@Parameter(names = {"-o", "--outfile"}, description = "Output filename")
String outputfile = "irpmaster.wav";
@Parameter(names = {"-p", "--play"}, description = "Send the generated wave to the audio device of the local machine")
boolean play = false;
@Parameter(names = {"-q", "--square"}, description = "Modulate with square wave instead of sine")
boolean square = false;
@Parameter(names = {"-r", "--repeats"}, description = "Number of times to include the repeat sequence")
int noRepeats = 0;
@Parameter(names = {"-s", "samplesize"}, description = "Sample size in bits")
int sampleSize = 8;
@Parameter(names = {"-S", "--stereo"}, description = "Generate two channels in anti-phase")
boolean stereo = false;
@Parameter(names = {"-t", "--omittail"}, description = "Skip silence at end")
boolean omitTail = false;
@Parameter(names = {"-v", "--version"}, description = "Display version information")
boolean versionRequested;
@Parameter(description = "[parameters]")
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private ArrayList<String> parameters = new ArrayList<>(64);
}
}
| gpl-3.0 |
avaire/orion | src/main/java/com/avairebot/imagegen/colors/ranks/MountainRangeColors.java | 1664 | /*
* Copyright (c) 2018.
*
* This file is part of AvaIre.
*
* AvaIre 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.
*
* AvaIre 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 AvaIre. If not, see <https://www.gnu.org/licenses/>.
*
*
*/
package com.avairebot.imagegen.colors.ranks;
import com.avairebot.contracts.imagegen.BackgroundRankColors;
import javax.annotation.Nonnull;
import java.awt.*;
public class MountainRangeColors extends BackgroundRankColors {
@Nonnull
@Override
public Color getBackgroundColor() {
return makeColor(55, 55, 70);
}
@Nonnull
@Override
public Color getMainTextColor() {
return makeColor(226, 226, 229, 85);
}
@Nonnull
@Override
public Color getSecondaryTextColor() {
return makeColor(166, 166, 166, 85);
}
@Nonnull
@Override
public Color getExperienceBackgroundColor() {
return makeColor(38, 39, 59, 60);
}
@Nonnull
@Override
public Color getExperienceForegroundColor() {
return makeColor(96, 132, 186, 80);
}
@Nonnull
@Override
public Color getExperienceSeparatorColor() {
return makeColor(83, 180, 201, 65);
}
}
| gpl-3.0 |
Tiketal/Overwatch | src/com/tiketal/overwatch/util/DisplayBar.java | 1427 | package com.tiketal.overwatch.util;
import org.bukkit.Bukkit;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player;
public class DisplayBar {
private BossBar bar;
public DisplayBar(String name, String color, String style) {
color = color.toUpperCase();
style = style.toUpperCase();
try {
bar = Bukkit.createBossBar(name, BarColor.valueOf(color), BarStyle.valueOf(style));
} catch (Exception e) {
bar = Bukkit.createBossBar(name, BarColor.WHITE, BarStyle.SOLID);
}
bar.setVisible(true);
}
public void show(Player player) {
bar.addPlayer(player);
}
public void hide(Player player) {
bar.removePlayer(player);
}
public void setTitle(String title) {
bar.setTitle(title);
}
public void setVisible(boolean visible) {
bar.setVisible(visible);
}
public void setColor(String color) {
try {
bar.setColor(BarColor.valueOf(color.toUpperCase()));
} catch (Exception e) {
bar.setColor(BarColor.WHITE);
}
}
public void setStyle(String style) {
try {
bar.setStyle(BarStyle.valueOf(style.toUpperCase()));
} catch (Exception e) {
bar.setStyle(BarStyle.SOLID);
}
}
public void progress(double amt) {
if (amt < 0) amt *= -1;
if (amt > 1) amt = 1;
bar.setProgress(amt);
}
public void reset() {
for (Player player : bar.getPlayers()) {
bar.removePlayer(player);
}
}
}
| gpl-3.0 |
demiurgosoft/star-droids | StarDroids/src/mapproject/Tile.java | 1477 | package mapproject;
import static helpers.Artist.*;
import org.newdawn.slick.opengl.Texture;
/**
* Clase que representa una celda individual del mapa
*
* @author Alba Ríos
*/
public class Tile {
private float x, y, width, height;
private Texture texture;
/**
*
* @param x Coordenada x del pixel del mapa
* @param y Coordenada y del pixel del mapa
* @param width Ancho del tile
* @param height Alto del tile
* @param tex Textura del tile
*
* @author Alba Ríos
*/
public Tile(float x, float y, float width, float height, Texture tex){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.texture = tex;
}
public void Draw(){
DrawQuadTex(texture, x, y, width, height);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public Texture getTexture() {
return texture;
}
public void setTexture(Texture texture) {
this.texture = texture;
}
}
| gpl-3.0 |
abmindiarepomanager/ABMOpenMainet | Mainet1.1/MainetServiceParent/MainetServiceAgency/src/main/java/com/abm/mainet/agency/dao/AgencyRegistrationProcessDao.java | 464 | package com.abm.mainet.agency.dao;
import com.abm.mainet.agency.dto.TPAgencyReqDTO;
import com.abm.mainet.agency.dto.TPAgencyResDTO;
import com.abm.mainet.common.domain.Employee;
/**
* @author Arun.Chavda
*
*/
public interface AgencyRegistrationProcessDao {
Employee saveAgnEmployeeDetails(Employee employee);
TPAgencyResDTO getAuthStatus(TPAgencyReqDTO requestDTO);
void updatedAuthStatus(Long empId, Long orgId, String flag);
}
| gpl-3.0 |
srnsw/xena | plugins/image/ext/src/w3c-svg/src/org/w3c/dom/svg/SVGUnitTypes.java | 281 |
package org.w3c.dom.svg;
public interface SVGUnitTypes {
// Unit Types
public static final short SVG_UNIT_TYPE_UNKNOWN = 0;
public static final short SVG_UNIT_TYPE_USERSPACEONUSE = 1;
public static final short SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2;
}
| gpl-3.0 |
teiniker/teiniker-lectures-securedesign | web-applications/access-control/session-management/Servlet-SessionManagement-ViewState/src/main/java/org/se/lab/ControllerServlet.java | 6040 | package org.se.lab;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
@WebServlet("/controller")
public class ControllerServlet extends HttpServlet
{
private final Logger LOG = Logger.getLogger(ControllerServlet.class);
private static final long serialVersionUID = 1L;
public ControllerServlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Controller
String message = "";
String state = "";
String action = request.getParameter("action");
if(action == null)
{
// do nothing
}
else if(action.equals("Login"))
{
LOG.info("> login");
state = listToString(new ArrayList<Product>());
message = "You logged in successfully!";
}
else if(action.equals("Logout"))
{
LOG.info("> logout");
state = "";
message = "You logged out successfully!";
}
else if(action.equals("Add"))
{
String name = request.getParameter("name");
String quantity = request.getParameter("quantity");
ArrayList<Product> cart = listFromString(request.getParameter("state"));
Product product = new Product(name, quantity);
LOG.info("> add " + product);
cart.add(product);
state = listToString(cart);
message = "added: " + product.getQuantity() + " " + product.getName() + " to the cart";
LOG.info("> cart: " + cart);
}
// generate response page
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String html = generateWebPage(state, message);
out.println(html);
out.close();
}
private String generateWebPage(String state, String message)
{
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
html.append("<html>\n");
html.append(" <head>\n");
html.append(" <title>Simple Shopping Cart</title>\n");
html.append(" </head>\n");
html.append(" <body>\n");
html.append(" <h2>Session Management</h2>\n");
html.append(" <form method=\"post\" action=\"controller\">");
html.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\"/>\n");
html.append(" <table border=\"0\" cellspacing=\"1\" cellpadding=\"5\">");
html.append(" <colgroup>");
html.append(" <col width=\"150\"> <col width=\"150\"> <col width=\"100\">");
html.append(" </colgroup>");
html.append(" <tr>");
html.append(" <th>");
html.append(" <input type=\"submit\" name=\"action\" value=\"Login\">");
html.append(" </th>");
html.append(" <th>");
html.append(" </th>");
html.append(" <th>");
html.append(" <input type=\"submit\" name=\"action\" value=\"Logout\">");
html.append(" </th>");
html.append(" </tr>");
html.append(" </table>");
html.append(" </form>");
html.append(" <p/>");
html.append(" <h2>Your Shopping Cart:</h2>\n");
html.append(" <form method=\"post\" action=\"controller\">");
html.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\"/>\n");
html.append(" <table border=\"0\" cellspacing=\"1\" cellpadding=\"5\">");
html.append(" <colgroup>");
html.append(" <col width=\"150\"> <col width=\"150\"> <col width=\"100\">");
html.append(" </colgroup>");
html.append(" <tr>");
html.append(" <th>Product</th>");
html.append(" <th>Quantity</th>");
html.append(" <th></th>");
html.append(" </tr>");
html.append(" <tr>");
html.append(" <td><input type = \"text\" name = \"name\" /></td>");
html.append(" <td><input type = \"text\" name = \"quantity\" /></td>");
html.append(" <td><input type = \"submit\" name = \"action\" value = \"Add\" /></td>");
html.append(" </tr>");
html.append(" </table>");
html.append(" </form>");
html.append(" <p/>");
html.append(" <p style=\"color:blue\"><i>" + message + "</i></p>");
html.append(" <p/>");
Date now = new Date();
html.append(" <h6>" + now + "</h6>");
return html.toString();
}
private String listToString(ArrayList<Product> list)
{
LOG.debug("listToString() " + list);
try
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(bout);
oos.writeObject(list);
oos.close();
byte[] bytes = bout.toByteArray();
// TODO: Encryption
return Base64.encodeBase64String(bytes);
}
catch (IOException e)
{
return "";
}
}
@SuppressWarnings("unchecked")
private ArrayList<Product> listFromString(String base64String)
{
LOG.debug("listFromString() " + base64String);
try
{
byte[] bytes = Base64.decodeBase64(base64String);
// Decrypt data
ArrayList<Product> list = new ArrayList<Product>();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
ObjectInputStream ois;
ois = new ObjectInputStream(bin);
list = (ArrayList<Product>) ois.readObject();
ois.close();
return list;
}
catch (IOException | ClassNotFoundException e)
{
return new ArrayList<Product>();
}
}
}
| gpl-3.0 |
cbuehler/freewrl | src/java/vrml/field/MFColor.java | 4431 | //AUTOMATICALLY GENERATED BY genfields.pl.
//DO NOT EDIT!!!!
package vrml.field;
import vrml.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class MFColor extends MField {
public MFColor() {
}
public MFColor(float[] colors) {
this(colors.length, colors);
}
public MFColor(int size, float[] colors) {
for (int i = 0; i < size; i += 3)
__vect.addElement(new ConstSFColor(colors[i], colors[i+1], colors[i+2]));
}
public MFColor(float[][] colors) {
for (int i = 0; i < colors.length; i++)
__vect.addElement(new ConstSFColor(colors[i][0], colors[i][1], colors[i][2]));
}
public void getValue(float[] colors) {
__updateRead();
int size = __vect.size();
for (int i = 0; i < size; i++) {
ConstSFColor sfColor = (ConstSFColor) __vect.elementAt(i);
colors[3*i+0] = sfColor.red;
colors[3*i+1] = sfColor.green;
colors[3*i+2] = sfColor.blue;
}
}
public void getValue(float[][] colors) {
__updateRead();
int size = __vect.size();
for (int i = 0; i < size; i++)
((ConstSFColor) __vect.elementAt(i)).getValue(colors[i]);
}
public void get1Value(int index, float[] colors) {
__update1Read(index);
((ConstSFColor) __vect.elementAt(index)).getValue(colors);
}
public void get1Value(int index, SFColor sfColor) {
__update1Read(index);
sfColor.setValue((ConstSFColor) __vect.elementAt(index));
}
public void setValue(float[] colors) {
setValue(colors.length, colors);
}
public void setValue(int size, float[] colors) {
__vect.clear();
for (int i = 0; i < size; i += 3)
__vect.addElement(new ConstSFColor(colors[i], colors[i+1], colors[i+2]));
__updateWrite();
}
public void set1Value(int index, float red, float green, float blue) {
__set1Value(index, new ConstSFColor(red, green, blue));
}
public void set1Value(int index, SFColor sfColor) {
sfColor.__updateRead();
__set1Value(index, new ConstSFColor(sfColor.red, sfColor.green, sfColor.blue));
}
public void set1Value(int index, ConstSFColor sfColor) {
__set1Value(index, sfColor);
}
public void addValue(float red, float green, float blue) {
__addValue(new ConstSFColor(red, green, blue));
}
public void addValue(SFColor sfColor) {
sfColor.__updateRead();
__addValue(new ConstSFColor(sfColor.red, sfColor.green, sfColor.blue));
}
public void addValue(ConstSFColor sfColor) {
__addValue(sfColor);
}
public void insertValue(int index, float red, float green, float blue) {
__insertValue(index, new ConstSFColor(red, green, blue));
}
public void insertValue(int index, SFColor sfColor) {
sfColor.__updateRead();
__insertValue(index, new ConstSFColor(sfColor.red, sfColor.green, sfColor.blue));
}
public void insertValue(int index, ConstSFColor sfColor) {
__insertValue(index, sfColor);
}
public String toString() {
__updateRead();
StringBuffer sb = new StringBuffer("[");
int size = __vect.size();
for (int i = 0; i < size; i++) {
if (i > 0) sb.append(", ");
sb.append(__vect.elementAt(i));
}
return sb.append("]").toString();
}
public void __fromPerl(BufferedReader in) throws IOException {
__vect.clear();
String lenline = in.readLine();
//System.out.println ("__fromPerl, read in length as " + lenline);
//int len = Integer.parseInt(in.readLine());
int len = Integer.parseInt(lenline);
for (int i = 0; i < len; i++) {
ConstSFColor sf = new ConstSFColor();
sf.__fromPerl(in);
__vect.addElement(sf);
}
}
public void __toPerl(PrintWriter out) throws IOException {
StringBuffer sb = new StringBuffer("");
int size = __vect.size();
//out.print(size);
for (int i = 0; i < size; i++) {
((ConstSFColor) __vect.elementAt(i)).__toPerl(out);
if (i != (size-1)) out.print (", ");
}
//out.println();
}
//public void setOffset(String offs) { this.offset = offs; } //JAS2
//public String getOffset() { return this.offset; } //JAS2
} | gpl-3.0 |
newa0/boamp-api-quickStart | src/main/gen/fr/gouv/api/Boamp_v230/EnumAvisImplique.java | 3154 | //
// Ce fichier a été généré par l'implémentation de référence JavaTM Architecture for XML Binding (JAXB), v2.2.11
// Voir <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Toute modification apportée à ce fichier sera perdue lors de la recompilation du schéma source.
// Généré le : 2017.09.18 à 11:31:40 AM CEST
//
package fr.gouv.api.Boamp_v230;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java pour EnumAvisImplique complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType name="EnumAvisImplique">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <element name="MARCHE_PUBLIC" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="ACCORD_CADRE" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* <element name="SAD" type="{http://www.w3.org/2001/XMLSchema}anyType"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EnumAvisImplique", propOrder = {
"marchepublic",
"accordcadre",
"sad"
})
public class EnumAvisImplique {
@XmlElement(name = "MARCHE_PUBLIC")
protected Object marchepublic;
@XmlElement(name = "ACCORD_CADRE")
protected Object accordcadre;
@XmlElement(name = "SAD")
protected Object sad;
/**
* Obtient la valeur de la propriété marchepublic.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getMARCHEPUBLIC() {
return marchepublic;
}
/**
* Définit la valeur de la propriété marchepublic.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setMARCHEPUBLIC(Object value) {
this.marchepublic = value;
}
/**
* Obtient la valeur de la propriété accordcadre.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getACCORDCADRE() {
return accordcadre;
}
/**
* Définit la valeur de la propriété accordcadre.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setACCORDCADRE(Object value) {
this.accordcadre = value;
}
/**
* Obtient la valeur de la propriété sad.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getSAD() {
return sad;
}
/**
* Définit la valeur de la propriété sad.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setSAD(Object value) {
this.sad = value;
}
}
| gpl-3.0 |
idega/platform2 | src/com/idega/block/trade/stockroom/business/ProductPriceException.java | 530 | package com.idega.block.trade.stockroom.business;
/**
* Title: IW Trade
* Description:
* Copyright: Copyright (c) 2001
* Company: idega.is
* @author 2000 - idega team - <br><a href="mailto:gummi@idega.is">Guðmundur Ágúst Sæmundsson</a><br><a href="mailto:gimmi@idega.is">Grímur Jónsson</a>
* @version 1.0
*/
public class ProductPriceException extends RuntimeException {
public ProductPriceException() {
super();
}
public ProductPriceException(String explanation){
super(explanation);
}
}
| gpl-3.0 |
StephaneMangin/Synth | src/main/java/org/istic/synthlab/core/modules/whitenoise/WhiteNoise.java | 1003 | package org.istic.synthlab.core.modules.whitenoise;
import org.istic.synthlab.components.IComponent;
import org.istic.synthlab.core.modules.io.IOutput;
import org.istic.synthlab.core.services.Factory;
import org.istic.synthlab.core.services.Register;
public class WhiteNoise implements IWhiteNoise {
private com.jsyn.unitgen.WhiteNoise whiteNoise;
private IOutput output;
public WhiteNoise(IComponent component) {
super();
whiteNoise = new com.jsyn.unitgen.WhiteNoise();
Register.declare(component, whiteNoise);
whiteNoise.output.setName("noise_output");
output = Factory.createOutput("Out", component, this.whiteNoise.output);
}
@Override
public IOutput getOutput() {
return this.output;
}
public void activate() {
whiteNoise.setEnabled(true);
}
public void deactivate() {
whiteNoise.setEnabled(false);
}
public boolean isActivated() {
return whiteNoise.isEnabled();
}
} | gpl-3.0 |
kc8hfi/mygolfcart | dev/java/src/networkRead.java | 1860 | import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class networkRead implements Runnable
{
//Objects
Scanner read;
debugLogger myLogger;
sharedData myData;
arduinoWrite ardWriter;
Socket pipe;
//Variables
String data;
long startTime;
long endTime;
boolean dead = false;
public networkRead(Socket tempSocket, sharedData tempData, debugLogger tempLog, arduinoWrite tempWriter)
{
pipe = tempSocket;
myData = tempData;
myLogger = tempLog;
ardWriter = tempWriter;
try
{
read = new Scanner(tempSocket.getInputStream());
}
catch (IOException e)
{
myLogger.writeLog("ERROR: Failure to write to network socket!");
myLogger.writeLog("\n\n");
e.printStackTrace();
myLogger.writeLog("\n\n");
}
}
public void run()
{
data = "myData";
startTime = System.currentTimeMillis();
endTime = startTime + 2000;
while (myData.getAlive())
{
if(pipe.isConnected())
{
if(read.hasNextLine())
{
//Read data
data = read.nextLine();
data = data.trim();
//Store Data in shared object
myData.setReadNet(data);
//Log the input
myLogger.writeLog("Read From Server: \t" + data);
//Pass input to arduino
ardWriter.writeToSerial(data);
}
}
if(data.equals("ping"))
{
startTime = System.currentTimeMillis();
endTime = startTime + 2000;
}
keepAlive();
data = "";
}
ardWriter.writeToSerial("BB");
ardWriter.writeToSerial("EVF");
ardWriter.writeToSerial("OFF");
myLogger.writeLog("CRITICAL: CONNECTION LOST!");
}
public void keepAlive()
{
long temp = System.currentTimeMillis();
if((temp >endTime))
{
myData.setAliveArd(false);
myData.setAliveNet(false);
}
}
}
| gpl-3.0 |
davenpcj5542009/eucalyptus | clc/modules/dns/src/main/java/com/eucalyptus/cloud/ws/ConnectionHandler.java | 17449 | /*************************************************************************
* Copyright 2009-2014 Eucalyptus Systems, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3 of the License.
*
* 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/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software 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.
*
* 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. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Copyright (c) 1999-2004, Brian Wellington.
* 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.
*
* 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 HOLDER 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.
************************************************************************/
package com.eucalyptus.cloud.ws;
import static com.eucalyptus.util.dns.DnsResolvers.DnsRequest;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import org.xbill.DNS.CNAMERecord;
import org.xbill.DNS.Credibility;
import org.xbill.DNS.DClass;
import org.xbill.DNS.DNAMERecord;
import org.xbill.DNS.ExtendedFlags;
import org.xbill.DNS.Flags;
import org.xbill.DNS.Header;
import org.xbill.DNS.Message;
import org.xbill.DNS.Name;
import org.xbill.DNS.NameTooLongException;
import org.xbill.DNS.OPTRecord;
import org.xbill.DNS.Opcode;
import org.xbill.DNS.RRset;
import org.xbill.DNS.Rcode;
import org.xbill.DNS.Record;
import org.xbill.DNS.Section;
import org.xbill.DNS.SetResponse;
import org.xbill.DNS.TSIG;
import org.xbill.DNS.TSIGRecord;
import org.xbill.DNS.Type;
import com.eucalyptus.dns.Zone;
import com.eucalyptus.dns.Cache;
import com.eucalyptus.util.Pair;
import com.eucalyptus.util.dns.DnsResolvers;
import com.google.common.base.Function;
import com.google.common.base.Optional;
public class ConnectionHandler extends Thread {
static final int FLAG_DNSSECOK = 1;
static final int FLAG_SIGONLY = 2;
Map caches = new ConcurrentHashMap();
//Map TSIGs;
byte []
generateReply(Message query, byte [] in, int length, Socket s)
throws IOException
{
Header header;
boolean badversion;
int maxLength;
boolean sigonly;
SetResponse sr;
int flags = 0;
header = query.getHeader();
// if (header.getFlag(Flags.QR))
// return null;
if (header.getRcode() != Rcode.NOERROR)
return errorMessage(query, Rcode.FORMERR);
if (header.getOpcode() != Opcode.QUERY)
return errorMessage(query, Rcode.NOTIMP);
Record queryRecord = query.getQuestion();
TSIGRecord queryTSIG = query.getTSIG();
TSIG tsig = null;
/* if (queryTSIG != null) {
tsig = (TSIG) TSIGs.get(queryTSIG.getName());
if (tsig == null ||
tsig.verify(query, in, length, null) != Rcode.NOERROR)
return formerrMessage(in);
}*/
OPTRecord queryOPT = query.getOPT();
if (queryOPT != null && queryOPT.getVersion() > 0)
badversion = true;
if (s != null)
maxLength = 65535;
else if (queryOPT != null)
maxLength = Math.max(queryOPT.getPayloadSize(), 512);
else
maxLength = 512;
if (queryOPT != null && (queryOPT.getFlags() & ExtendedFlags.DO) != 0)
flags = FLAG_DNSSECOK;
Message response = new Message(query.getHeader().getID());
response.getHeader().setFlag(Flags.QR);
if (query.getHeader().getFlag(Flags.RD))
response.getHeader().setFlag(Flags.RD);
if(queryRecord != null) {
response.addRecord(queryRecord, Section.QUESTION);
Name name = queryRecord.getName();
int type = queryRecord.getType();
int dclass = queryRecord.getDClass();
/* if (type == Type.AXFR && s != null)
return doAXFR(name, query, tsig, queryTSIG, s);
*/ if (!Type.isRR(type) && type != Type.ANY)
return errorMessage(query, Rcode.NOTIMP);
byte rcode = addAnswer(response, name, type, dclass, 0, flags);
if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN)
return errorMessage(query, Rcode.SERVFAIL);
addAdditional(response, type, flags);
if (queryOPT != null) {
int optflags = (flags == FLAG_DNSSECOK) ? ExtendedFlags.DO : 0;
OPTRecord opt = new OPTRecord((short)4096, rcode, (byte)0, optflags);
response.addRecord(opt, Section.ADDITIONAL);
}
}
response.setTSIG(tsig, Rcode.NOERROR, queryTSIG);
return response.toWire(maxLength);
}
public Zone
findBestZone(Name name) {
Zone foundzone = null;
int labels = name.labels();
for (int i = 1; i < labels; i++) {
Name tname = new Name(name, i);
foundzone = (Zone) ZoneManager.getZone(tname);
if (foundzone != null)
return foundzone;
}
return null;
}
public RRset
findExactMatch(Name name, int type, int dclass, boolean glue) {
Zone zone = findBestZone(name);
if (zone != null)
return zone.findExactMatch(name, type);
else {
RRset [] rrsets;
Cache cache = getCache(dclass);
if (glue)
rrsets = cache.findAnyRecords(name, type);
else
rrsets = cache.findRecords(name, type);
if (rrsets == null)
return null;
else
return rrsets[0]; /* not quite right */
}
}
private void
addGlue(Message response, Name name, int type, int flags) {
RRset a = findExactMatch(name, type, DClass.IN, true);
if (a == null)
return;
addRRset(name, response, a, Section.ADDITIONAL, flags);
}
private void
addAdditional2(Message response, int section, int type, int flags) {
Record [] records = response.getSectionArray(section);
for (int i = 0; i < records.length; i++) {
Record r = records[i];
Name glueName = r.getAdditionalName();
if (glueName != null)
addGlue(response, glueName, type, flags);
}
}
private final void
addAdditional(Message response, int type, int flags) {
addAdditional2(response, Section.ANSWER, type, flags);
addAdditional2(response, Section.AUTHORITY, type, flags);
}
byte
addAnswer( final Message response, Name name, int type, int dclass,
int iterations, int flags)
{
SetResponse sr;
byte rcode = Rcode.NOERROR;
if (iterations > 6)
return Rcode.NOERROR;
if (type == Type.SIG || type == Type.RRSIG) {
type = Type.ANY;
flags |= FLAG_SIGONLY;
}
try {
sr = DnsResolvers.findRecords( response, new DnsRequest() {
@Override public Record getQuery() { return response.getQuestion( ); }
@Override public InetAddress getLocalAddress() { return ConnectionHandler.getLocalInetAddress(); }
@Override public InetAddress getRemoteAddress() { return ConnectionHandler.getRemoteInetAddress(); }
} );
if ( sr != null ) {
if ( sr.isSuccessful( ) ) {
return Rcode.NOERROR;
} else if ( sr.isNXDOMAIN( ) ) {
return Rcode.NXDOMAIN;
}
}
} catch ( Exception ex ) {
Logger.getLogger( DnsResolvers.class ).error( ex );
}
Zone zone = findBestZone(name);
if (zone != null) {
if (type == Type.AAAA) {
addSOA(response, zone);
response.getHeader().setFlag(Flags.AA);
return (Rcode.NOERROR);
}
sr = zone.findRecords(name, type, getLocalInetAddress( ));
}
else {
Cache cache = getCache(dclass);
sr = cache.lookupRecords(name, type, Credibility.NORMAL);
}
if (sr.isUnknown()) {
return (Rcode.SERVFAIL);
}
if (sr.isNXDOMAIN()) {
response.getHeader().setRcode(Rcode.NXDOMAIN);
if (zone != null) {
addSOA(response, zone);
if (iterations == 0)
response.getHeader().setFlag(Flags.AA);
}
rcode = Rcode.NXDOMAIN;
}
else if (sr.isNXRRSET()) {
if (zone != null) {
addSOA(response, zone);
if (iterations == 0)
response.getHeader().setFlag(Flags.AA);
}
}
else if (sr.isDelegation()) {
RRset nsRecords = sr.getNS();
addRRset(nsRecords.getName(), response, nsRecords,
Section.AUTHORITY, flags);
}
else if (sr.isCNAME()) {
CNAMERecord cname = sr.getCNAME();
RRset rrset = new RRset(cname);
addRRset(name, response, rrset, Section.ANSWER, flags);
if (zone != null && iterations == 0)
response.getHeader().setFlag(Flags.AA);
rcode = addAnswer(response, cname.getTarget(),
type, dclass, iterations + 1, flags);
}
else if (sr.isDNAME()) {
DNAMERecord dname = sr.getDNAME();
RRset rrset = new RRset(dname);
addRRset(name, response, rrset, Section.ANSWER, flags);
Name newname;
try {
newname = name.fromDNAME(dname);
}
catch (NameTooLongException e) {
return Rcode.YXDOMAIN;
}
if(newname != null) {
rrset = new RRset(new CNAMERecord(name, dclass, 0, newname));
addRRset(name, response, rrset, Section.ANSWER, flags);
if (zone != null && iterations == 0)
response.getHeader().setFlag(Flags.AA);
rcode = addAnswer(response, newname, type, dclass, iterations + 1, flags);
}
}
else if (sr.isSuccessful()) {
RRset [] rrsets = sr.answers();
if(rrsets != null) {
for (int i = 0; i < rrsets.length; i++)
addRRset(name, response, rrsets[i], Section.ANSWER, flags);
}
if (zone != null) {
addNS(response, zone, flags);
if (iterations == 0)
response.getHeader().setFlag(Flags.AA);
}
else
addCacheNS(response, getCache(dclass), name);
}
return rcode;
}
private final void
addSOA(Message response, Zone zone) {
response.addRecord(zone.getSOA(), Section.AUTHORITY);
}
private final void
addNS(Message response, Zone zone, int flags) {
RRset nsRecords = zone.getNS();
addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags);
}
private final void
addCacheNS(Message response, Cache cache, Name name) {
SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT);
if (!sr.isDelegation())
return;
RRset nsRecords = sr.getNS();
Iterator it = nsRecords.rrs();
while (it.hasNext()) {
Record r = (Record) it.next();
response.addRecord(r, Section.AUTHORITY);
}
}
byte []
doAXFR(Name name, Message query, TSIG tsig, TSIGRecord qtsig, Socket s) {
Zone zone = (Zone) ZoneManager.getZone(name);
boolean first = true;
if (zone == null)
return errorMessage(query, Rcode.REFUSED);
Iterator it = zone.AXFR();
try {
DataOutputStream dataOut;
dataOut = new DataOutputStream(s.getOutputStream());
int id = query.getHeader().getID();
while (it.hasNext()) {
RRset rrset = (RRset) it.next();
Message response = new Message(id);
Header header = response.getHeader();
header.setFlag(Flags.QR);
header.setFlag(Flags.AA);
addRRset(rrset.getName(), response, rrset,
Section.ANSWER, FLAG_DNSSECOK);
if (tsig != null) {
tsig.applyStream(response, qtsig, first);
qtsig = response.getTSIG();
}
first = false;
byte [] out = response.toWire();
dataOut.writeShort(out.length);
dataOut.write(out);
}
}
catch (IOException ex) {
System.out.println("AXFR failed");
}
try {
s.close();
}
catch (IOException ex) {
}
return null;
}
void
addRRset(Name name, Message response, RRset rrset, int section, int flags) {
for (int s = 1; s <= section; s++)
if (response.findRRset(name, rrset.getType(), s))
return;
if ((flags & FLAG_SIGONLY) == 0) {
Iterator it = rrset.rrs();
while (it.hasNext()) {
Record r = (Record) it.next();
if (r.getName().isWild() && !name.isWild())
r = r.withName(name);
response.addRecord(r, section);
}
}
if ((flags & (FLAG_SIGONLY | FLAG_DNSSECOK)) != 0) {
Iterator it = rrset.sigs();
while (it.hasNext()) {
Record r = (Record) it.next();
if (r.getName().isWild() && !name.isWild())
r = r.withName(name);
response.addRecord(r, section);
}
}
}
byte []
buildErrorMessage(Header header, int rcode, Record question) {
Message response = new Message();
response.setHeader(header);
for (int i = 0; i < 4; i++)
response.removeAllRecords(i);
if (rcode == Rcode.SERVFAIL)
response.addRecord(question, Section.QUESTION);
header.setRcode(rcode);
return response.toWire();
}
public byte []
errorMessage(Message query, int rcode) {
return buildErrorMessage(query.getHeader(), rcode,
query.getQuestion());
}
public byte []
formerrMessage(byte [] in) {
Header header;
try {
header = new Header(in);
}
catch (IOException e) {
return null;
}
return buildErrorMessage(header, Rcode.FORMERR, null);
}
public Cache
getCache(int dclass) {
Cache c = (Cache) caches.get(new Integer(dclass));
if (c == null) {
c = new Cache(dclass);
caches.put(new Integer(dclass), c);
}
return c;
}
private static final ThreadLocal<Pair<InetAddress,InetAddress>> localAndRemoteInetAddresses = new ThreadLocal<>();
private static InetAddress getInetAddress( final Function<Pair<InetAddress,InetAddress>,InetAddress> extractor ) {
return Optional.fromNullable( localAndRemoteInetAddresses.get( ) ).transform( extractor ).orNull( );
}
static InetAddress getLocalInetAddress( ) {
return getInetAddress( Pair.<InetAddress,InetAddress>left( ) );
}
static InetAddress getRemoteInetAddress( ) {
return getInetAddress( Pair.<InetAddress, InetAddress>right() );
}
static void setLocalAndRemoteInetAddresses( InetAddress local, InetAddress remote ) {
ConnectionHandler.localAndRemoteInetAddresses.set( Pair.pair( local, remote ) );
}
static void clearInetAddresses( ) {
ConnectionHandler.localAndRemoteInetAddresses.remove( );
}
}
| gpl-3.0 |
headissue/cache2k | cache2k-core/src/main/java/org/cache2k/core/CommonMetricsFactory.java | 947 | package org.cache2k.core;
/*
* #%L
* cache2k core implementation
* %%
* Copyright (C) 2000 - 2021 headissue GmbH, Munich
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.cache2k.core.api.CommonMetrics;
/**
* @author Jens Wilke
*/
public interface CommonMetricsFactory {
CommonMetrics.Updater create(Parameters p);
interface Parameters {
boolean isDisabled();
boolean isPrecise();
}
}
| gpl-3.0 |
fanruan/finereport-design | designer_base/src/com/fr/design/beans/FurtherBasicBeanPane.java | 656 | package com.fr.design.beans;
import com.fr.stable.StringUtils;
/**
*
* @author zhou
* @since 2012-5-30下午12:12:42
*/
public abstract class FurtherBasicBeanPane<T> extends BasicBeanPane<T> {
/**
* 是否是指定类型
* @param ob 对象
* @return 是否是指定类型
*/
public abstract boolean accept(Object ob);
/**
* title应该是一个属性,不只是对话框的标题时用到,与其他组件结合时,也会用得到
* @return 绥化狂标题
*/
@Deprecated
public String title4PopupWindow(){
return StringUtils.EMPTY;
}
/**
* 重置
*/
public abstract void reset();
} | gpl-3.0 |
dmfs/jdav-client | src/org/dmfs/davclient/rfc7231/HttpOptions.java | 947 | /*
* Copyright (C) 2015 Marten Gajda <marten@dmfs.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package org.dmfs.davclient.rfc7231;
import org.dmfs.httpclientinterfaces.IHttpResponse;
public class HttpOptions
{
public HttpOptions(IHttpResponse response)
{
}
}
| gpl-3.0 |
YixingHuang/CONRAD | src/edu/stanford/rsl/conrad/numerics/DecompositionSVD.java | 14143 | package edu.stanford.rsl.conrad.numerics;
import Jama.Matrix;
import Jama.util.*;
/** Singular Value Decomposition.
<P>
For an m-by-n matrix A, the singular value decomposition is
an m-by-(m or n) orthogonal matrix U, a (m or n)-by-n diagonal matrix S, and
an n-by-n orthogonal matrix V so that A = U*S*V'.
<P>
The singular values, sigma[k] = S[k][k], are ordered so that
sigma[0] >= sigma[1] >= ... >= sigma[n-1].
<P>
The singular value decompostion always exists, so the constructor will
never fail. The matrix condition number and the effective numerical
rank can be computed from this decomposition.
<P>
This class is mainly based on SingularValueDecomposition class in Jama in which
SVD sometimes fails on cases m < n. The bug has been fixed by Ron Boisvert <boisvert@nist.gov>.
Details of what were fixed can be found below:
http://cio.nist.gov/esd/emaildir/lists/jama/msg01431.html
http://cio.nist.gov/esd/emaildir/lists/jama/msg01430.html
http://metamerist.blogspot.com/2008/04/svd-for-vertically-challenged.html
Then, small changes were made to be compatible with CONRAD.
@author Jang-Hwan Choi
*/
public class DecompositionSVD implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 201880439875521920L;
/* ------------------------
Class variables
* ------------------------ */
/** Arrays for internal storage of U and V.
@serial internal storage of U.
@serial internal storage of V.
*/
private double[][] U, V;
/** Array for internal storage of singular values.
@serial internal storage of singular values.
*/
private double[] s;
/** Row and column dimensions.
@serial row dimension.
@serial column dimension.
@serial U column dimension.
*/
private int m, n, ncu;
/** Column specification of matrix U
@serial U column dimension toggle
*/
private boolean thin;
/**
* <b>Old Constructor</b><br>
* Construct the singular value decomposition
* Structure to access U, S and V.
* @param Arg Rectangular matrix
*
*/
public DecompositionSVD (SimpleMatrix Arg) {
this(Arg,true,true,true);
}
/* ------------------------
Constructor
* ------------------------ */
/**
* Construct the singular value decomposition, i.e. a
* structure to access U, S and V.
* @param Arg Rectangular matrix
* @param thin If true U is economy sized
* @param wantu If true generate the U matrix
* @param wantv If true generate the V matrix
*
*/
public DecompositionSVD (SimpleMatrix Arg, boolean thin, boolean wantu,
boolean wantv) {
// Derived from LINPACK code.
// Initialize.
double[][] A = Arg.copyAsDoubleArray();
m = Arg.getRows();
n = Arg.getCols();
this.thin = thin;
ncu = thin?Math.min(m,n):m;
s = new double [Math.min(m+1,n)];
if (wantu) U = new double [m][ncu];
if (wantv) V = new double [n][n];
double[] e = new double [n];
double[] work = new double [m];
// Reduce A to bidiagonal form, storing the diagonal elements
// in s and the super-diagonal elements in e.
int nct = Math.min(m-1,n);
int nrt = Math.max(0,Math.min(n-2,m));
int lu = Math.max(nct,nrt);
for (int k = 0; k < lu; k++) {
if (k < nct) {
// Compute the transformation for the k-th column and
// place the k-th diagonal in s[k].
// Compute 2-norm of k-th column without under/overflow.
s[k] = 0;
for (int i = k; i < m; i++) {
s[k] = Maths.hypot(s[k],A[i][k]);
}
if (s[k] != 0.0) {
if (A[k][k] < 0.0) {
s[k] = -s[k];
}
for (int i = k; i < m; i++) {
A[i][k] /= s[k];
}
A[k][k] += 1.0;
}
s[k] = -s[k];
}
for (int j = k+1; j < n; j++) {
if ((k < nct) & (s[k] != 0.0)) {
// Apply the transformation.
double t = 0;
for (int i = k; i < m; i++) {
t += A[i][k]*A[i][j];
}
t = -t/A[k][k];
for (int i = k; i < m; i++) {
A[i][j] += t*A[i][k];
}
}
// Place the k-th row of A into e for the
// subsequent calculation of the row transformation.
e[j] = A[k][j];
}
if (wantu & (k < nct)) {
// Place the transformation in U for subsequent back
// multiplication.
for (int i = k; i < m; i++) {
U[i][k] = A[i][k];
}
}
if (k < nrt) {
// Compute the k-th row transformation and place the
// k-th super-diagonal in e[k].
// Compute 2-norm without under/overflow.
e[k] = 0;
for (int i = k+1; i < n; i++) {
e[k] = Maths.hypot(e[k],e[i]);
}
if (e[k] != 0.0) {
if (e[k+1] < 0.0) {
e[k] = -e[k];
}
for (int i = k+1; i < n; i++) {
e[i] /= e[k];
}
e[k+1] += 1.0;
}
e[k] = -e[k];
if ((k+1 < m) & (e[k] != 0.0)) {
// Apply the transformation.
for (int i = k+1; i < m; i++) {
work[i] = 0.0;
}
for (int j = k+1; j < n; j++) {
for (int i = k+1; i < m; i++) {
work[i] += e[j]*A[i][j];
}
}
for (int j = k+1; j < n; j++) {
double t = -e[j]/e[k+1];
for (int i = k+1; i < m; i++) {
A[i][j] += t*work[i];
}
}
}
if (wantv) {
// Place the transformation in V for subsequent
// back multiplication.
for (int i = k+1; i < n; i++) {
V[i][k] = e[i];
}
}
}
}
// Set up the final bidiagonal matrix or order p.
int p = Math.min(n,m+1);
if (nct < n) {
s[nct] = A[nct][nct];
}
if (m < p) {
s[p-1] = 0.0;
}
if (nrt+1 < p) {
e[nrt] = A[nrt][p-1];
}
e[p-1] = 0.0;
// If required, generate U.
if (wantu) {
for (int j = nct; j < ncu; j++) {
for (int i = 0; i < m; i++) {
U[i][j] = 0.0;
}
U[j][j] = 1.0;
}
for (int k = nct-1; k >= 0; k--) {
if (s[k] != 0.0) {
for (int j = k+1; j < ncu; j++) {
double t = 0;
for (int i = k; i < m; i++) {
t += U[i][k]*U[i][j];
}
t = -t/U[k][k];
for (int i = k; i < m; i++) {
U[i][j] += t*U[i][k];
}
}
for (int i = k; i < m; i++ ) {
U[i][k] = -U[i][k];
}
U[k][k] += 1.0;
for (int i = 0; i < k-1; i++) {
U[i][k] = 0.0;
}
} else {
for (int i = 0; i < m; i++) {
U[i][k] = 0.0;
}
U[k][k] = 1.0;
}
}
}
// If required, generate V.
if (wantv) {
for (int k = n-1; k >= 0; k--) {
if ((k < nrt) & (e[k] != 0.0)) {
for (int j = k+1; j < n; j++) {
double t = 0;
for (int i = k+1; i < n; i++) {
t += V[i][k]*V[i][j];
}
t = -t/V[k+1][k];
for (int i = k+1; i < n; i++) {
V[i][j] += t*V[i][k];
}
}
}
for (int i = 0; i < n; i++) {
V[i][k] = 0.0;
}
V[k][k] = 1.0;
}
}
// Main iteration loop for the singular values.
int pp = p-1;
int iter = 0;
double eps = Math.pow(2.0,-52.0);
double tiny = Math.pow(2.0,-966.0);
while (p > 0) {
int k,kase;
// Here is where a test for too many iterations would go.
// This section of the program inspects for
// negligible elements in the s and e arrays. On
// completion the variables kase and k are set as follows.
// kase = 1 if s(p) and e[k-1] are negligible and k<p
// kase = 2 if s(k) is negligible and k<p
// kase = 3 if e[k-1] is negligible, k<p, and
// s(k), ..., s(p) are not negligible (qr step).
// kase = 4 if e(p-1) is negligible (convergence).
for (k = p-2; k >= -1; k--) {
if (k == -1) {
break;
}
if (Math.abs(e[k]) <=
tiny + eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) {
e[k] = 0.0;
break;
}
}
if (k == p-2) {
kase = 4;
} else {
int ks;
for (ks = p-1; ks >= k; ks--) {
if (ks == k) {
break;
}
double t = (ks != p ? Math.abs(e[ks]) : 0.) +
(ks != k+1 ? Math.abs(e[ks-1]) : 0.);
if (Math.abs(s[ks]) <= tiny + eps*t) {
s[ks] = 0.0;
break;
}
}
if (ks == k) {
kase = 3;
} else if (ks == p-1) {
kase = 1;
} else {
kase = 2;
k = ks;
}
}
k++;
// Perform the task indicated by kase.
switch (kase) {
// Deflate negligible s(p).
case 1: {
double f = e[p-2];
e[p-2] = 0.0;
for (int j = p-2; j >= k; j--) {
double t = Maths.hypot(s[j],f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
if (j != k) {
f = -sn*e[j-1];
e[j-1] = cs*e[j-1];
}
if (wantv) {
for (int i = 0; i < n; i++) {
t = cs*V[i][j] + sn*V[i][p-1];
V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1];
V[i][j] = t;
}
}
}
}
break;
// Split at negligible s(k).
case 2: {
double f = e[k-1];
e[k-1] = 0.0;
for (int j = k; j < p; j++) {
double t = Maths.hypot(s[j],f);
double cs = s[j]/t;
double sn = f/t;
s[j] = t;
f = -sn*e[j];
e[j] = cs*e[j];
if (wantu) {
for (int i = 0; i < m; i++) {
t = cs*U[i][j] + sn*U[i][k-1];
U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1];
U[i][j] = t;
}
}
}
}
break;
// Perform one qr step.
case 3: {
// Calculate the shift.
double scale = Math.max(Math.max(Math.max(Math.max(
Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])),
Math.abs(s[k])),Math.abs(e[k]));
double sp = s[p-1]/scale;
double spm1 = s[p-2]/scale;
double epm1 = e[p-2]/scale;
double sk = s[k]/scale;
double ek = e[k]/scale;
double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
double c = (sp*epm1)*(sp*epm1);
double shift = 0.0;
if ((b != 0.0) | (c != 0.0)) {
shift = Math.sqrt(b*b + c);
if (b < 0.0) {
shift = -shift;
}
shift = c/(b + shift);
}
double f = (sk + sp)*(sk - sp) + shift;
double g = sk*ek;
// Chase zeros.
for (int j = k; j < p-1; j++) {
double t = Maths.hypot(f,g);
double cs = f/t;
double sn = g/t;
if (j != k) {
e[j-1] = t;
}
f = cs*s[j] + sn*e[j];
e[j] = cs*e[j] - sn*s[j];
g = sn*s[j+1];
s[j+1] = cs*s[j+1];
if (wantv) {
for (int i = 0; i < n; i++) {
t = cs*V[i][j] + sn*V[i][j+1];
V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1];
V[i][j] = t;
}
}
t = Maths.hypot(f,g);
cs = f/t;
sn = g/t;
s[j] = t;
f = cs*e[j] + sn*s[j+1];
s[j+1] = -sn*e[j] + cs*s[j+1];
g = sn*e[j+1];
e[j+1] = cs*e[j+1];
if (wantu && (j < m-1)) {
for (int i = 0; i < m; i++) {
t = cs*U[i][j] + sn*U[i][j+1];
U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1];
U[i][j] = t;
}
}
}
e[p-2] = f;
iter++;
}
break;
// Convergence.
case 4: {
// Make the singular values positive.
if (s[k] <= 0.0) {
s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
if (wantv) {
for (int i = 0; i < n; i++) {
V[i][k] = -V[i][k];
}
}
}
// Order the singular values.
while (k < pp) {
if (s[k] >= s[k+1]) {
break;
}
double t = s[k];
s[k] = s[k+1];
s[k+1] = t;
if (wantv && (k < n-1)) {
for (int i = 0; i < n; i++) {
t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t;
}
}
if (wantu && (k < m-1)) {
for (int i = 0; i < m; i++) {
t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t;
}
}
k++;
}
iter = 0;
p--;
}
break;
}
}
A = null;
}
/* ------------------------
Public Methods
* ------------------------ */
/** Return the left singular vectors
@return U
*/
public SimpleMatrix getU () {
return U==null?null:(new SimpleMatrix(new Matrix(U,m,m>=n?(thin?Math.min(m+1,n):ncu):ncu)));
}
/** Return the right singular vectors
@return V
*/
public SimpleMatrix getV () {
return V==null?null:new SimpleMatrix(new Matrix(V,n,n));
}
/** Return the one-dimensional array of singular values
@return diagonal of S.
*/
public double[] getSingularValues () {
return s;
}
/** Return the diagonal matrix of singular values
@return S
*/
public SimpleMatrix getS () {
SimpleMatrix X = new SimpleMatrix(new Matrix(m>=n?(thin?n:ncu):ncu,n));
for (int i = Math.min(m,n)-1; i>=0; i--)
X.setElementValue(i, i, s[i]);
return X;
}
/** Return the diagonal matrix of the reciprocals of the singular values
@return S+
*/
public SimpleMatrix getreciprocalS () {
SimpleMatrix X = new SimpleMatrix(new Matrix(n,m>=n?(thin?n:ncu):ncu));
for (int i = Math.min(m,n)-1; i>=0; i--)
X.setElementValue(i, i, s[i]==0.0?0.0:1.0/s[i]);
return X;
}
/** Return the Moore-Penrose (generalized) inverse
* Slightly modified version of Kim van der Linde's code
@param omit if true tolerance based omitting of negligible singular values
@return A+
*/
public SimpleMatrix inverse(boolean omit) {
double[][] inverse = new double[n][m];
if(rank()> 0) {
double[] reciprocalS = new double[s.length];
if (omit) {
double tol = Math.max(m,n)*s[0]*Math.pow(2.0,-52.0);
for (int i = s.length-1;i>=0;i--)
reciprocalS[i] = Math.abs(s[i])<tol?0.0:1.0/s[i];
}
else
for (int i=s.length-1;i>=0;i--)
reciprocalS[i] = s[i]==0.0?0.0:1.0/s[i];
int min = Math.min(n, ncu);
for (int i = n-1; i >= 0; i--)
for (int j = m-1; j >= 0; j--)
for (int k = min-1; k >= 0; k--)
inverse[i][j] += V[i][k] * reciprocalS[k] * U[j][k];
}
return new SimpleMatrix(new Matrix(inverse));
}
/** Two norm
@return max(S)
*/
public double norm2 () {
return s[0];
}
/** Two norm condition number
@return max(S)/min(S)
*/
public double cond () {
return s[0]/s[Math.min(m,n)-1];
}
/** Effective numerical matrix rank
@return Number of nonnegligible singular values.
*/
public int rank () {
double tol = Math.max(m,n)*s[0]*Math.pow(2.0,-52.0);
int r = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] > tol) {
r++;
}
}
return r;
}
}
/*
* Copyright (C) 2010-2014 Jang-Hwan Choi
* CONRAD is developed as an Open Source project under the GNU General Public License (GPL).
*/ | gpl-3.0 |
oicr-gsi/niassa | seqware-common/src/main/java/net/sourceforge/seqware/common/util/filetools/lock/LockingFileTools.java | 2474 | package net.sourceforge.seqware.common.util.filetools.lock;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* LockingFileTools class.
* </p>
*
* @author boconnor
* @version $Id: $Id
*/
public class LockingFileTools {
private static final Logger LOGGER = LoggerFactory.getLogger(LockingFileTools.class);
private static final int RETRIES = 100;
public static boolean lockAndAppend(File file, String output) {
return lockAndWrite(file, output, true);
}
/**
* Try to acquire lock. If we can, write the String to file and then release the lock
*
* @param file
* a {@link java.io.File} object.
* @param output
* a {@link java.lang.String} object.
* @param append
* @return a boolean.
*/
public static boolean lockAndWrite(File file, String output, boolean append) {
for (int i = 0; i < RETRIES; i++) {
try {
try (FileOutputStream fos = new FileOutputStream(file, append)) {
FileLock fl = fos.getChannel().tryLock();
if (fl != null) {
try (OutputStreamWriter fw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
fw.append(output);
fl.release();
}
// LOGGER.info("LockingFileTools.lockAndWrite Locked, appended, and released for file: "+file.getAbsolutePath()+" value: "+output);
return true;
} else {
LOGGER.info("LockingFileTools.lockAndWrite Can't get lock for " + file.getAbsolutePath() + " try number " + i + " of " + RETRIES);
// sleep for 2 seconds before trying again
Thread.sleep(2000);
}
}
} catch (IOException | InterruptedException e) {
LOGGER.error("LockingFileTools.lockAndWrite Attempt " + i + " Exception with LockingFileTools: " + e.getMessage(), e);
}
}
LOGGER.error("LockingFileTools.lockAndWrite Unable to get lock for " + file.getAbsolutePath() + " gave up after " + RETRIES + " tries");
return false;
}
}
| gpl-3.0 |
fbk/fcw | fcw-utils/src/main/java/eu/fbk/fcw/utils/corpus/Word.java | 2901 | package eu.fbk.fcw.utils.corpus;
import java.io.Serializable;
/**
* Created by alessio on 12/11/15.
*/
public class Word implements Serializable {
private int id;
private String form;
private String lemma;
private String pos;
private int depParent;
private String depLabel;
private int begin;
private int end;
public static Word readFromArray(String[] parts) {
//todo: better management of possibilities
if (parts.length >= 12) {
return new Word(
Integer.parseInt(parts[0]),
parts[1],
parts[2],
parts[4],
Integer.parseInt(parts[8]),
parts[10]
);
}
return new Word(
Integer.parseInt(parts[0]),
parts[1],
parts[2],
parts[4]
);
}
public Word(int id, String form, String lemma, String pos) {
this.id = id;
this.form = form;
this.lemma = lemma;
this.pos = pos;
}
public Word(int id, String form, String lemma, String pos, int depParent, String depLabel) {
this.id = id;
this.form = form;
this.lemma = lemma;
this.pos = pos;
this.depParent = depParent;
this.depLabel = depLabel;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getLemma() {
return lemma;
}
public void setLemma(String lemma) {
this.lemma = lemma;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public int getDepParent() {
return depParent;
}
public void setDepParent(int depParent) {
this.depParent = depParent;
}
public String getDepLabel() {
return depLabel;
}
public void setDepLabel(String depLabel) {
this.depLabel = depLabel;
}
public int getId() {
return id;
}
public int getBegin() {
return begin;
}
public void setBegin(int begin) {
this.begin = begin;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
@Override public String toString() {
return "Word{" +
"id=" + id +
", form='" + form + '\'' +
", lemma='" + lemma + '\'' +
", pos='" + pos + '\'' +
", depParent=" + depParent +
", depLabel='" + depLabel + '\'' +
'}';
}
@Override public boolean equals(Object obj) {
if (obj instanceof Word) {
return ((Word) obj).getId() == id;
}
return super.equals(obj);
}
}
| gpl-3.0 |
G2159687/espd | app/src/main/java/com/github/epd/sprout/levels/DeadEndLevel.java | 1393 |
package com.github.epd.sprout.levels;
import com.github.epd.sprout.Assets;
import com.github.epd.sprout.messages.Messages;
import java.util.Arrays;
public class DeadEndLevel extends Level {
private static final int SIZE = 5;
{
color1 = 0x534f3e;
color2 = 0xb9d661;
}
@Override
public String tilesTex() {
return Assets.TILES_CAVES;
}
@Override
public String waterTex() {
return Assets.WATER_HALLS;
}
@Override
protected boolean build() {
setSize(7, 7);
Arrays.fill(map, Terrain.WALL);
for (int i = 2; i < SIZE; i++) {
for (int j = 2; j < SIZE; j++) {
map[i * getWidth() + j] = Terrain.EMPTY;
}
}
for (int i = 1; i <= SIZE; i++) {
map[getWidth() + i] = map[getWidth() * SIZE + i] = map[getWidth() * i + 1] = map[getWidth()
* i + SIZE] = Terrain.WATER;
}
entrance = SIZE * getWidth() + SIZE / 2 + 1;
map[entrance] = Terrain.ENTRANCE;
exit = 0;
return true;
}
@Override
public String tileName(int tile) {
switch (tile) {
case Terrain.WATER:
return Messages.get(CityLevel.class, "water_name");
case Terrain.HIGH_GRASS:
return Messages.get(CityLevel.class, "high_grass_name");
default:
return super.tileName(tile);
}
}
@Override
protected void createMobs() {
}
@Override
protected void createItems() {
}
@Override
public int randomRespawnCell() {
return entrance - getWidth();
}
}
| gpl-3.0 |
iterate-ch/cyberduck | s3/src/main/java/ch/cyberduck/core/cloudfront/CloudFrontDistributionConfiguration.java | 37094 | package ch.cyberduck.core.cloudfront;
/*
* Copyright (c) 2002-2013 David Kocher. All rights reserved.
* http://cyberduck.ch/
*
* 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.
*
* Bug fixes, suggestions and comments should be sent to:
* dkocher@cyberduck.ch
*/
import ch.cyberduck.core.AlphanumericRandomStringService;
import ch.cyberduck.core.DisabledListProgressListener;
import ch.cyberduck.core.Host;
import ch.cyberduck.core.HostUrlProvider;
import ch.cyberduck.core.LocaleFactory;
import ch.cyberduck.core.LoginCallback;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.PathContainerService;
import ch.cyberduck.core.Scheme;
import ch.cyberduck.core.auth.AWSCredentialsConfigurator;
import ch.cyberduck.core.aws.AmazonServiceExceptionMappingService;
import ch.cyberduck.core.aws.CustomClientConfiguration;
import ch.cyberduck.core.cdn.Distribution;
import ch.cyberduck.core.cdn.DistributionConfiguration;
import ch.cyberduck.core.cdn.features.Cname;
import ch.cyberduck.core.cdn.features.DistributionLogging;
import ch.cyberduck.core.cdn.features.Index;
import ch.cyberduck.core.cdn.features.Purge;
import ch.cyberduck.core.exception.AccessDeniedException;
import ch.cyberduck.core.exception.BackgroundException;
import ch.cyberduck.core.exception.InteroperabilityException;
import ch.cyberduck.core.features.Location;
import ch.cyberduck.core.preferences.HostPreferences;
import ch.cyberduck.core.preferences.Preferences;
import ch.cyberduck.core.preferences.PreferencesFactory;
import ch.cyberduck.core.s3.S3BucketListService;
import ch.cyberduck.core.s3.S3LocationFeature;
import ch.cyberduck.core.s3.S3Protocol;
import ch.cyberduck.core.s3.S3Session;
import ch.cyberduck.core.ssl.ThreadLocalHostnameDelegatingTrustManager;
import ch.cyberduck.core.ssl.X509KeyManager;
import ch.cyberduck.core.ssl.X509TrustManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jets3t.service.utils.ServiceUtils;
import java.net.URI;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudfront.AmazonCloudFront;
import com.amazonaws.services.cloudfront.AmazonCloudFrontClientBuilder;
import com.amazonaws.services.cloudfront.model.*;
/**
* Amazon CloudFront CDN configuration.
*/
public class CloudFrontDistributionConfiguration implements DistributionConfiguration, Purge, Index, DistributionLogging, Cname {
private static final Logger log = LogManager.getLogger(CloudFrontDistributionConfiguration.class);
private final Preferences preferences = PreferencesFactory.get();
protected final S3Session session;
private final Host bookmark;
private final ClientConfiguration configuration;
private final Location locationFeature;
public CloudFrontDistributionConfiguration(final S3Session session, final X509TrustManager trust, final X509KeyManager key) {
this.session = session;
this.bookmark = session.getHost();
this.configuration = new CustomClientConfiguration(bookmark,
new ThreadLocalHostnameDelegatingTrustManager(trust, bookmark.getHostname()), key);
this.locationFeature = session.getFeature(Location.class);
}
@Override
public String getName() {
return LocaleFactory.localizedString("Amazon CloudFront", "S3");
}
/**
* @param method Distribution method
* @return Origin server hostname. This is not the same as the container for custom origin configurations and
* website endpoints. <bucketname>.s3.amazonaws.com
*/
protected URI getOrigin(final Path container, final Distribution.Method method) throws BackgroundException {
return URI.create(String.format("http://%s.%s", container.getName(), bookmark.getProtocol().getDefaultHostname()));
}
@Override
public List<Distribution.Method> getMethods(final Path container) {
return Arrays.asList(Distribution.DOWNLOAD, Distribution.STREAMING);
}
@Override
public Distribution read(final Path file, final Distribution.Method method, final LoginCallback prompt) throws BackgroundException {
final Path container = session.getFeature(PathContainerService.class).getContainer(file);
try {
if(log.isDebugEnabled()) {
log.debug(String.format("List %s distributions", method));
}
final AmazonCloudFront client = this.client(container);
if(method.equals(Distribution.STREAMING)) {
for(StreamingDistributionSummary d : client.listStreamingDistributions(
new ListStreamingDistributionsRequest()).getStreamingDistributionList().getItems()) {
final S3Origin config = d.getS3Origin();
if(config != null) {
final URI origin = this.getOrigin(container, method);
if(config.getDomainName().equals(origin.getHost())) {
// We currently only support one distribution per bucket
return this.readStreamingDistribution(client, d, container, method);
}
}
}
}
else if(method.equals(Distribution.DOWNLOAD)) {
// List distributions restricting to bucket name origin
for(DistributionSummary d : client.listDistributions(
new ListDistributionsRequest()).getDistributionList().getItems()) {
for(Origin o : d.getOrigins().getItems()) {
final S3OriginConfig config = o.getS3OriginConfig();
if(config != null) {
if(o.getDomainName().equals(this.getOrigin(container, method).getHost())) {
// We currently only support one distribution per bucket
return this.readDownloadDistribution(client, d, container, method);
}
}
}
}
}
else if(method.equals(Distribution.CUSTOM) || method.equals(Distribution.WEBSITE_CDN)) {
for(DistributionSummary d : client.listDistributions(new ListDistributionsRequest()).getDistributionList().getItems()) {
final URI origin = this.getOrigin(container, method);
for(Origin o : d.getOrigins().getItems()) {
// Listing all distributions and look for custom origin
final CustomOriginConfig config = o.getCustomOriginConfig();
if(config != null) {
if(o.getDomainName().equals(origin.getHost())) {
// We currently only support one distribution per bucket
return this.readDownloadDistribution(client, d, container, method);
}
}
}
}
}
final URI origin = this.getOrigin(container, method);
// Return disabled configuration
return new Distribution(method, this.getName(), origin, false);
}
catch(AmazonClientException e) {
throw new AmazonServiceExceptionMappingService().map("Cannot read CDN configuration", e);
}
}
@Override
public void write(final Path file, final Distribution distribution, final LoginCallback prompt) throws BackgroundException {
final Path container = session.getFeature(PathContainerService.class).getContainer(file);
try {
if(null == distribution.getId()) {
// No existing configuration
if(log.isDebugEnabled()) {
log.debug(String.format("No existing distribution found for method %s", distribution.getMethod()));
}
if(distribution.getMethod().equals(Distribution.STREAMING)) {
distribution.setId(this.createStreamingDistribution(container, distribution).getId());
}
else if(distribution.getMethod().equals(Distribution.DOWNLOAD)) {
distribution.setId(this.createDownloadDistribution(container, distribution).getId());
}
else if(distribution.getMethod().equals(Distribution.CUSTOM)
|| distribution.getMethod().equals(Distribution.WEBSITE_CDN)) {
distribution.setId(this.createCustomDistribution(container, distribution).getId());
}
}
else {
if(distribution.getMethod().equals(Distribution.DOWNLOAD)) {
distribution.setEtag(this.updateDownloadDistribution(container, distribution).getETag());
}
else if(distribution.getMethod().equals(Distribution.STREAMING)) {
distribution.setEtag(this.updateStreamingDistribution(container, distribution).getETag());
}
else if(distribution.getMethod().equals(Distribution.CUSTOM)
|| distribution.getMethod().equals(Distribution.WEBSITE_CDN)) {
distribution.setEtag(this.updateCustomDistribution(container, distribution).getETag());
}
}
}
catch(AmazonClientException e) {
throw new AmazonServiceExceptionMappingService().map("Cannot write CDN configuration", e);
}
}
@Override
@SuppressWarnings("unchecked")
public <T> T getFeature(final Class<T> type, final Distribution.Method method) {
if(type == Purge.class || type == Index.class) {
if(method.equals(Distribution.DOWNLOAD)
|| method.equals(Distribution.WEBSITE_CDN)
|| method.equals(Distribution.CUSTOM)) {
return (T) this;
}
}
if(type == DistributionLogging.class) {
if(method.equals(Distribution.DOWNLOAD)
|| method.equals(Distribution.STREAMING)
|| method.equals(Distribution.CUSTOM)) {
return (T) this;
}
}
if(type == Cname.class) {
return (T) this;
}
return null;
}
/**
* You can make any number of invalidation requests, but you can have only three invalidation requests in progress
* at one time. Each request can contain up to 1,000 objects to invalidate. If you exceed these limits, you get an
* error message.
* <p>
* It usually takes 10 to 15 minutes to complete your invalidation request, depending on the size of your request.
*/
@Override
public void invalidate(final Path container, final Distribution.Method method, final List<Path> files, final LoginCallback prompt) throws BackgroundException {
try {
final Distribution d = this.read(container, method, prompt);
if(d.isEnabled()) {
final List<String> keys = new ArrayList<>();
for(Path file : files) {
if(session.getFeature(PathContainerService.class).isContainer(file)) {
// To invalidate all of the objects in a distribution
keys.add(String.format("%s*", Path.DELIMITER));
}
else {
if(file.isDirectory()) {
// The *, which replaces 0 or more characters, must be the last character in the invalidation path
keys.add(String.format("/%s*", session.getFeature(PathContainerService.class).getKey(file)));
}
else {
keys.add(String.format("/%s", session.getFeature(PathContainerService.class).getKey(file)));
}
}
}
if(keys.isEmpty()) {
log.warn("No keys selected for invalidation");
}
else {
final AmazonCloudFront client = this.client(container);
client.createInvalidation(new CreateInvalidationRequest(d.getId(),
new InvalidationBatch(new Paths().withItems(keys).withQuantity(keys.size()), new AlphanumericRandomStringService().random())
));
}
}
}
catch(AmazonClientException e) {
throw new AmazonServiceExceptionMappingService().map("Cannot write CDN configuration", e);
}
}
/**
* @param distribution Configuration
* @return Status message from service
*/
private String readInvalidationStatus(final AmazonCloudFront client,
final Distribution distribution) throws BackgroundException {
try {
int pending = 0;
int completed = 0;
String marker = null;
do {
final ListInvalidationsResult response = client.listInvalidations(new ListInvalidationsRequest(distribution.getId())
.withMaxItems(String.valueOf(1000))
.withMarker(marker));
for(InvalidationSummary s : response.getInvalidationList().getItems()) {
// When the invalidation batch is finished, the status is Completed.
if("Completed".equals(s.getStatus())) {
// No schema for status enumeration. Fail.
completed++;
}
else {
// InProgress
pending++;
}
}
marker = response.getInvalidationList().getNextMarker();
}
while(marker != null);
if(pending > 0) {
return MessageFormat.format(LocaleFactory.localizedString("{0} invalidations in progress", "S3"), pending);
}
if(completed > 0) {
return MessageFormat.format(LocaleFactory.localizedString("{0} invalidations completed", "S3"), completed);
}
return LocaleFactory.localizedString("None");
}
catch(AmazonClientException e) {
throw new AmazonServiceExceptionMappingService().map("Cannot read CDN configuration", e);
}
}
/**
* Amazon CloudFront Extension to create a new distribution configuration
*
* @return Distribution configuration
*/
protected StreamingDistribution createStreamingDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Create new %s distribution", distribution));
}
final AmazonCloudFront client = this.client(container);
final URI origin = this.getOrigin(container, distribution.getMethod());
final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
final StreamingDistributionConfig config = new StreamingDistributionConfig(new AlphanumericRandomStringService().random(),
new S3Origin(origin.getHost(), StringUtils.EMPTY), distribution.isEnabled())
.withComment(originId)
.withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0))
.withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
// Make bucket name fully qualified
final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
false, new S3Protocol().getDefaultHostname());
if(log.isDebugEnabled()) {
log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
}
config.setLogging(new StreamingLoggingConfig()
.withEnabled(distribution.isLogging())
.withBucket(loggingTarget)
.withPrefix(new HostPreferences(session.getHost()).getProperty("cloudfront.logging.prefix"))
);
return client.createStreamingDistribution(new CreateStreamingDistributionRequest(config)).getStreamingDistribution();
}
protected com.amazonaws.services.cloudfront.model.Distribution createDownloadDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
if(log.isDebugEnabled()) {
log.debug(String.format("Create new %s distribution", distribution));
}
final AmazonCloudFront client = this.client(container);
final URI origin = this.getOrigin(container, distribution.getMethod());
final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
final DistributionConfig config = new DistributionConfig(new AlphanumericRandomStringService().random(), distribution.isEnabled())
.withComment(originId)
.withOrigins(new Origins()
.withQuantity(1)
.withItems(new Origin()
.withId(originId)
.withCustomHeaders(new CustomHeaders().withQuantity(0))
.withOriginPath(StringUtils.EMPTY)
.withDomainName(origin.getHost())
.withS3OriginConfig(new S3OriginConfig().withOriginAccessIdentity(StringUtils.EMPTY))
)
)
.withPriceClass(PriceClass.PriceClass_All)
.withDefaultCacheBehavior(new DefaultCacheBehavior()
.withTargetOriginId(originId)
.withForwardedValues(new ForwardedValues().withQueryString(true).withCookies(new CookiePreference().withForward(ItemSelection.All)))
.withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
.withMinTTL(0L)
.withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0)))
.withDefaultRootObject(distribution.getIndexDocument())
.withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
// Make bucket name fully qualified
final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
false, new S3Protocol().getDefaultHostname());
if(log.isDebugEnabled()) {
log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
}
config.setLogging(new LoggingConfig()
.withEnabled(distribution.isLogging())
.withIncludeCookies(true)
.withBucket(loggingTarget)
.withPrefix(new HostPreferences(session.getHost()).getProperty("cloudfront.logging.prefix")
));
return client.createDistribution(new CreateDistributionRequest(config)).getDistribution();
}
protected com.amazonaws.services.cloudfront.model.Distribution createCustomDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
final AmazonCloudFront client = this.client(container);
int httpPort = 80;
int httpsPort = 443;
final URI origin = this.getOrigin(container, distribution.getMethod());
if(origin.getPort() != -1) {
if(origin.getScheme().equals(Scheme.http.name())) {
httpPort = origin.getPort();
}
if(origin.getScheme().equals(Scheme.https.name())) {
httpsPort = origin.getPort();
}
}
final String originId = String.format("%s-%s", preferences.getProperty("application.name"), new AlphanumericRandomStringService().random());
final DistributionConfig config = new DistributionConfig(new AlphanumericRandomStringService().random(), distribution.isEnabled())
.withComment(originId)
.withOrigins(new Origins()
.withQuantity(1)
.withItems(new Origin()
.withId(originId)
.withDomainName(origin.getHost())
.withCustomOriginConfig(new CustomOriginConfig()
.withHTTPPort(httpPort)
.withHTTPSPort(httpsPort)
.withOriginSslProtocols(new OriginSslProtocols().withQuantity(2).withItems("TLSv1.1", "TLSv1.2"))
.withOriginProtocolPolicy(this.getPolicy(distribution.getMethod()))
)
)
)
.withPriceClass(PriceClass.PriceClass_All)
.withDefaultCacheBehavior(new DefaultCacheBehavior()
.withTargetOriginId(originId)
.withForwardedValues(new ForwardedValues().withQueryString(true).withCookies(new CookiePreference().withForward(ItemSelection.All)))
.withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
.withMinTTL(0L)
.withTrustedSigners(new TrustedSigners().withEnabled(false).withQuantity(0)))
.withDefaultRootObject(distribution.getIndexDocument())
.withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
if(distribution.isLogging()) {
// Make bucket name fully qualified
final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
false, new S3Protocol().getDefaultHostname());
if(log.isDebugEnabled()) {
log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
}
config.setLogging(new LoggingConfig()
.withEnabled(distribution.isLogging())
.withIncludeCookies(true)
.withBucket(loggingTarget)
.withPrefix(new HostPreferences(session.getHost()).getProperty("cloudfront.logging.prefix"))
);
}
return client.createDistribution(new CreateDistributionRequest(config)).getDistribution();
}
/**
* Amazon CloudFront Extension used to enable or disable a distribution configuration and its CNAMESs
*/
protected UpdateDistributionResult updateDownloadDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
final URI origin = this.getOrigin(container, distribution.getMethod());
if(log.isDebugEnabled()) {
log.debug(String.format("Update %s distribution with origin %s", distribution, origin));
}
final AmazonCloudFront client = this.client(container);
final GetDistributionConfigResult response = client.getDistributionConfig(new GetDistributionConfigRequest(distribution.getId()));
final DistributionConfig config = response.getDistributionConfig()
.withEnabled(distribution.isEnabled())
.withDefaultRootObject(distribution.getIndexDocument())
.withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
if(distribution.isLogging()) {
// Make bucket name fully qualified
final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
false, new S3Protocol().getDefaultHostname());
if(log.isDebugEnabled()) {
log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
}
config.setLogging(new LoggingConfig()
.withEnabled(distribution.isLogging())
.withIncludeCookies(true)
.withBucket(loggingTarget)
.withPrefix(new HostPreferences(session.getHost()).getProperty("cloudfront.logging.prefix"))
);
}
return client.updateDistribution(new UpdateDistributionRequest(config, distribution.getId(), response.getETag()));
}
protected UpdateStreamingDistributionResult updateStreamingDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
final URI origin = this.getOrigin(container, distribution.getMethod());
if(log.isDebugEnabled()) {
log.debug(String.format("Update %s distribution with origin %s", distribution, origin));
}
final AmazonCloudFront client = this.client(container);
final GetStreamingDistributionConfigResult response = client.getStreamingDistributionConfig(new GetStreamingDistributionConfigRequest(distribution.getId()));
final StreamingDistributionConfig config = response.getStreamingDistributionConfig()
.withEnabled(distribution.isEnabled())
.withS3Origin(new S3Origin(origin.getHost(), StringUtils.EMPTY))
.withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
if(distribution.isLogging()) {
// Make bucket name fully qualified
final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
false, new S3Protocol().getDefaultHostname());
if(log.isDebugEnabled()) {
log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
}
config.setLogging(new StreamingLoggingConfig()
.withEnabled(distribution.isLogging())
.withBucket(loggingTarget)
.withPrefix(new HostPreferences(session.getHost()).getProperty("cloudfront.logging.prefix"))
);
}
return client.updateStreamingDistribution(new UpdateStreamingDistributionRequest(config, distribution.getId(), response.getETag()));
}
protected UpdateDistributionResult updateCustomDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
final URI origin = this.getOrigin(container, distribution.getMethod());
if(log.isDebugEnabled()) {
log.debug(String.format("Update %s distribution with origin %s", distribution, origin));
}
final AmazonCloudFront client = this.client(container);
final GetDistributionConfigResult response = client.getDistributionConfig(new GetDistributionConfigRequest(distribution.getId()));
final DistributionConfig config = response.getDistributionConfig()
.withEnabled(distribution.isEnabled())
.withDefaultRootObject(distribution.getIndexDocument() != null ? distribution.getIndexDocument() : StringUtils.EMPTY)
.withAliases(new Aliases().withItems(distribution.getCNAMEs()).withQuantity(distribution.getCNAMEs().length));
// Make bucket name fully qualified
final String loggingTarget = ServiceUtils.generateS3HostnameForBucket(distribution.getLoggingContainer(),
false, new S3Protocol().getDefaultHostname());
if(log.isDebugEnabled()) {
log.debug(String.format("Set logging target for %s to %s", distribution, loggingTarget));
}
config.setLogging(new LoggingConfig()
.withEnabled(distribution.isLogging())
.withIncludeCookies(true)
.withBucket(loggingTarget)
.withPrefix(new HostPreferences(session.getHost()).getProperty("cloudfront.logging.prefix"))
);
return client.updateDistribution(new UpdateDistributionRequest(config, distribution.getId(), response.getETag()));
}
protected void deleteDownloadDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
final URI origin = this.getOrigin(container, distribution.getMethod());
if(log.isDebugEnabled()) {
log.debug(String.format("Update %s distribution with origin %s", distribution, origin));
}
final AmazonCloudFront client = this.client(container);
client.deleteDistribution(new DeleteDistributionRequest(distribution.getId(), distribution.getEtag()));
}
protected void deleteStreamingDistribution(final Path container, final Distribution distribution)
throws BackgroundException {
final URI origin = this.getOrigin(container, distribution.getMethod());
if(log.isDebugEnabled()) {
log.debug(String.format("Update %s distribution with origin %s", distribution, origin));
}
final AmazonCloudFront client = this.client(container);
client.deleteStreamingDistribution(new DeleteStreamingDistributionRequest(distribution.getId(), distribution.getEtag()));
}
/**
* @param method Distribution method
* @return Match viewer policy
*/
protected OriginProtocolPolicy getPolicy(final Distribution.Method method) {
return OriginProtocolPolicy.MatchViewer;
}
private Distribution readStreamingDistribution(final AmazonCloudFront client,
final StreamingDistributionSummary summary,
final Path container,
final Distribution.Method method) throws BackgroundException {
// Retrieve distributions configuration to access current logging status settings.
try {
final GetStreamingDistributionConfigResult response = client.getStreamingDistributionConfig(new GetStreamingDistributionConfigRequest(summary.getId()));
final StreamingDistributionConfig configuration = response.getStreamingDistributionConfig();
final Distribution distribution = new Distribution(method, this.getName(), this.getOrigin(container, method), summary.isEnabled());
distribution.setId(summary.getId());
distribution.setDeployed("Deployed".equals(summary.getStatus()));
distribution.setUrl(URI.create(String.format("%s://%s%s", method.getScheme(), summary.getDomainName(), method.getContext())));
distribution.setSslUrl(method.equals(Distribution.DOWNLOAD) || method.equals(Distribution.CUSTOM) ? URI.create(String.format("https://%s%s", summary.getDomainName(), method.getContext())) : null);
distribution.setReference(configuration.getCallerReference());
distribution.setEtag(response.getETag());
distribution.setStatus(LocaleFactory.localizedString(summary.getStatus(), "S3"));
distribution.setCNAMEs(configuration.getAliases().getItems().toArray(new String[configuration.getAliases().getItems().size()]));
distribution.setLogging(configuration.getLogging().isEnabled());
distribution.setLoggingContainer(StringUtils.isNotBlank(configuration.getLogging().getBucket()) ?
ServiceUtils.findBucketNameInHostname(configuration.getLogging().getBucket(), new S3Protocol().getDefaultHostname()) : null);
if(this.getFeature(Purge.class, method) != null) {
distribution.setInvalidationStatus(this.readInvalidationStatus(client, distribution));
}
if(this.getFeature(DistributionLogging.class, method) != null) {
try {
distribution.setContainers(new S3BucketListService(session, new S3LocationFeature.S3Region(bookmark.getRegion())).list(
new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)),
new DisabledListProgressListener()).toList());
}
catch(AccessDeniedException | InteroperabilityException e) {
log.warn(String.format("Failure listing buckets. %s", e.getMessage()));
}
}
return distribution;
}
catch(AmazonClientException e) {
throw new AmazonServiceExceptionMappingService().map("Cannot read CDN configuration", e);
}
}
private Distribution readDownloadDistribution(final AmazonCloudFront client,
final DistributionSummary summary,
final Path container,
final Distribution.Method method) throws BackgroundException {
// Retrieve distributions configuration to access current logging status settings.
try {
final GetDistributionConfigResult response = client.getDistributionConfig(new GetDistributionConfigRequest(summary.getId()));
final DistributionConfig configuration = response.getDistributionConfig();
final Distribution distribution = new Distribution(method, this.getName(), this.getOrigin(container, method), summary.isEnabled());
distribution.setId(summary.getId());
distribution.setDeployed("Deployed".equals(summary.getStatus()));
distribution.setUrl(URI.create(String.format("%s://%s%s", method.getScheme(), summary.getDomainName(), method.getContext())));
distribution.setSslUrl(method.equals(Distribution.DOWNLOAD) || method.equals(Distribution.CUSTOM) ? URI.create(String.format("https://%s%s", summary.getDomainName(), method.getContext())) : null);
distribution.setReference(configuration.getCallerReference());
distribution.setEtag(response.getETag());
distribution.setStatus(LocaleFactory.localizedString(summary.getStatus(), "S3"));
distribution.setCNAMEs(configuration.getAliases().getItems().toArray(new String[configuration.getAliases().getItems().size()]));
distribution.setLogging(configuration.getLogging().isEnabled());
distribution.setLoggingContainer(StringUtils.isNotBlank(configuration.getLogging().getBucket()) ?
ServiceUtils.findBucketNameInHostname(configuration.getLogging().getBucket(), new S3Protocol().getDefaultHostname()) : null);
if(StringUtils.isNotBlank(configuration.getDefaultRootObject())) {
distribution.setIndexDocument(configuration.getDefaultRootObject());
}
if(this.getFeature(Purge.class, method) != null) {
distribution.setInvalidationStatus(this.readInvalidationStatus(client, distribution));
}
if(this.getFeature(DistributionLogging.class, method) != null) {
distribution.setContainers(new S3BucketListService(session, new S3LocationFeature.S3Region(bookmark.getRegion())).list(
new Path(String.valueOf(Path.DELIMITER), EnumSet.of(Path.Type.volume, Path.Type.directory)),
new DisabledListProgressListener()).toList());
}
return distribution;
}
catch(AmazonClientException e) {
throw new AmazonServiceExceptionMappingService().map("Cannot read CDN configuration", e);
}
}
private AmazonCloudFront client(final Path container) throws BackgroundException {
final AmazonCloudFrontClientBuilder builder = AmazonCloudFrontClientBuilder.standard()
.withCredentials(AWSCredentialsConfigurator.toAWSCredentialsProvider(session.getClient().getProviderCredentials()))
.withClientConfiguration(configuration);
final Location.Name region = this.getRegion(container);
if(S3Session.isAwsHostname(session.getHost().getHostname(), false)) {
if(Location.unknown.equals(region)) {
builder.withRegion(Regions.DEFAULT_REGION);
}
else {
builder.withRegion(region.getIdentifier());
}
}
else {
builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
new HostUrlProvider(false).get(session.getHost()), region.getIdentifier()));
}
return builder.build();
}
protected Location.Name getRegion(final Path container) throws BackgroundException {
return locationFeature.getLocation(container);
}
}
| gpl-3.0 |
nigelcog/mini-IoT | android/mini-IoT/app/src/main/java/com/creativecub/iotarduino/DataAdapter.java | 1899 | package com.creativecub.iotarduino;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import java.util.List;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> {
private List<Data> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, genre;
public ImageView ivIcon;
public Switch aSwitch;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
genre = (TextView) view.findViewById(R.id.genre);
year = (TextView) view.findViewById(R.id.year);
ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
aSwitch = (Switch) view.findViewById(R.id.switch1);
}
}
public DataAdapter(List<Data> moviesList) {
this.moviesList = moviesList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Data data = moviesList.get(position);
holder.title.setText(data.getTitle());
holder.genre.setText(data.getGenre());
holder.year.setText(data.getYear());
holder.ivIcon.setImageBitmap(data.getIvIcon());
holder.aSwitch.setChecked(data.gettoggle());
}
@Override
public int getItemCount() {
return moviesList.size();
}
} | gpl-3.0 |
SuperMap-iDesktop/SuperMap-iDesktop-Cross | DataView/src/main/java/com/supermap/desktop/framemenus/CtrlActionWorkspaceSaveAsOracle.java | 785 | package com.supermap.desktop.framemenus;
import com.supermap.desktop.Application;
import com.supermap.desktop.Interface.IBaseItem;
import com.supermap.desktop.Interface.IForm;
import com.supermap.desktop.implement.CtrlAction;
import com.supermap.desktop.ui.controls.JDialogWorkspaceSaveAs;
import javax.swing.*;
public class CtrlActionWorkspaceSaveAsOracle extends CtrlAction {
public CtrlActionWorkspaceSaveAsOracle(IBaseItem caller, IForm formClass) {
super(caller, formClass);
}
public void run(){
JFrame parent = (JFrame) Application.getActiveApplication().getMainFrame();
JDialogWorkspaceSaveAs dialog = new JDialogWorkspaceSaveAs(parent, true,JDialogWorkspaceSaveAs.saveAsOracle);
dialog.showDialog();
}
@Override
public boolean enable() {
return true;
}
}
| gpl-3.0 |
jinsedeyuzhou/NewsClient | doraemonkit/src/main/java/com/ebrightmoon/doraemonkit/ui/widget/tableview/listener/Observable.java | 1237 | package com.ebrightmoon.doraemonkit.ui.widget.tableview.listener;
import java.util.ArrayList;
import java.util.List;
public abstract class Observable<T> {
public final ArrayList<T> observables = new ArrayList<>();
/**AttachObserver(通过实例注册观察者)
**/
public void register(T observer){
if(observer==null) throw new NullPointerException();
synchronized(observables){
if(!observables.contains(observer)){
observables.add(observer);
}
}
}
/**UnattachObserver(注销观察者)
**/
public void unRegister(T observer){
if(observer==null) throw new NullPointerException();
if(observables.contains(observer)){
observables.remove(observer);
}
}
public void unRegisterAll(){
synchronized(observables){
observables.clear();
}
}
/**Ruturnthesizeofobservers*/
public int countObservers(){
synchronized(observables){
return observables.size();
}
}
/**
*notify all observer(通知所有观察者,在子类中实现)
*/
public abstract void notifyObservers(List<T> observers);
}
| gpl-3.0 |
fanruan/finereport-design | designer_chart/src/com/fr/plugin/chart/custom/component/VanChartHyperLinkPane.java | 11772 | package com.fr.plugin.chart.custom.component;
import com.fr.chart.chartattr.Plot;
import com.fr.chart.web.ChartHyperPoplink;
import com.fr.chart.web.ChartHyperRelateCellLink;
import com.fr.chart.web.ChartHyperRelateFloatLink;
import com.fr.design.ExtraDesignClassManager;
import com.fr.design.beans.BasicBeanPane;
import com.fr.design.chart.javascript.ChartEmailPane;
import com.fr.design.chart.series.SeriesCondition.impl.ChartHyperPoplinkPane;
import com.fr.design.chart.series.SeriesCondition.impl.ChartHyperRelateCellLinkPane;
import com.fr.design.chart.series.SeriesCondition.impl.ChartHyperRelateFloatLinkPane;
import com.fr.design.chart.series.SeriesCondition.impl.FormHyperlinkPane;
import com.fr.design.designer.TargetComponent;
import com.fr.design.fun.HyperlinkProvider;
import com.fr.design.gui.HyperlinkFilterHelper;
import com.fr.design.gui.controlpane.NameObjectCreator;
import com.fr.design.gui.controlpane.NameableCreator;
import com.fr.design.gui.imenutable.UIMenuNameableCreator;
import com.fr.design.hyperlink.ReportletHyperlinkPane;
import com.fr.design.hyperlink.WebHyperlinkPane;
import com.fr.design.javascript.JavaScriptImplPane;
import com.fr.design.javascript.ParameterJavaScriptPane;
import com.fr.design.module.DesignModuleFactory;
import com.fr.general.FRLogger;
import com.fr.general.Inter;
import com.fr.general.NameObject;
import com.fr.js.EmailJavaScript;
import com.fr.js.FormHyperlinkProvider;
import com.fr.js.JavaScript;
import com.fr.js.JavaScriptImpl;
import com.fr.js.NameJavaScript;
import com.fr.js.NameJavaScriptGroup;
import com.fr.js.ParameterJavaScript;
import com.fr.js.ReportletHyperlink;
import com.fr.js.WebHyperlink;
import com.fr.plugin.chart.designer.component.VanChartUIListControlPane;
import com.fr.stable.ListMap;
import com.fr.stable.Nameable;
import com.fr.stable.bridge.StableFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by Fangjie on 2016/4/28.
*/
public class VanChartHyperLinkPane extends VanChartUIListControlPane {
public VanChartHyperLinkPane() {
super();
}
@Override
public NameableCreator[] createNameableCreators() {
//面板初始化,需要在populate的时候更新
Map<String, NameableCreator> nameCreators = new ListMap<>();
NameableCreator[] creators = DesignModuleFactory.getHyperlinkGroupType().getHyperlinkCreators();
for (NameableCreator creator : creators) {
nameCreators.put(creator.menuName(), creator);
}
Set<HyperlinkProvider> providers = ExtraDesignClassManager.getInstance().getArray(HyperlinkProvider.XML_TAG);
for (HyperlinkProvider provider : providers) {
NameableCreator nc = provider.createHyperlinkCreator();
nameCreators.put(nc.menuName(), nc);
}
return nameCreators.values().toArray(new NameableCreator[nameCreators.size()]);
}
protected BasicBeanPane createPaneByCreators(NameableCreator creator) {
Constructor<? extends BasicBeanPane> constructor = null;
try {
constructor = creator.getUpdatePane().getConstructor(HashMap.class, boolean.class);
return constructor.newInstance(plot.getHyperLinkEditorMap(), false);
} catch (InstantiationException e) {
FRLogger.getLogger().error(e.getMessage(), e);
} catch (IllegalAccessException e) {
FRLogger.getLogger().error(e.getMessage(), e);
} catch (NoSuchMethodException e) {
return super.createPaneByCreators(creator);
} catch (InvocationTargetException e) {
FRLogger.getLogger().error(e.getMessage(), e);
}
return null;
}
/**
* 弹出列表的标题.
*
* @return 返回标题字符串.
*/
public String title4PopupWindow() {
return Inter.getLocText("FR-Designer_Hyperlink");
}
@Override
protected String getAddItemText() {
return Inter.getLocText("FR-Designer_Add_Hyperlink");
}
@Override
protected AddItemMenuDef getAddItemMenuDef (NameableCreator[] creators) {
return new AddVanChartItemMenuDef(creators);
}
public void populate(NameJavaScriptGroup nameHyperlink_array) {
java.util.List<NameObject> list = new ArrayList<NameObject>();
if (nameHyperlink_array != null) {
for (int i = 0; i < nameHyperlink_array.size(); i++) {
list.add(new NameObject(nameHyperlink_array.getNameHyperlink(i).getName(), nameHyperlink_array.getNameHyperlink(i).getJavaScript()));
}
}
this.populate(list.toArray(new NameObject[list.size()]));
}
public void populate(TargetComponent elementCasePane) {
//populate
}
/**
* updateJs的Group
*
* @return 返回NameJavaScriptGroup
*/
public NameJavaScriptGroup updateJSGroup() {
Nameable[] res = this.update();
NameJavaScript[] res_array = new NameJavaScript[res.length];
for (int i = 0; i < res.length; i++) {
NameObject no = (NameObject) res[i];
res_array[i] = new NameJavaScript(no.getName(), (JavaScript) no.getObject());
}
return new NameJavaScriptGroup(res_array);
}
public void populate(Plot plot) {
this.plot = plot;
HashMap paneMap = getHyperlinkMap(plot);
//安装平台内打开插件时,添加相应按钮
Set<HyperlinkProvider> providers = ExtraDesignClassManager.getInstance().getArray(HyperlinkProvider.XML_TAG);
for (HyperlinkProvider provider : providers) {
NameableCreator nc = provider.createHyperlinkCreator();
paneMap.put(nc.getHyperlink(), nc.getUpdatePane());
}
java.util.List<UIMenuNameableCreator> list = refreshList(paneMap);
NameObjectCreator[] creators = new NameObjectCreator[list.size()];
for (int i = 0; list != null && i < list.size(); i++) {
UIMenuNameableCreator uiMenuNameableCreator = list.get(i);
creators[i] = new NameObjectCreator(uiMenuNameableCreator.getName(), uiMenuNameableCreator.getObj().getClass(), uiMenuNameableCreator.getPaneClazz());
}
refreshNameableCreator(creators);
java.util.List<NameObject> nameObjects = new ArrayList<NameObject>();
NameJavaScriptGroup nameGroup = populateHotHyperLink(plot);
for (int i = 0; nameGroup != null && i < nameGroup.size(); i++) {
NameJavaScript javaScript = nameGroup.getNameHyperlink(i);
if (javaScript != null && javaScript.getJavaScript() != null) {
JavaScript script = javaScript.getJavaScript();
UIMenuNameableCreator uiMenuNameableCreator = new UIMenuNameableCreator(javaScript.getName(), script, getUseMap(paneMap, script.getClass()));
nameObjects.add(new NameObject(uiMenuNameableCreator.getName(), uiMenuNameableCreator.getObj()));
}
}
this.populate(nameObjects.toArray(new NameObject[nameObjects.size()]));
doLayout();
}
protected NameJavaScriptGroup populateHotHyperLink(Plot plot) {
return plot.getHotHyperLink();
}
protected HashMap getHyperlinkMap(Plot plot) {
HashMap<Class, Class> map = new HashMap<Class, Class>();
map.put(ReportletHyperlink.class, ReportletHyperlinkPane.class);
map.put(EmailJavaScript.class, ChartEmailPane.class);
map.put(WebHyperlink.class, WebHyperlinkPane.class);
map.put(ParameterJavaScript.class, ParameterJavaScriptPane.class);
map.put(JavaScriptImpl.class, JavaScriptImplPane.class);
map.put(ChartHyperPoplink.class, ChartHyperPoplinkPane.class);
map.put(ChartHyperRelateCellLink.class, ChartHyperRelateCellLinkPane.class);
map.put(ChartHyperRelateFloatLink.class, ChartHyperRelateFloatLinkPane.class);
map.put(FormHyperlinkProvider.class, FormHyperlinkPane.class);
return map;
}
public void update(Plot plot) {
NameJavaScriptGroup nameGroup = updateNameGroup();
updateHotHyperLink(plot, nameGroup);
}
protected void updateHotHyperLink(Plot plot, NameJavaScriptGroup nameGroup) {
plot.setHotHyperLink(nameGroup);
}
private NameJavaScriptGroup updateNameGroup() {
Nameable[] nameables = update();
NameJavaScriptGroup nameGroup = new NameJavaScriptGroup();
nameGroup.clear();
for (int i = 0; i < nameables.length; i++) {
JavaScript javaScript = (JavaScript) ((NameObject) nameables[i]).getObject();
String name = nameables[i].getName();
NameJavaScript nameJava = new NameJavaScript(name, javaScript);
nameGroup.addNameHyperlink(nameJava);
}
return nameGroup;
}
protected java.util.List<UIMenuNameableCreator> refreshList(HashMap map) {
java.util.List<UIMenuNameableCreator> list = new ArrayList<UIMenuNameableCreator>();
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Reportlet"),
new ReportletHyperlink(), getUseMap(map, ReportletHyperlink.class)));
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Mail"), new EmailJavaScript(), VanChartEmailPane.class));
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Web"),
new WebHyperlink(), getUseMap(map, WebHyperlink.class)));
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Dynamic_Parameters"),
new ParameterJavaScript(), getUseMap(map, ParameterJavaScript.class)));
list.add(new UIMenuNameableCreator("JavaScript", new JavaScriptImpl(), getUseMap(map, JavaScriptImpl.class)));
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Float_Chart"),
new ChartHyperPoplink(), getUseMap(map, ChartHyperPoplink.class)));
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Cell"),
new ChartHyperRelateCellLink(), getUseMap(map, ChartHyperRelateCellLink.class)));
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Float"),
new ChartHyperRelateFloatLink(), getUseMap(map, ChartHyperRelateFloatLink.class)));
FormHyperlinkProvider hyperlink = StableFactory.getMarkedInstanceObjectFromClass(FormHyperlinkProvider.XML_TAG, FormHyperlinkProvider.class);
list.add(new UIMenuNameableCreator(Inter.getLocText("Chart-Link_Form"),
hyperlink, getUseMap(map, FormHyperlinkProvider.class)));
return list;
}
protected Class<? extends BasicBeanPane> getUseMap(HashMap map, Object key) {
if (map.get(key) != null) {
return (Class<? extends BasicBeanPane>) map.get(key);
}
//引擎在这边放了个provider,当前表单对象
for (Object tempKey : map.keySet()) {
if (((Class) tempKey).isAssignableFrom((Class) key)) {
return (Class<? extends BasicBeanPane>) map.get(tempKey);
}
}
return null;
}
protected class AddVanChartItemMenuDef extends AddItemMenuDef {
public AddVanChartItemMenuDef(NameableCreator[] creators) {
super(creators);
}
@Override
protected boolean whetherAdd(String itemName) {
return HyperlinkFilterHelper.whetherAddHyperlink4Chart(itemName);
}
}
//邮箱
public static class VanChartEmailPane extends ChartEmailPane {
@Override
protected boolean needRenamePane() {
return false;
}
}
}
| gpl-3.0 |
ThoNill/JanusData | JanusData/test/test/janus/data/DataDescriptionTest.java | 3870 | package test.janus.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.apache.log4j.Logger;
import org.janus.data.DataContext;
import org.janus.data.DataContextImpl;
import org.janus.data.DataDescription;
import org.janus.data.DataDescriptionImpl;
import org.junit.Test;
public class DataDescriptionTest {
private static final String THIS_EXCEPTION_IS_OK = "This Exception is ok";
private static final String THIS_EXCEPTION_IS_NOT_OK = "This Exception is not ok";
public static final Logger LOG = Logger.getLogger(DataDescriptionTest.class
.getSimpleName());
private DataDescription createTestDescription() {
DataDescription description = new DataDescriptionImpl();
description.getHandle("first");
description.getHandle("second");
return description;
}
@Test
public void testGetHandle() {
DataDescription description = new DataDescriptionImpl();
int h0 = description.getHandle("first");
int h1 = description.getHandle("second");
assertEquals(0, h0);
assertEquals(1, h1);
assertEquals(0, description.getHandle("first"));
assertEquals(1, description.getHandle("second"));
}
@Test
public void testExistsHandleName() {
DataDescription description = createTestDescription();
assertEquals(true, description.existsHandleName("first"));
assertEquals(false, description.existsHandleName("name"));
}
@Test
public void testGetHandleName() {
DataDescription description = createTestDescription();
assertEquals("first",
description.getHandleName(description.getHandle("first")));
assertEquals("second",
description.getHandleName(description.getHandle("second")));
}
@Test
public void testCreateAnonymousHandle() {
DataDescription description = createTestDescription();
assertNotEquals(description.getHandle("first"),
description.createAnonymousHandle());
assertNotEquals(description.getHandle("second"),
description.createAnonymousHandle());
}
@Test
public void testFix() {
try {
DataDescription description = createTestDescription();
DataContext ctx = description.newContext();
description.getHandle("gehtNichtMehr");
fail("not fixed");
} catch (Exception rx) {
LOG.error(THIS_EXCEPTION_IS_OK,rx);
}
}
@Test
public void testFixAnonymous() {
try {
DataDescription description = createTestDescription();
DataContext ctx = description.newContext();
description.createAnonymousHandle();
fail("not fixed");
} catch (Exception rx) {
LOG.error(THIS_EXCEPTION_IS_OK,rx);
}
}
@Test
public void testFixErlaubt() {
try {
DataDescription description = createTestDescription();
DataContext ctx = description.newContext();
description.getHandle("second");
} catch (Exception rx) {
LOG.error(THIS_EXCEPTION_IS_NOT_OK,rx);
fail("not fixed");
}
}
@Test
public void testGetSize() {
DataDescription description = createTestDescription();
assertEquals(2, description.getSize());
}
@Test
public void testNewContext() {
DataDescription description = createTestDescription();
DataContext ctx = description.newContext();
assertTrue(ctx instanceof DataContextImpl);
}
}
| gpl-3.0 |
Minecolonies/minecolonies | src/main/java/com/minecolonies/coremod/client/gui/WindowAssignCitizen.java | 8602 | package com.minecolonies.coremod.client.gui;
import com.ldtteam.blockout.Pane;
import com.ldtteam.blockout.controls.Button;
import com.ldtteam.blockout.controls.ButtonHandler;
import com.ldtteam.blockout.controls.Text;
import com.ldtteam.blockout.views.ScrollingList;
import com.ldtteam.blockout.views.Window;
import com.ldtteam.structurize.util.LanguageHandler;
import com.minecolonies.api.colony.ICitizenDataView;
import com.minecolonies.api.colony.IColonyView;
import com.minecolonies.api.colony.buildings.views.IBuildingView;
import com.minecolonies.api.util.BlockPosUtil;
import com.minecolonies.api.util.constant.Constants;
import com.minecolonies.coremod.Network;
import com.minecolonies.coremod.colony.buildings.AbstractBuildingGuards;
import com.minecolonies.coremod.colony.buildings.views.LivingBuildingView;
import com.minecolonies.coremod.network.messages.server.colony.building.home.AssignUnassignMessage;
import net.minecraft.util.math.BlockPos;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static com.minecolonies.api.util.constant.WindowConstants.*;
import static com.minecolonies.coremod.client.gui.huts.WindowHutBuilderModule.DARKGREEN;
import static com.minecolonies.coremod.client.gui.huts.WindowHutBuilderModule.RED;
/**
* Window for the hiring or firing of a worker.
*/
public class WindowAssignCitizen extends Window implements ButtonHandler
{
/**
* Threshold that defines when the living quarters are too far away.
*/
private static final double FAR_DISTANCE_THRESHOLD = 250;
/**
* The view of the current building.
*/
private final IBuildingView building;
/**
* List of citizens which can be assigned.
*/
private final ScrollingList citizenList;
/**
* The colony.
*/
private final IColonyView colony;
/**
* Contains all the citizens.
*/
private List<ICitizenDataView> citizens = new ArrayList<>();
/**
* Constructor for the window when the player wants to assign a worker for a certain home building.
*
* @param c the colony view.
* @param buildingId the building position.
*/
public WindowAssignCitizen(final IColonyView c, final BlockPos buildingId)
{
super(Constants.MOD_ID + ASSIGN_CITIZEN_RESOURCE_SUFFIX);
this.colony = c;
building = colony.getBuilding(buildingId);
citizenList = findPaneOfTypeByID(CITIZEN_LIST, ScrollingList.class);
updateCitizens();
}
/**
* Clears and resets/updates all citizens.
*/
private void updateCitizens()
{
citizens.clear();
citizens.addAll(colony.getCitizens().values());
//Removes all citizens which already have a job.
citizens = colony.getCitizens().values().stream()
.filter(cit -> cit.getHomeBuilding() == null
|| !(colony.getBuilding(cit.getHomeBuilding()) instanceof AbstractBuildingGuards.View)
&& !cit.getHomeBuilding().equals(building.getID()))
.sorted(Comparator.comparing(cit -> ((ICitizenDataView) cit).getHomeBuilding() == null ? 0 : 1)
.thenComparingLong(cit -> {
if (((ICitizenDataView) cit).getWorkBuilding() == null)
{
return 0;
}
return BlockPosUtil.getDistance2D(((ICitizenDataView) cit).getWorkBuilding(), building.getPosition());
})).collect(Collectors.toList());
}
/**
* Called when the GUI has been opened. Will fill the fields and lists.
*/
@Override
public void onOpened()
{
updateCitizens();
citizenList.enable();
citizenList.show();
//Creates a dataProvider for the homeless citizenList.
citizenList.setDataProvider(new ScrollingList.DataProvider()
{
/**
* The number of rows of the list.
* @return the number.
*/
@Override
public int getElementCount()
{
return citizens.size();
}
/**
* Inserts the elements into each row.
* @param index the index of the row/list element.
* @param rowPane the parent Pane for the row, containing the elements to update.
*/
@Override
public void updateElement(final int index, @NotNull final Pane rowPane)
{
@NotNull final ICitizenDataView citizen = citizens.get(index);
if (building instanceof LivingBuildingView)
{
rowPane.findPaneOfTypeByID(CITIZEN_LABEL, Text.class).setText(citizen.getName());
final BlockPos work = citizen.getWorkBuilding();
String workString = "";
double newDistance = 0;
if (work != null)
{
newDistance = BlockPosUtil.getDistance2D(work, building.getPosition());;
workString = " " + newDistance + " blocks";
}
final BlockPos home = citizen.getHomeBuilding();
String homeString = "";
boolean better = false;
boolean badCurrentLiving = false;
if (home != null)
{
if (work != null)
{
final double oldDistance = BlockPosUtil.getDistance2D(work, home);
homeString = LanguageHandler.format("com.minecolonies.coremod.gui.homeHut.currently", oldDistance);
better = newDistance < oldDistance;
if (oldDistance >= FAR_DISTANCE_THRESHOLD)
{
badCurrentLiving = true;
}
}
else
{
homeString = LanguageHandler.format("com.minecolonies.coremod.gui.homeHut.current", home.getX(), home.getY(), home.getZ());
}
}
final Text newLivingLabel = rowPane.findPaneOfTypeByID(CITIZEN_JOB, Text.class);
newLivingLabel.setText(LanguageHandler.format(citizen.getJob()) + workString);
if (better)
{
newLivingLabel.setColors(DARKGREEN);
}
final Text currentLivingLabel = rowPane.findPaneOfTypeByID(CITIZEN_LIVING, Text.class);
currentLivingLabel.setText(homeString);
if (badCurrentLiving)
{
currentLivingLabel.setColors(RED);
}
final Button done = rowPane.findPaneOfTypeByID(CITIZEN_DONE, Button.class);
if (colony.isManualHousing())
{
done.enable();
}
else
{
done.disable();
}
}
}
});
}
@Override
public void onUpdate()
{
updateCitizens();
window.findPaneOfTypeByID(CITIZEN_LIST, ScrollingList.class).refreshElementPanes();
}
/**
* Called when any button has been clicked.
*
* @param button the clicked button.
*/
@Override
public void onButtonClicked(@NotNull final Button button)
{
if (button.getID().equals(BUTTON_DONE))
{
final int row = citizenList.getListElementIndexByPane(button);
final ICitizenDataView data = citizens.get(row);
if (building instanceof LivingBuildingView)
{
((LivingBuildingView) building).addResident(data.getId());
}
Network.getNetwork().sendToServer(new AssignUnassignMessage(this.building, true, data.getId()));
}
else if (!button.getID().equals(BUTTON_CANCEL))
{
return;
}
if (colony.getTownHall() != null)
{
building.openGui(false);
}
}
}
| gpl-3.0 |
weblicht/oaipmh-cmdi-bindings | src/main/java/eu/clarin/weblicht/bindings/cmd/ws/OutputValues.java | 932 | package eu.clarin.weblicht.bindings.cmd.ws;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
/**
*
* @author akislev
*/
@XmlAccessorType(value = XmlAccessType.FIELD)
public class OutputValues extends AbstractValues<OutputValue> {
@XmlElement(name = "ParameterValue", required = true)
private List<OutputValue> values;
OutputValues() {
}
@Override
protected List<OutputValue> getValues() {
return values;
}
public boolean add(OutputValue value) {
if (values == null) {
values = new ArrayList<OutputValue>();
}
return values.add(value);
}
@Override
public OutputValues copy() {
OutputValues v = (OutputValues) super.copy();
v.values = copy(values);
return v;
}
}
| gpl-3.0 |