repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
mp-pinheiro/DW2Digivolver
src/Digivolver/Digivolution.java
580
package Digivolver; public class Digivolution{ private Digimon digimon; private int minDp = 0; private int maxDp = 0; public boolean isWithinDp(int minDp, int maxDp){ return this.minDp<=maxDp && this.maxDp>=minDp; } public Digivolution(Digimon digimon, int minDp, int maxDp) { this.digimon = digimon; this.minDp = minDp; this.maxDp = maxDp; } public Digimon getDigimon() { return digimon; } public void setDigimon(Digimon digimon) { this.digimon = digimon; } public int getMinDp(){ return minDp; } public int getMaxDp(){ return maxDp; } }
mit
robobalasko/DFA-Simulator
src/main/java/net/robobalasko/dfa/gui/MainFrame.java
3007
package net.robobalasko.dfa.gui; import net.robobalasko.dfa.core.Automaton; import net.robobalasko.dfa.core.exceptions.NodeConnectionMissingException; import net.robobalasko.dfa.core.exceptions.StartNodeMissingException; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MainFrame extends JFrame { private final Automaton automaton; private JButton checkButton; public MainFrame(final Automaton automaton) throws HeadlessException { super("DFA Simulator"); this.automaton = automaton; setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JPanel containerPanel = new JPanel(); containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.PAGE_AXIS)); containerPanel.setBorder(new EmptyBorder(20, 20, 20, 20)); setContentPane(containerPanel); CanvasPanel canvasPanel = new CanvasPanel(this, automaton); containerPanel.add(canvasPanel); JPanel checkInputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); containerPanel.add(checkInputPanel); final JTextField inputText = new JTextField(40); Document document = inputText.getDocument(); document.addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { checkButton.setEnabled(e.getDocument().getLength() > 0); } @Override public void removeUpdate(DocumentEvent e) { checkButton.setEnabled(e.getDocument().getLength() > 0); } @Override public void changedUpdate(DocumentEvent e) { checkButton.setEnabled(e.getDocument().getLength() > 0); } }); checkInputPanel.add(inputText); checkButton = new JButton("Check"); checkButton.setEnabled(false); checkButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { JOptionPane.showMessageDialog(MainFrame.this, automaton.acceptsString(inputText.getText()) ? "Input accepted." : "Input rejected."); } catch (StartNodeMissingException ex) { JOptionPane.showMessageDialog(MainFrame.this, "Missing start node."); } catch (NodeConnectionMissingException ex) { JOptionPane.showMessageDialog(MainFrame.this, "Not a good string. Automat doesn't accept it."); } } }); checkInputPanel.add(checkButton); setResizable(false); setVisible(true); pack(); } }
mit
EXASOL/virtual-schemas
src/main/java/com/exasol/adapter/dialects/bigquery/BigQueryColumnMetadataReader.java
1364
package com.exasol.adapter.dialects.bigquery; import java.sql.Connection; import java.sql.Types; import com.exasol.adapter.AdapterProperties; import com.exasol.adapter.dialects.IdentifierConverter; import com.exasol.adapter.jdbc.BaseColumnMetadataReader; import com.exasol.adapter.jdbc.JdbcTypeDescription; import com.exasol.adapter.metadata.DataType; /** * This class implements BigQuery-specific reading of column metadata. */ public class BigQueryColumnMetadataReader extends BaseColumnMetadataReader { /** * Create a new instance of the {@link BigQueryColumnMetadataReader}. * * @param connection connection to the remote data source * @param properties user-defined adapter properties * @param identifierConverter converter between source and Exasol identifiers */ public BigQueryColumnMetadataReader(final Connection connection, final AdapterProperties properties, final IdentifierConverter identifierConverter) { super(connection, properties, identifierConverter); } @Override public DataType mapJdbcType(final JdbcTypeDescription jdbcTypeDescription) { if (jdbcTypeDescription.getJdbcType() == Types.TIME) { return DataType.createVarChar(30, DataType.ExaCharset.UTF8); } return super.mapJdbcType(jdbcTypeDescription); } }
mit
github/codeql
javascript/extractor/src/com/semmle/jcorn/SyntaxError.java
392
package com.semmle.jcorn; import com.semmle.js.ast.Position; public class SyntaxError extends RuntimeException { private static final long serialVersionUID = -4883173648492364902L; private final Position position; public SyntaxError(String msg, Position loc, int raisedAt) { super(msg); this.position = loc; } public Position getPosition() { return position; } }
mit
merinhunter/SecureApp
assembler/package-info.java
131
/** * This package provides the necessary classes to slice and compose a file. * * @author Sergio Merino */ package assembler;
mit
DaedalusGame/BetterWithAddons
src/main/java/betterwithaddons/crafting/recipes/PackingRecipe.java
1468
package betterwithaddons.crafting.recipes; import betterwithaddons.crafting.ICraftingResult; import betterwithaddons.util.ItemUtil; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class PackingRecipe { public ICraftingResult output; public List<Ingredient> inputs; public PackingRecipe(List<Ingredient> inputs, ICraftingResult output) { this.output = output; this.inputs = inputs; } public ICraftingResult getOutput(List<ItemStack> inputs, IBlockState compressState) { return this.output.copy(); } public boolean consume(List<ItemStack> inputs, IBlockState compressState, boolean simulate) { inputs = new ArrayList<>(inputs); for (Ingredient ingredient : this.inputs) { boolean matches = false; Iterator<ItemStack> iterator = inputs.iterator(); while(iterator.hasNext()) { ItemStack checkStack = iterator.next(); if(ingredient.apply(checkStack)) { if(!simulate) checkStack.shrink(ItemUtil.getSize(ingredient)); iterator.remove(); matches = true; } } if(!matches) return false; } return true; } }
mit
anba/es6draft
src/main/java/com/github/anba/es6draft/runtime/types/builtins/BuiltinConstructor.java
1758
/** * Copyright (c) André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ package com.github.anba.es6draft.runtime.types.builtins; import java.lang.invoke.MethodHandle; import java.lang.reflect.Method; import com.github.anba.es6draft.runtime.ExecutionContext; import com.github.anba.es6draft.runtime.Realm; import com.github.anba.es6draft.runtime.types.Constructor; /** * <h1>9 Ordinary and Exotic Objects Behaviours</h1> * <ul> * <li>9.3 Built-in Function Objects * </ul> */ public abstract class BuiltinConstructor extends BuiltinFunction implements Constructor { private MethodHandle constructMethod; /** * Constructs a new built-in constructor function. * * @param realm * the realm object * @param name * the function name * @param arity * the function arity */ protected BuiltinConstructor(Realm realm, String name, int arity) { super(realm, name, arity); } /** * Returns `(? extends BuiltinConstructor, ExecutionContext, Constructor, Object[]) {@literal ->} ScriptObject` * method-handle. * * @return the call method handle */ public MethodHandle getConstructMethod() { if (constructMethod == null) { try { Method method = getClass().getDeclaredMethod("construct", ExecutionContext.class, Constructor.class, Object[].class); constructMethod = lookup().unreflect(method); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } return constructMethod; } }
mit
cc-afitz/awesome-services
recommendation/src/main/java/de/codecentric/awesome/recommendation/core/RecommendationLookup.java
979
package de.codecentric.awesome.recommendation.core; import java.util.HashMap; import java.util.Map; /** * Created by afitz on 15.03.16. */ public class RecommendationLookup { private static RecommendationLookup ourInstance = new RecommendationLookup(); private String standardProductRecommendation = "P999"; // Map<User, Product> private final Map<String, String> recommendationMap = new HashMap<String, String>(); public static RecommendationLookup getInstance() { return ourInstance; } private RecommendationLookup() { recommendationMap.put("P00T", "P001"); recommendationMap.put("P001", "P002"); recommendationMap.put("P002", "P003"); recommendationMap.put("P003", "P003"); } public Product getRecommendation (Product product) { return new Product((recommendationMap.containsKey(product.getId()) ? recommendationMap.get(product.getId()) : standardProductRecommendation)); } }
mit
TMAC-Coding/Ported-Blocks
src/net/tmachq/Ported_Blocks/tileentities/renderers/TileEntitySailRenderer.java
2561
package net.tmachq.Ported_Blocks.tileentities.renderers; import java.io.DataInputStream; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import org.lwjgl.opengl.GL11; import net.tmachq.Ported_Blocks.models.SailModel; public class TileEntitySailRenderer extends TileEntitySpecialRenderer { private final SailModel model; public TileEntitySailRenderer() { this.model = new SailModel(); } @Override public void renderTileEntityAt(TileEntity te, double x, double y, double z, float scale) { int rotation = 180; switch (te.getBlockMetadata() % 4) { case 0: rotation = 0; break; case 3: rotation = 90; break; case 2: rotation = 180; break; case 1: rotation = 270; break; } GL11.glPushMatrix(); int i = te.getBlockMetadata(); GL11.glTranslatef((float) x + 0.5F, (float) y + 1.5F, (float) z + 0.5F); GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F); Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation("Ported_Blocks:textures/texturemaps/Sail_HD.png")); GL11.glScalef(1.0F, -1F, -1F); model.render((Entity)null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F); GL11.glPopMatrix(); } private void adjustLightFixture(World world, int i, int j, int k, Block block) { Tessellator tess = Tessellator.instance; float brightness = block.getBlockBrightness(world, i, j, k); int skyLight = world.getLightBrightnessForSkyBlocks(i, j, k, 0); int modulousModifier = skyLight % 65536; int divModifier = skyLight / 65536; tess.setColorOpaque_F(brightness, brightness, brightness); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) modulousModifier, divModifier); } }
mit
nico01f/z-pec
ZimbraWebClient/src/com/zimbra/webClient/build/PackageJammerTask.java
14020
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.webClient.build; import java.io.*; import java.util.*; import java.util.regex.*; import org.apache.tools.ant.*; import org.apache.tools.ant.types.*; public class PackageJammerTask extends Task { // // Constants // private static final Pattern RE_DEFINE = Pattern.compile("^AjxPackage\\.define\\(['\"]([^'\"]+)['\"]\\);?"); private static final Pattern RE_UNDEFINE = Pattern.compile("^AjxPackage\\.undefine\\(['\"]([^'\"]+)['\"]\\);?"); private static final Pattern RE_REQUIRE = Pattern.compile("^AjxPackage\\.require\\(['\"]([^'\"]+)['\"](.*?)\\);?"); private static final Pattern RE_REQUIRE_OBJ = Pattern.compile("^AjxPackage\\.require\\((\\s*\\{\\s*name\\s*:\")?([^'\"]+)['\"](.*?)\\);?"); private static final String OUTPUT_JS = "js"; private static final String OUTPUT_HTML = "html"; private static final String OUTPUT_ALL = "all"; // // Data // // attributes private File destFile; private File jsFile; private File htmlFile; private List<Source> sources = new LinkedList<Source>(); private File dependsFile; private String output = OUTPUT_JS; private String basepath = ""; private String extension = ".js"; private boolean verbose = false; // children private Text prefix; private Text suffix; private List<JammerFiles> files = new LinkedList<JammerFiles>(); // internal state private String depth; private Map<String,Boolean> defines; private boolean isJs = true; private boolean isHtml = false; private boolean isAll = false; // // Public methods // // attributes public void setDestFile(File file) { this.destFile = file; } public void setJsDestFile(File file) { this.jsFile = file; } public void setHtmlDestFile(File file) { this.htmlFile = file; } public void setJsDir(File dir) { Source source = new Source(); source.setDir(dir); this.sources.clear(); this.sources.add(source); } public void setDependsFile(File file) { this.dependsFile = file; } public void setOutput(String output) { this.output = output; this.isAll = OUTPUT_ALL.equals(output); this.isHtml = this.isAll || OUTPUT_HTML.equals(output); this.isJs = this.isAll || OUTPUT_JS.equals(output) || !this.isHtml; } public void setBasePath(String basepath) { this.basepath = basepath; } public void setExtension(String extension) { this.extension = extension; } public void setVerbose(boolean verbose) { this.verbose = verbose; } // children public Text createPrefix() { return this.prefix = new Text(); } public Text createSuffix() { return this.suffix = new Text(); } public FileList createFileList() { JammerFileList fileList = new JammerFileList(); this.files.add(fileList); return fileList; } public FileSet createFileSet() { JammerFileSet fileSet = new JammerFileSet(); this.files.add(fileSet); return fileSet; } public Source createSrc() { Source source = new Source(); this.sources.add(source); return source; } // // Task methods // public void execute() throws BuildException { this.depth = ""; this.defines = new HashMap<String,Boolean>(); PrintWriter jsOut = null; PrintWriter htmlOut = null; PrintWriter dependsOut = null; try { if (this.isJs) { File file = this.jsFile != null ? this.jsFile : this.destFile; log("Jamming to ",file.toString()); jsOut = new PrintWriter(new FileWriter(file)); } if (this.isHtml) { File file = this.htmlFile != null ? this.htmlFile : this.destFile; log("Jamming to ",file.toString()); htmlOut = new PrintWriter(new FileWriter(file)); } if (this.dependsFile != null) { log("Dependencies saved to "+this.dependsFile); dependsOut = new PrintWriter(new FileWriter(this.dependsFile)); } if (this.prefix != null) { PrintWriter out = OUTPUT_JS.equals(this.prefix.output) ? jsOut : htmlOut; if (out != null) { out.println(this.prefix.toString()); } } List<String> packages = new LinkedList<String>(); for (JammerFiles files : this.files) { boolean wrap = files.isWrapped(); boolean isManifest = files.isManifest(); File dir = files.getDir(this.getProject()); for (String filename : files.getFiles(this.getProject())) { File file = new File(dir, filename); String pkg = path2package(stripExt(filename).replace(File.separatorChar, '/')); packages.add(pkg); if (this.isHtml && !isManifest) { printHTML(htmlOut, pkg, files.getBasePath(), files.getExtension()); } jamFile(jsOut, htmlOut, file, pkg, packages, wrap, true, dependsOut); } } if (this.isHtml && packages.size() > 0 && htmlOut != null) { htmlOut.println("<script type=\"text/javascript\">"); for (String pkg : packages) { htmlOut.print("AjxPackage.define(\""); htmlOut.print(pkg); htmlOut.println("\");"); } htmlOut.println("</script>"); } if (this.suffix != null) { PrintWriter out = OUTPUT_JS.equals(this.prefix.output) ? jsOut : htmlOut; if (out != null) { out.println(this.suffix.toString()); } } } catch (IOException e) { throw new BuildException(e); } finally { if (jsOut != null) jsOut.close(); if (htmlOut != null) htmlOut.close(); if (dependsOut != null) dependsOut.close(); } } // // Private methods // private void jamFile(PrintWriter jsOut, PrintWriter htmlOut, File ifile, String pkg, List<String> packages, boolean wrap, boolean top, PrintWriter dependsOut) throws IOException { if (this.verbose) log("file: ",ifile.toString()); BufferedReader in = new BufferedReader(new FileReader(ifile)); boolean isJS = ifile.getName().endsWith(".js"); // "wrap" source if (this.isJs && isJS && pkg != null && wrap && jsOut != null) { jsOut.print("if (AjxPackage.define(\""); jsOut.print(pkg); jsOut.println("\")) {"); } // remember this file if (dependsOut != null) { dependsOut.println(ifile.getCanonicalPath()); dependsOut.flush(); } // read file String line; while ((line = in.readLine()) != null) { // define package String define = matchDefine(line); if (define != null) { if (this.verbose) log("define ", define); this.defines.put(package2path(define), true); continue; } // undefine package String undefine = matchUndefine(line); if (undefine != null) { if (this.verbose) log("undefine ", undefine); this.defines.remove(package2path(undefine)); continue; } // require package String require = matchRequire(line); if (require != null) { if (this.verbose) log("require ", require); String path = package2path(require); if (this.defines.get(path) == null) { packages.add(require); // output script tag if (this.isHtml && !path.endsWith("__all__")) { printHTML(htmlOut, require, null, null); } // implicitly define and jam on! this.defines.put(path, true); File file = this.getFileForPath(path); String odepth = this.verbose ? this.depth : null; if (this.verbose) this.depth += " "; jamFile(jsOut, htmlOut, file, path2package(require), packages, wrap, false, dependsOut); if (this.verbose) this.depth = odepth; } continue; } // leave line intact if (this.isJs && isJS && jsOut != null) { jsOut.println(line); } } if (this.isJs && isJS && pkg != null && wrap && jsOut != null) { jsOut.println("}"); } in.close(); } private File getFileForPath(String path) { String name = path.replace('/',File.separatorChar)+".js"; File file = null; for (Source source : this.sources) { String filename = name; if (source.prefix != null && name.startsWith(source.prefix+"/")) { filename = name.substring(source.prefix.length() + 1); } file = new File(source.dir, filename); if (file.exists()) { break; } } return file; } private void printHTML(PrintWriter out, String pkg, String basePath, String extension) { if (out == null) return; String path = package2path(pkg); out.print("<script type=\"text/javascript\" src=\""); out.print(basePath != null ? basePath : this.basepath); out.print(path); out.print(extension != null ? extension : this.extension); out.println("\"></script>"); } private String matchDefine(String s) { Matcher m = RE_DEFINE.matcher(s); return m.matches() ? m.group(1) : null; } private String matchUndefine(String s) { Matcher m = RE_UNDEFINE.matcher(s); return m.matches() ? m.group(1) : null; } private String matchRequire(String s) { Matcher m = RE_REQUIRE.matcher(s); if (m.matches()){ return m.group(1); } m = RE_REQUIRE_OBJ.matcher(s); if (m.matches()){ return m.group(2); } return null; } private void log(String... ss) { System.out.print(this.depth); for (String s : ss) { System.out.print(s); } System.out.println(); } // // Private functions // private static String package2path(String pkg) { return pkg.replace('.', '/').replaceAll("\\*$", "__all__"); } private static String path2package(String path) { return path.replace('/', '.').replaceAll("\\*$", "__all__"); } private static String stripExt(String fname) { return fname.replaceAll("\\..+$", ""); } // // Classes // private static interface JammerFiles { public boolean isWrapped(); public boolean isManifest(); public String getBasePath(); public String getExtension(); public File getDir(Project project); public String[] getFiles(Project project); } public static class JammerFileList extends FileList implements JammerFiles { // // Data // private boolean wrap = true; private boolean manifest = true; private String basePath; private String extension; // // Public methods // public void setWrap(boolean wrap) { this.wrap = wrap; } public boolean isWrapped() { return this.wrap; } public void setManifest(boolean manifest) { this.manifest = manifest; } public boolean isManifest() { return this.manifest; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getBasePath() { return this.basePath; } public void setExtension(String extension) { this.extension = extension; } public String getExtension() { return this.extension; } } // class JammerFileList public static class JammerFileSet extends FileSet implements JammerFiles { // // Data // private boolean wrap = true; private boolean manifest = true; private String basePath; private String extension; // // Public methods // public String[] getFiles(Project project) { return this.getDirectoryScanner(project).getIncludedFiles(); } public void setWrap(boolean wrap) { this.wrap = wrap; } public boolean isWrapped() { return wrap; } public void setManifest(boolean manifest) { this.manifest = manifest; } public boolean isManifest() { return this.manifest; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getBasePath() { return this.basePath; } public void setExtension(String extension) { this.extension = extension; } public String getExtension() { return this.extension; } } // class JammerFileList public static class Text { public String output = PackageJammerTask.OUTPUT_JS; private StringBuilder str = new StringBuilder(); public void setOutput(String output) { this.output = output; } public void addText(String s) { str.append(s); } public String toString() { return str.toString(); } } public class Source { public File dir; public String prefix; public void setDir(File dir) { this.dir = dir; } public void setPrefix(String prefix) { this.prefix = prefix; } } } // class PackageJammerTask
mit
alphagov/vitruvius
vitruvius.markdown/src/main/java/uk/gov/prototype/vitruvius/parser/validator/ValidationMessage.java
1327
package uk.gov.prototype.vitruvius.parser.validator; import java.util.List; public class ValidationMessage { private String message; private ValidationType type; public ValidationMessage() { } public ValidationMessage(String message, ValidationType type) { this.message = message; this.type = type; } public String getMessage() { return message; } public ValidationType getType() { return type; } @Override public String toString() { return "ValidationMessage{" + "message='" + message + '\'' + ", type=" + type + '}'; } public enum ValidationType { ERROR, WARNING } public static ValidationMessage createErrorMessage(String message) { return new ValidationMessage(message, ValidationType.ERROR); } public static ValidationMessage createWarning(String message) { return new ValidationMessage(message, ValidationType.WARNING); } public static boolean hasErrors(List<ValidationMessage> messages) { for (ValidationMessage validationMessage : messages) { if (validationMessage.getType() == ValidationType.ERROR) { return true; } } return false; } }
mit
longluo/AndroidDemo
app/src/main/java/com/longluo/demo/widget/swipelistview/SwipeListView.java
20482
package com.longluo.demo.widget.swipelistview; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewConfigurationCompat; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; import com.longluo.demo.R; import java.util.List; /** * ListView subclass that provides the swipe functionality */ public class SwipeListView extends ListView { /** * log tag */ public final static String TAG = "SwipeListView"; /** * whether debug */ public final static boolean DEBUG = false; /** * Used when user want change swipe list mode on some rows */ public final static int SWIPE_MODE_DEFAULT = -1; /** * Disables all swipes */ public final static int SWIPE_MODE_NONE = 0; /** * Enables both left and right swipe */ public final static int SWIPE_MODE_BOTH = 1; /** * Enables right swipe */ public final static int SWIPE_MODE_RIGHT = 2; /** * Enables left swipe */ public final static int SWIPE_MODE_LEFT = 3; /** * Binds the swipe gesture to reveal a view behind the row (Drawer style) */ public final static int SWIPE_ACTION_REVEAL = 0; /** * Dismisses the cell when swiped over */ public final static int SWIPE_ACTION_DISMISS = 1; /** * Marks the cell as checked when swiped and release */ public final static int SWIPE_ACTION_CHOICE = 2; /** * No action when swiped */ public final static int SWIPE_ACTION_NONE = 3; /** * Default ids for front view */ public final static String SWIPE_DEFAULT_FRONT_VIEW = "swipelist_frontview"; /** * Default id for back view */ public final static String SWIPE_DEFAULT_BACK_VIEW = "swipelist_backview"; /** * Indicates no movement */ private final static int TOUCH_STATE_REST = 0; /** * State scrolling x position */ private final static int TOUCH_STATE_SCROLLING_X = 1; /** * State scrolling y position */ private final static int TOUCH_STATE_SCROLLING_Y = 2; private int touchState = TOUCH_STATE_REST; private float lastMotionX; private float lastMotionY; private int touchSlop; int swipeFrontView = 0; int swipeBackView = 0; /** * Internal listener for common swipe events */ private SwipeListViewListener swipeListViewListener; /** * Internal touch listener */ private SwipeListViewTouchListener touchListener; /** * If you create a View programmatically you need send back and front identifier * * @param context Context * @param swipeBackView Back Identifier * @param swipeFrontView Front Identifier */ public SwipeListView(Context context, int swipeBackView, int swipeFrontView) { super(context); this.swipeFrontView = swipeFrontView; this.swipeBackView = swipeBackView; init(null); } /** * @see android.widget.ListView#ListView(android.content.Context, android.util.AttributeSet) */ public SwipeListView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } /** * @see android.widget.ListView#ListView(android.content.Context, android.util.AttributeSet, int) */ public SwipeListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } /** * Init ListView * * @param attrs AttributeSet */ private void init(AttributeSet attrs) { int swipeMode = SWIPE_MODE_BOTH; boolean swipeOpenOnLongPress = true; boolean swipeCloseAllItemsWhenMoveList = true; long swipeAnimationTime = 0; float swipeOffsetLeft = 0; float swipeOffsetRight = 0; int swipeDrawableChecked = 0; int swipeDrawableUnchecked = 0; int swipeActionLeft = SWIPE_ACTION_REVEAL; int swipeActionRight = SWIPE_ACTION_REVEAL; if (attrs != null) { TypedArray styled = getContext().obtainStyledAttributes(attrs, R.styleable.SwipeListView); swipeMode = styled.getInt(R.styleable.SwipeListView_swipeMode, SWIPE_MODE_BOTH); swipeActionLeft = styled.getInt(R.styleable.SwipeListView_swipeActionLeft, SWIPE_ACTION_REVEAL); swipeActionRight = styled.getInt(R.styleable.SwipeListView_swipeActionRight, SWIPE_ACTION_REVEAL); swipeOffsetLeft = styled.getDimension(R.styleable.SwipeListView_swipeOffsetLeft, 0); swipeOffsetRight = styled.getDimension(R.styleable.SwipeListView_swipeOffsetRight, 0); swipeOpenOnLongPress = styled.getBoolean(R.styleable.SwipeListView_swipeOpenOnLongPress, true); swipeAnimationTime = styled.getInteger(R.styleable.SwipeListView_swipeAnimationTime, 0); swipeCloseAllItemsWhenMoveList = styled.getBoolean(R.styleable.SwipeListView_swipeCloseAllItemsWhenMoveList, true); swipeDrawableChecked = styled.getResourceId(R.styleable.SwipeListView_swipeDrawableChecked, 0); swipeDrawableUnchecked = styled.getResourceId(R.styleable.SwipeListView_swipeDrawableUnchecked, 0); swipeFrontView = styled.getResourceId(R.styleable.SwipeListView_swipeFrontView, 0); swipeBackView = styled.getResourceId(R.styleable.SwipeListView_swipeBackView, 0); styled.recycle(); } if (swipeFrontView == 0 || swipeBackView == 0) { swipeFrontView = getContext().getResources().getIdentifier(SWIPE_DEFAULT_FRONT_VIEW, "id", getContext().getPackageName()); swipeBackView = getContext().getResources().getIdentifier(SWIPE_DEFAULT_BACK_VIEW, "id", getContext().getPackageName()); if (swipeFrontView == 0 || swipeBackView == 0) { throw new RuntimeException(String.format("You forgot the attributes swipeFrontView or swipeBackView. You can add this attributes or use '%s' and '%s' identifiers", SWIPE_DEFAULT_FRONT_VIEW, SWIPE_DEFAULT_BACK_VIEW)); } } final ViewConfiguration configuration = ViewConfiguration.get(getContext()); touchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); touchListener = new SwipeListViewTouchListener(this, swipeFrontView, swipeBackView); if (swipeAnimationTime > 0) { touchListener.setAnimationTime(swipeAnimationTime); } touchListener.setRightOffset(swipeOffsetRight); touchListener.setLeftOffset(swipeOffsetLeft); touchListener.setSwipeActionLeft(swipeActionLeft); touchListener.setSwipeActionRight(swipeActionRight); touchListener.setSwipeMode(swipeMode); touchListener.setSwipeClosesAllItemsWhenListMoves(swipeCloseAllItemsWhenMoveList); touchListener.setSwipeOpenOnLongPress(swipeOpenOnLongPress); touchListener.setSwipeDrawableChecked(swipeDrawableChecked); touchListener.setSwipeDrawableUnchecked(swipeDrawableUnchecked); setOnTouchListener(touchListener); setOnScrollListener(touchListener.makeScrollListener()); } /** * Recycle cell. This method should be called from getView in Adapter when use SWIPE_ACTION_CHOICE * * @param convertView parent view * @param position position in list */ public void recycle(View convertView, int position) { touchListener.reloadChoiceStateInView(convertView.findViewById(swipeFrontView), position); touchListener.reloadSwipeStateInView(convertView.findViewById(swipeFrontView), position); // Clean pressed state (if dismiss is fire from a cell, to this cell, with a press drawable, in a swipelistview // when this cell will be recycle it will still have his pressed state. This ensure the pressed state is // cleaned. for (int j = 0; j < ((ViewGroup) convertView).getChildCount(); ++j) { View nextChild = ((ViewGroup) convertView).getChildAt(j); nextChild.setPressed(false); } } /** * Get if item is selected * * @param position position in list * @return */ public boolean isChecked(int position) { return touchListener.isChecked(position); } /** * Get positions selected * * @return */ public List<Integer> getPositionsSelected() { return touchListener.getPositionsSelected(); } /** * Count selected * * @return */ public int getCountSelected() { return touchListener.getCountSelected(); } /** * Unselected choice state in item */ public void unselectedChoiceStates() { touchListener.unselectedChoiceStates(); } /** * @see android.widget.ListView#setAdapter(android.widget.ListAdapter) */ @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); touchListener.resetItems(); if (null != adapter) { adapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { super.onChanged(); onListChanged(); touchListener.resetItems(); } }); } } /** * Dismiss item * * @param position Position that you want open */ public void dismiss(int position) { int height = touchListener.dismiss(position); if (height > 0) { touchListener.handlerPendingDismisses(height); } else { int[] dismissPositions = new int[1]; dismissPositions[0] = position; onDismiss(dismissPositions); touchListener.resetPendingDismisses(); } } /** * Dismiss items selected */ public void dismissSelected() { List<Integer> list = touchListener.getPositionsSelected(); int[] dismissPositions = new int[list.size()]; int height = 0; for (int i = 0; i < list.size(); i++) { int position = list.get(i); dismissPositions[i] = position; int auxHeight = touchListener.dismiss(position); if (auxHeight > 0) { height = auxHeight; } } if (height > 0) { touchListener.handlerPendingDismisses(height); } else { onDismiss(dismissPositions); touchListener.resetPendingDismisses(); } touchListener.returnOldActions(); } /** * Open ListView's item * * @param position Position that you want open */ public void openAnimate(int position) { touchListener.openAnimate(position); } /** * Close ListView's item * * @param position Position that you want open */ public void closeAnimate(int position) { touchListener.closeAnimate(position); } /** * Notifies onDismiss * * @param reverseSortedPositions All dismissed positions */ protected void onDismiss(int[] reverseSortedPositions) { if (swipeListViewListener != null) { swipeListViewListener.onDismiss(reverseSortedPositions); } } /** * Start open item * * @param position list item * @param action current action * @param right to right */ protected void onStartOpen(int position, int action, boolean right) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onStartOpen(position, action, right); } } /** * Start close item * * @param position list item * @param right */ protected void onStartClose(int position, boolean right) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onStartClose(position, right); } } /** * Notifies onClickFrontView * * @param position item clicked */ protected void onClickFrontView(int position) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onClickFrontView(position); } } /** * Notifies onClickBackView * * @param position back item clicked */ protected void onClickBackView(int position) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onClickBackView(position); } } /** * Notifies onOpened * * @param position Item opened * @param toRight If should be opened toward the right */ protected void onOpened(int position, boolean toRight) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onOpened(position, toRight); } } /** * Notifies onClosed * * @param position Item closed * @param fromRight If open from right */ protected void onClosed(int position, boolean fromRight) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onClosed(position, fromRight); } } /** * Notifies onChoiceChanged * * @param position position that choice * @param selected if item is selected or not */ protected void onChoiceChanged(int position, boolean selected) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onChoiceChanged(position, selected); } } /** * User start choice items */ protected void onChoiceStarted() { if (swipeListViewListener != null) { swipeListViewListener.onChoiceStarted(); } } /** * User end choice items */ protected void onChoiceEnded() { if (swipeListViewListener != null) { swipeListViewListener.onChoiceEnded(); } } /** * User is in first item of list */ protected void onFirstListItem() { if (swipeListViewListener != null) { swipeListViewListener.onFirstListItem(); } } /** * User is in last item of list */ protected void onLastListItem() { if (swipeListViewListener != null) { swipeListViewListener.onLastListItem(); } } /** * Notifies onListChanged */ protected void onListChanged() { if (swipeListViewListener != null) { swipeListViewListener.onListChanged(); } } /** * Notifies onMove * * @param position Item moving * @param x Current position */ protected void onMove(int position, float x) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { swipeListViewListener.onMove(position, x); } } protected int changeSwipeMode(int position) { if (swipeListViewListener != null && position != ListView.INVALID_POSITION) { return swipeListViewListener.onChangeSwipeMode(position); } return SWIPE_MODE_DEFAULT; } /** * Sets the Listener * * @param swipeListViewListener Listener */ public void setSwipeListViewListener(SwipeListViewListener swipeListViewListener) { this.swipeListViewListener = swipeListViewListener; } /** * Resets scrolling */ public void resetScrolling() { touchState = TOUCH_STATE_REST; } /** * Set offset on right * * @param offsetRight Offset */ public void setOffsetRight(float offsetRight) { touchListener.setRightOffset(offsetRight); } /** * Set offset on left * * @param offsetLeft Offset */ public void setOffsetLeft(float offsetLeft) { touchListener.setLeftOffset(offsetLeft); } /** * Set if all items opened will be closed when the user moves the ListView * * @param swipeCloseAllItemsWhenMoveList */ public void setSwipeCloseAllItemsWhenMoveList(boolean swipeCloseAllItemsWhenMoveList) { touchListener.setSwipeClosesAllItemsWhenListMoves(swipeCloseAllItemsWhenMoveList); } /** * Sets if the user can open an item with long pressing on cell * * @param swipeOpenOnLongPress */ public void setSwipeOpenOnLongPress(boolean swipeOpenOnLongPress) { touchListener.setSwipeOpenOnLongPress(swipeOpenOnLongPress); } /** * Set swipe mode * * @param swipeMode */ public void setSwipeMode(int swipeMode) { touchListener.setSwipeMode(swipeMode); } /** * Return action on left * * @return Action */ public int getSwipeActionLeft() { return touchListener.getSwipeActionLeft(); } /** * Set action on left * * @param swipeActionLeft Action */ public void setSwipeActionLeft(int swipeActionLeft) { touchListener.setSwipeActionLeft(swipeActionLeft); } /** * Return action on right * * @return Action */ public int getSwipeActionRight() { return touchListener.getSwipeActionRight(); } /** * Set action on right * * @param swipeActionRight Action */ public void setSwipeActionRight(int swipeActionRight) { touchListener.setSwipeActionRight(swipeActionRight); } /** * Sets animation time when user drops cell * * @param animationTime milliseconds */ public void setAnimationTime(long animationTime) { touchListener.setAnimationTime(animationTime); } /** * @see android.widget.ListView#onInterceptTouchEvent(android.view.MotionEvent) */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { int action = MotionEventCompat.getActionMasked(ev); final float x = ev.getX(); final float y = ev.getY(); if (isEnabled() && touchListener.isSwipeEnabled()) { if (touchState == TOUCH_STATE_SCROLLING_X) { return touchListener.onTouch(this, ev); } switch (action) { case MotionEvent.ACTION_MOVE: checkInMoving(x, y); return touchState == TOUCH_STATE_SCROLLING_Y; case MotionEvent.ACTION_DOWN: super.onInterceptTouchEvent(ev); touchListener.onTouch(this, ev); touchState = TOUCH_STATE_REST; lastMotionX = x; lastMotionY = y; return false; case MotionEvent.ACTION_CANCEL: touchState = TOUCH_STATE_REST; break; case MotionEvent.ACTION_UP: touchListener.onTouch(this, ev); return touchState == TOUCH_STATE_SCROLLING_Y; default: break; } } return super.onInterceptTouchEvent(ev); } /** * Check if the user is moving the cell * * @param x Position X * @param y Position Y */ private void checkInMoving(float x, float y) { final int xDiff = (int) Math.abs(x - lastMotionX); final int yDiff = (int) Math.abs(y - lastMotionY); final int touchSlop = this.touchSlop; boolean xMoved = xDiff > touchSlop; boolean yMoved = yDiff > touchSlop; if (xMoved) { touchState = TOUCH_STATE_SCROLLING_X; lastMotionX = x; lastMotionY = y; } if (yMoved) { touchState = TOUCH_STATE_SCROLLING_Y; lastMotionX = x; lastMotionY = y; } } /** * Close all opened items */ public void closeOpenedItems() { touchListener.closeOpenedItems(); } }
mit
pineasaurusrex/inference-engine
src/com/github/pineasaurusrex/inference_engine/Model.java
1821
package com.github.pineasaurusrex.inference_engine; import java.util.HashMap; /** * Partially or fully assigned model * A model represents a possible representation of the propositional symbol states in the KB */ public class Model { private HashMap<PropositionalSymbol, Boolean> symbolValues = new HashMap<>(); public boolean holdsTrue(Sentence sentence) { if (sentence.isPropositionSymbol()) { return symbolValues.get(sentence); } else { switch(sentence.getConnective()) { case NOT: return !holdsTrue(sentence.getOperand(0)); case AND: return holdsTrue(sentence.getOperand(0)) && holdsTrue(sentence.getOperand(1)); case OR: return holdsTrue(sentence.getOperand(0)) || holdsTrue(sentence.getOperand(1)); case IMPLICATION: return !holdsTrue(sentence.getOperand(0)) || holdsTrue(sentence.getOperand(1)); case BICONDITIONAL: return holdsTrue(sentence.getOperand(0)) == holdsTrue(sentence.getOperand(1)); } } return false; } public boolean holdsTrue(KnowledgeBase kb) { return kb.getSentences().parallelStream() .map(this::holdsTrue) .allMatch(Boolean::booleanValue); } /** * Returns a new model, with the union of the results of the old model and the result passed in * @param symbol the symbol to merge in * @param b the value to set * @return a new Model object */ public Model union(PropositionalSymbol symbol, boolean b) { Model m = new Model(); m.symbolValues.putAll(this.symbolValues); m.symbolValues.put(symbol, b); return m; } }
mit
jwfwessels/AFK
src/afk/ge/tokyo/ems/nodes/LifeNode.java
1391
/* * Copyright (c) 2013 Triforce - in association with the University of Pretoria and Epi-Use <Advance/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package afk.ge.tokyo.ems.nodes; import afk.ge.ems.Node; import afk.ge.tokyo.ems.components.Life; /** * * @author Daniel */ public class LifeNode extends Node { public Life life; }
mit
VishnuPrabhu/EHS
app/src/main/java/com/sms4blood/emergencyhealthservices/util/AppUtil.java
5042
package com.sms4blood.emergencyhealthservices.util; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.widget.Toast; import com.sms4blood.emergencyhealthservices.Sms; import com.sms4blood.emergencyhealthservices.app.EhsApplication; import java.text.DecimalFormat; /** * Created by Vishnu on 8/1/2015. */ public class AppUtil extends Util { public static boolean callNumber(String phoneNumber) { boolean isValidPhoneNumber = checkPhoneNumber(phoneNumber); if (isValidPhoneNumber) { String callUri = "tel:" + phoneNumber; Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(callUri)); callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(callIntent); } else { Toast.makeText(EhsApplication.getContext(), "Invalid phone number.", Toast.LENGTH_SHORT).show(); } return isValidPhoneNumber; } public static boolean sendSms(String phoneNumber, String message) { boolean isValidPhoneNumber = checkPhoneNumber(phoneNumber); if (isValidPhoneNumber) { // /*It is better to let the android manage the sms sending task using native messaging app*/ // Intent smsIntent = new Intent(Intent.ACTION_VIEW); // // Invokes only SMS/MMS clients // smsIntent.setType("vnd.android-dir/mms-sms"); // // Specify the Phone Number // smsIntent.putExtra("address", phoneNumber); // // Specify the Message // smsIntent.putExtra("sms_body", message); // smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // try { // startActivity(smsIntent); // } catch (Exception e) { // e.printStackTrace(); // Toast.makeText(EhsApplication.getContext(), "Unable to send sms to this number.", Toast.LENGTH_SHORT) // .show(); // } Intent i=new Intent(EhsApplication.getContext(), Sms.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Bundle bundle = new Bundle(); bundle.putString("mobileno",phoneNumber); i.putExtras(bundle); startActivity(i); } else { Toast.makeText(EhsApplication.getContext(), "Invalid phone number.", Toast.LENGTH_SHORT).show(); } return isValidPhoneNumber; } public static boolean showMap(String latitude, String longitude) { try { if (!TextUtils.isEmpty(latitude) && (!TextUtils.isEmpty(longitude))) { Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + "," + longitude); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent.setPackage("com.google.android.apps.maps"); mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(mapIntent); return true; } else { Toast.makeText(EhsApplication.getContext(), "Address not available.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean showMap(String address) { try { if (!TextUtils.isEmpty(address)) { String encodedAddress = address.replaceAll("\n", " "); Uri gmmIntentUri = Uri.parse("google.navigation:q=" + encodedAddress); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent.setPackage("com.google.android.apps.maps"); mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(mapIntent); return true; } else { Toast.makeText(EhsApplication.getContext(), "Address not available.", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } return false; } /** * @param fromLatitude * @param fromLongitude * @param toLatitude * @param toLongitude * @return distance between the two latitudes and longitudes in kms. */ public static double calculateDistance(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude) { float results[] = new float[1]; try { Location.distanceBetween(fromLatitude, fromLongitude, toLatitude, toLongitude, results); } catch (Exception e) { if (e != null) e.printStackTrace(); } int dist = (int) results[0]; if(dist<=0) { return 0D; } DecimalFormat decimalFormat = new DecimalFormat("#.##"); results[0]/=1000D; String distance = decimalFormat.format(results[0]); double d = Double.parseDouble(distance); return d; } }
mit
tomoya0x00/FrugalityCalc
app/src/main/java/miwax/java_conf/gr/jp/frugalitycalc/view/MainActivity.java
2423
package miwax.java_conf.gr.jp.frugalitycalc.view; import android.app.AlertDialog; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import miwax.java_conf.gr.jp.frugalitycalc.R; import miwax.java_conf.gr.jp.frugalitycalc.databinding.ActivityMainBinding; import miwax.java_conf.gr.jp.frugalitycalc.util.messenger.ShowAlertDialogMessage; import miwax.java_conf.gr.jp.frugalitycalc.viewmodel.MainViewModel; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.subscriptions.CompositeSubscription; public class MainActivity extends AppCompatActivity { private final String VIEW_MODEL = "VIEW_MODEL"; private ActivityMainBinding binding; private MainViewModel mainViewModel; private CompositeSubscription subscriptions = new CompositeSubscription(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_main); if (savedInstanceState != null) { mainViewModel = savedInstanceState.getParcelable(VIEW_MODEL); } else { mainViewModel = new MainViewModel(); } binding.setViewModel(mainViewModel); // ダイアログ表示のメッセージ受信 subscriptions.add( mainViewModel.getMessenger().register(ShowAlertDialogMessage.class) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<ShowAlertDialogMessage>() { @Override public void call(ShowAlertDialogMessage message) { showAlertDialog(message.getTitleId(), message.getTextId()); } }) ); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(VIEW_MODEL, mainViewModel); } @Override protected void onDestroy() { mainViewModel.unsubscribe(); super.onDestroy(); } private void showAlertDialog(int titleId, int textId) { new AlertDialog.Builder(this) .setTitle(this.getString(titleId)) .setMessage(this.getString(textId)) .setPositiveButton("OK", null) .show(); } }
mit
MrGenga/BouncyBall
src/main/java/io/github/jython234/jraklibplus/protocol/raknet/NACKPacket.java
1189
/** * JRakLibPlus is not affiliated with Jenkins Software LLC or RakNet. * This software is an enhanced port of RakLib https://github.com/PocketMine/RakLib. * This file is part of JRakLibPlus. * * JRakLibPlus 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. * * JRakLibPlus 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 JRakLibPlus. If not, see <http://www.gnu.org/licenses/>. */ package io.github.jython234.jraklibplus.protocol.raknet; import static io.github.jython234.jraklibplus.JRakLibPlus.*; /** * Created by jython234 on 9/12/2015. * * @author RedstoneLamp Team */ public class NACKPacket extends AcknowledgePacket { @Override public byte getPID() { return NACK; } }
mit
hosaka893/junit-tutorial
src/test/java/junit/tutorial/calculator/CalculatorTest.java
1401
// Copyright(c) 2013 GROWTH XPARTNERS, Incorporated. // // package junit.tutorial.calculator; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class CalculatorTest { @Test public void multiplyで3と4の乗算結果が取得できる() { Calculator calc = new Calculator(); int expected = 12; int actual = calc.multiply(3, 4); assertThat(actual, is(expected)); } @Test public void multiplyで5と7の乗算結果が取得できる() { Calculator calc = new Calculator(); int expected = 35; int actual = calc.multiply(5, 7); assertThat(actual, is(expected)); } @Test public void divideで3と2の除算結果が取得できる() { Calculator calc = new Calculator(); float expected = 1.5f; float actual = calc.divide(3, 2); assertThat(actual, is(expected)); } @Test(expected = IllegalArgumentException.class) public void divideで5と0のときIllegalArgumentExceptionを送出する() { Calculator calc = new Calculator(); calc.divide(5, 0); } public static void main(String[] args) { org.junit.runner.JUnitCore.main(CalculatorTest.class.getName()); } }
mit
MjAbuz/influent
influent-server/src/main/java/influent/server/sql/SQLFrom.java
2160
/* * Copyright (C) 2013-2015 Uncharted Software Inc. * * Property of Uncharted(TM), formerly Oculus Info Inc. * http://uncharted.software/ * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package influent.server.sql; /** * Represents a SQL FROM clause. This can be used to create complicated * sub-selects that can still be chained together. * * @author cregnier * */ public interface SQLFrom { /** * Sets the name of table to select results from.<br> * This cannot be set if {@link #fromQuery(SQLSelect)} has also been set. * @param name * The name of an existing table in the database * @return */ SQLFrom table(String name); /** * Adds an alias for the table. * @param alias * The name of the alias that will be used in the SQL statement. * @return */ SQLFrom as(String alias); /** * Sets a subquery that should be used to select results from.<br> * This cannot be set if {@link #table(String)} has also been set. * @param fromQuery * A subquery to select results from. * @return */ SQLFrom fromQuery(SQLSelect fromQuery); }
mit
NewEconomyMovement/nem.core
src/main/java/org/nem/core/model/MultisigSignatureTransactionComparator.java
854
package org.nem.core.model; import org.nem.core.utils.ArrayUtils; import java.util.Comparator; /** * A custom comparator for comparing MultisigSignatureTransaction objects. * <br> * This comparator only looks at the transaction signer and other hash. */ public class MultisigSignatureTransactionComparator implements Comparator<MultisigSignatureTransaction> { @Override public int compare(final MultisigSignatureTransaction lhs, final MultisigSignatureTransaction rhs) { final Address lhsAddress = lhs.getSigner().getAddress(); final Address rhsAddress = rhs.getSigner().getAddress(); final int addressCompareResult = lhsAddress.compareTo(rhsAddress); if (addressCompareResult != 0) { return addressCompareResult; } return ArrayUtils.compare(lhs.getOtherTransactionHash().getRaw(), rhs.getOtherTransactionHash().getRaw()); } }
mit
4lexBaum/projekt-5s-dhbw
Backend/src/main/java/model/dataModels/ManufacturingData.java
1974
package model.dataModels; /** * Class ManufacturingData. * @author Daniel * */ public class ManufacturingData { private String customerNumber; private String materialNumber; private String orderNumber; private String timeStamp; private MachineData[] machineData; private SpectralAnalysisData analysisData; /** * Constructor. */ public ManufacturingData() {} /** * Creates a string representation * of this object. * @return */ @Override public String toString() { return customerNumber + " " + materialNumber + " " + orderNumber + " " + timeStamp + " " + machineData + " " + analysisData; } /* * Getters and Setters. */ /** * Adds erp data. * @param data */ public void setErpData(ErpData data) { this.customerNumber = data.getCustomerNumber(); this.materialNumber = data.getMaterialNumber(); this.orderNumber = data.getOrderNumber(); this.timeStamp = data.getTimeStamp(); } /** * Appends machine data to the array. * @param data */ public void appendMachineData(MachineData data) { if(this.machineData == null) { this.machineData = new MachineData[1]; machineData[0] = data; } else { int length = this.machineData.length; MachineData[] temp = new MachineData[length + 1]; for(int i = 0; i < length; i++) { temp[i] = this.machineData[i]; } temp[length] = data; this.machineData = temp; } } /** * Adds spectral analysis data. * @param analysisData */ public void setAnalysisData(SpectralAnalysisData analysisData) { this.analysisData = analysisData; } public String getCustomerNumber() { return customerNumber; } public String getMaterialNumber() { return materialNumber; } public String getOrderNumber() { return orderNumber; } public String getTimeStamp() { return timeStamp; } public MachineData[] getMachineData() { return machineData; } public SpectralAnalysisData getAnalysisData() { return analysisData; } }
mit
thebachchaoproject/safemaps
safemaps_android/src/com/tbp/safemaps/MarkUnsafe.java
1557
package com.tbp.safemaps; import the.safemaps.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MarkUnsafe extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.marksafe); //Button back = (Button)findViewById(R.id.mbuttonBack); Button done = (Button)findViewById(R.id.done); done.setOnClickListener(onClickListener); // back.setOnClickListener(onClickListener); } private OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { switch(v.getId()){ // case R.id.go: // Intent go= new Intent(Markunsafe.this,mapdirections.class); //startActivity(go); //break; } } }; public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()) { case R.id.action_bar: //Toast.makeText(getBaseContext(), "back", Toast.LENGTH_SHORT).show(); Intent back= new Intent(MarkUnsafe.this,MainActivity.class); startActivity(back); break; } return true; } }
mit
Pankiev/MMORPG_Prototype
Client/core/src/pl/mmorpg/prototype/client/exceptions/UnknownSpellException.java
262
package pl.mmorpg.prototype.client.exceptions; public class UnknownSpellException extends GameException { public UnknownSpellException(String identifier) { super(identifier); } public UnknownSpellException(Class<?> type) { super(type.getName()); } }
mit
jonasrottmann/realm-browser
realm-browser/src/main/java/de/jonasrottmann/realmbrowser/helper/ScrollAwareFABBehavior.java
2812
/* * Copyright 2015 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 de.jonasrottmann.realmbrowser.helper; import android.content.Context; import android.support.annotation.RestrictTo; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior { public ScrollAwareFABBehavior(Context context, AttributeSet attrs) { // This is mandatory if we're assigning the behavior straight from XML super(); } @Override public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child, final View directTargetChild, final View target, final int nestedScrollAxes) { // Ensure we react to vertical scrolling return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes); } @Override public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child, final View target, final int dxConsumed, final int dyConsumed, final int dxUnconsumed, final int dyUnconsumed) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed); if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) { // User scrolled down and the FAB is currently visible -> hide the FAB child.hide(new FloatingActionButton.OnVisibilityChangedListener() { @Override public void onHidden(FloatingActionButton fab) { // Workaround for bug in support libs (http://stackoverflow.com/a/41641841/2192848) super.onHidden(fab); fab.setVisibility(View.INVISIBLE); } }); } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) { // User scrolled up and the FAB is currently not visible -> show the FAB child.show(); } } }
mit
valentin7/pianoHero
src/main/java/edu/brown/cs/pianoHeroFiles/PianoHeroFileHandler.java
11443
package edu.brown.cs.pianoHeroFiles; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class PianoHeroFileHandler { public void doFileHandling() { try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8"))) { File dir = new File("pianoHeroFiles/songImages/"); File actualFile = new File(dir, "hey"); File f = new File("C:\\pianoHeroFiles\\songImages\\kiwiCover.png"); System.out.println(f.getName().toString()); File newDir = new File("pianoHeroFiles/songImages/new/"); File newFile = new File(f, "kiwi2.png"); // System.out.println(actualFile); writer.write("something"); writeFile("pianoHeroFiles/test.txt", "something, brah."); Set<File> allMp3s = new HashSet<File>(); File mp3Dir = new File("pianoHeroFiles/songs/"); getAllFilesAndFolder(mp3Dir, allMp3s); for (File fm : allMp3s) { System.out.println("song:"); System.out.println(fm); if (!fm.isDirectory()) { File dest = new File(fm.getParentFile().toString(), "new" + fm.getName()); copyFile(fm, dest); } } } catch (IOException e) { System.err.println("ERROR: error saving the file"); e.printStackTrace(); } } /** * Saves an image to file directory and returns its saved path as a string * * @param image * file * @return path saved */ public static String saveImage(String imageName) { try { File image = new File("Images/" + imageName); // File imageDir = new File("pianoHeroFiles/songImages/"); File imageDir = new File("src/main/resources/static/img/"); File saveDir = new File("../img/"); File dest = new File(imageDir, "" + image.getName()); File savedDir = new File(saveDir, "" + image.getName()); copyFile(image, dest); return savedDir.getPath(); } catch (IOException e) { System.err.println("ERROR: error saving image"); } return null; } /** * Saves an mp3 file directory and returns its saved path as a string * * @param mp3 * file * @return path saved */ public static String saveMp3(String mp3Name) { try { File mp3 = new File("Songs/" + mp3Name); // File songsDir = new File("pianoHeroFiles/songs/"); File songsDir = new File("src/main/resources/static/songs/"); File saveDir = new File("../songs/"); File dest = new File(songsDir, "" + mp3.getName()); File saveDest = new File(saveDir, "" + mp3.getName()); copyFile(mp3, dest); return saveDest.getPath(); } catch (IOException e) { System.err.println("ERROR: error saving image"); } return null; } /** * Saves the 1d-array boolean of keystrokes for a given song id. * * @param keyStrokes * : 1d-array of booleans * @param songId * : int, the song id * @return String of the path where the keystrokes file was saved. */ public static String saveSongKeystrokes(boolean[] keyStrokes, int songId) { String path = "pianoHeroFiles/songKeyStrokes/"; String keyStrokesID = songId + "_keyStrokes.txt"; String keyStrokesPath = path + keyStrokesID; try (PrintWriter writer = new PrintWriter(keyStrokesPath, "UTF-8")) { String line = ""; // this is for the fake, testing songs. if (keyStrokes == null) { System.out.println("FAKEEEEE"); line += "1000100100010100010101"; } for (int i = 0; i < keyStrokes.length; i++) { String add = keyStrokes[i] ? "1" : "0"; line += add; } writer.println(line); writer.close(); } catch (IOException e) { System.err .println("ERROR: error saving keystrokes for songId: " + songId); } return keyStrokesPath; } /** * Saves a 2d-array boolean of keystrokes for a given song id. * * @param keyStrokes * : 2d-array of booleans * @param songId * : int, the song id * @return String of the path where the keystrokes file was saved. */ public static String save2DSongKeystrokes(boolean[][] keyStrokes, int songId) { String path = "pianoHeroFiles/songKeyStrokes/"; String keyStrokesID = songId + "_keyStrokes.txt"; String keyStrokesPath = path + keyStrokesID; try (PrintWriter writer = new PrintWriter(keyStrokesPath, "UTF-8")) { for (int i = 0; i < keyStrokes.length; i++) { String line = ""; for (int j = 0; j < keyStrokes[i].length; j++) { String add = keyStrokes[i][j] ? "1" : "0"; line += add; } writer.println(line); } writer.close(); } catch (IOException e) { System.err .println("ERROR: error saving keystrokes for songId: " + songId); } return keyStrokesPath; } /** * Converts a 1d array of booleans to a 2d array of booleans. * * @param array * : the initial 1d array * @param length * : the length of the partitions. * @return the converted 2d array. */ public static boolean[][] convert1DBooleansTo2D(boolean[] array, int length) { boolean[][] boolean2d = new boolean[length][array.length / length]; for (int i = 0; i < length; i++) { for (int j = 0; j < array.length / length; j++) { boolean2d[i][j] = array[j + i * length]; } } return boolean2d; } /** * Converts a 2d array of booleans to a 1d array of booleans. * * @param array * : the initial 2d array * @return the converted 1d array. */ public static boolean[] convert2DBooleansTo1D(boolean[][] boolean2D) { boolean[] boolean1D = new boolean[boolean2D.length * boolean2D[0].length]; for (int i = 0; i < boolean2D.length; i++) { for (int j = 0; j < boolean2D[i].length; j++) { assert (boolean2D[i].length == boolean2D[0].length); boolean1D[j + i * boolean2D.length] = boolean2D[i][j]; } } return boolean1D; } /** * Returns a file from a given string path * * @param path * string representing the file path * @return the File in the path */ public static File getFileFromPath(String path) { File file = new File(path); return file; } /** * Saves all the files and folders in a set, for a given initial folder. * * @param folder * the initial folder to look all files for. * @param all * the set of files to save on */ public static void getAllFilesAndFolder(File folder, Set<File> all) { all.add(folder); if (folder.isFile()) { return; } for (File file : folder.listFiles()) { if (file.isFile()) { all.add(file); } if (file.isDirectory()) { getAllFilesAndFolder(file, all); } } } /** * Gets the file of the strokes and converts it to a 1d boolean array to * return * * @param fileName * the file name of the keystrokes * @return the 1d array of the strokes */ public static boolean[] getStrokesArray(String fileName) { // This will reference one line at a time String line = null; // FileReader reads text files in the default encoding. try (FileReader fileReader = new FileReader(fileName)) { // It's good to always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); int length = 0; ArrayList<Boolean> results = new ArrayList<Boolean>(); while ((line = bufferedReader.readLine()) != null) { if (line != null) { length = line.length(); for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '0') { results.add(false); } else if (line.charAt(i) == '1') { results.add(true); } } } } boolean[] results1D = new boolean[results.size()]; for (int i = 0; i < results.size(); i++) { results1D[i] = results.get(i); } bufferedReader.close(); return results1D; // convert1DBooleansTo2D(results1D, length); } catch (FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch (IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); } return null; } /** * Copies a file from an initial source path file to a destination * * @param src * - the initial source file * @param dst * - the destination path file * @throws IOException * exception with file handling */ public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); try { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException e) { System.err.println("ERROR: couldn't copy file in directory"); } finally { in.close(); out.close(); } } /** * Save the given text to the given filename. * * @param canonicalFilename * Like /Users/al/foo/bar.txt * @param text * All the text you want to save to the file as one String. * @throws IOException */ public static void writeFile(String canonicalFilename, String text) throws IOException { File file = new File(canonicalFilename); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(text); out.close(); } /** * Write an array of bytes to a file. Presumably this is binary data; for * plain text use the writeFile method. */ public static void writeFileAsBytes(String fullPath, byte[] bytes) throws IOException { OutputStream bufferedOutputStream = new BufferedOutputStream( new FileOutputStream(fullPath)); InputStream inputStream = new ByteArrayInputStream(bytes); int token = -1; while ((token = inputStream.read()) != -1) { bufferedOutputStream.write(token); } bufferedOutputStream.flush(); bufferedOutputStream.close(); inputStream.close(); } /** * Convert a byte array to a boolean array. Bit 0 is represented with false, * Bit 1 is represented with 1 * * @param bytes * byte[] * @return boolean[] */ public static boolean[] byteArray2BitArray(byte[] bytes) { boolean[] bits = new boolean[bytes.length * 8]; for (int i = 0; i < bytes.length * 8; i++) { if ((bytes[i / 8] & (1 << (7 - (i % 8)))) > 0) { bits[i] = true; } } return bits; } }
mit
fegalo/jee6-demos
jsp/jsp-eventsource/src/main/java/dev/jee6demo/jspes/EventSourceServlet.java
1399
package dev.jee6demo.jspes; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; 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; @WebServlet("/EventSourceServlet") public class EventSourceServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/event-stream"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = response.getWriter(); for (int i = 0; i < 5; i++) { pw.write("event:new_time\n"); pw.write("data: " + now() + "\n\n"); pw.flush(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } pw.write("event:new_time\n"); pw.write("data: STOP\n\n"); pw.flush(); pw.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } public static String now(){ DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); return dateFormat.format(new Date()); } }
mit
AVChkadua/interpreter
src/ru/mephi/interpreter/Scope.java
6273
package ru.mephi.interpreter; import org.antlr.v4.runtime.tree.ParseTree; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Anton_Chkadua */ public class Scope { static Scope GLOBAL = new Scope(null); private Scope parent; private Map<BigInteger, Variable> variables = new HashMap<>(); private Map<Function, ParseTree> functions = new HashMap<>(); private BigInteger memoryCounter = BigInteger.ZERO; Scope(Scope parent) { this.parent = parent; if (parent != null) { memoryCounter = parent.getMemoryCounter(); } } private BigInteger getMemoryCounter() { return memoryCounter; } void add(Variable variable) throws RuntimeLangException { if (variables.values().contains(variable)) { throw new RuntimeLangException(RuntimeLangException.Type.DUPLICATE_IDENTIFIER); } if (variable instanceof Array) { ((Array) variable).setScope(this); for (int i = 0; i < ((Array) variable).memoryLength; i++) { variables.put(memoryCounter, variable); memoryCounter = memoryCounter.add(BigInteger.ONE); } } else { variables.put(memoryCounter, variable); memoryCounter = memoryCounter.add(BigInteger.ONE); } } public void remove(String name) throws RuntimeLangException { Variable toBeRemoved = get(name); BigInteger address = variables.keySet().stream().filter(key -> variables.get(key).equals(toBeRemoved)).findFirst().orElseThrow(() -> new RuntimeLangException( RuntimeLangException.Type.NO_SUCH_VARIABLE)); variables.remove(address); } Scope getParent() { return parent; } Variable get(String name) throws RuntimeLangException { Variable candidate = variables.values().stream().filter(variable -> variable.getName().equals(name)).findAny() .orElse(null); if (candidate == null) { if (parent != null) { candidate = parent.get(name); } else { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_VARIABLE); } } return candidate; } Variable getByAddress(Pointer pointer) throws RuntimeLangException { Variable variable = variables.get(pointer.getValue()); System.out.println(variable); if (variable instanceof Array) { int address = getVariableAddress(variable).intValue(); int index = pointer.getValue().intValue() - address; return variable.getElement(index); } else { return variable; } } void setValueByAddress(Pointer pointer, BigInteger value) throws RuntimeLangException { if (pointer.constantValue) throw new RuntimeLangException(RuntimeLangException.Type.ILLEGAL_MODIFICATION); variables.get(pointer.getValue()).setValue(value); } BigInteger getVariableAddress(Variable variable) throws RuntimeLangException { if (!variables.values().contains(variable)) { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_VARIABLE); } for (Map.Entry<BigInteger, Variable> entry : variables.entrySet()) { if (entry.getValue().name.equals(variable.name)) return entry.getKey(); } return null; } void addFunction(Function function, ParseTree functionTree) throws RuntimeLangException { if (functions.containsKey(function)) { throw new RuntimeLangException(RuntimeLangException.Type.DUPLICATE_IDENTIFIER); } functions.put(function, functionTree); } ParseTree getFunctionTree(String name, List<Class> types) throws RuntimeLangException { ParseTree tree = functions.get(getFunction(name, types)); if (tree == null) { if (parent != null) { tree = parent.getFunctionTree(name, types); } else { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } } return tree; } Function getFunction(String name, List<Class> types) throws RuntimeLangException { Map.Entry<Function, ParseTree> entryCandidate = functions.entrySet().stream().filter(entry -> entry.getKey().name.equals(name)).findAny() .orElse(null); Function candidate = null; if (entryCandidate == null) { if (parent != null) { candidate = parent.getFunction(name, types); } } else { candidate = entryCandidate.getKey(); } if (candidate == null) { if (name.equals("main")) { throw new RuntimeLangException(RuntimeLangException.Type.NO_MAIN_FUNCTION); } else { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } } if (candidate.args.size() != types.size()) { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } for (int i = 0; i < candidate.args.size(); i++) { if (!candidate.args.get(i).getType().equals(types.get(i))) { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } } return candidate; } @Override public String toString() { String parent = this.parent != null ? this.parent.toString() : ""; StringBuilder builder = new StringBuilder(); for (Variable variable : variables.values()) { builder.append(variable.getName()).append("-").append(variable.getType()).append("-length-") .append(variable.getLength()); try { builder.append("-value-").append(variable.getValue()).append('-').append(variable.constantValue) .append("\r\n"); } catch (RuntimeLangException e) { System.out.println(e.getType()); } } return builder.insert(0, parent).toString(); } }
mit
MHS-FIRSTrobotics/TeamClutch-FTC2016
OpenCV/src/main/java/org/opencv/objdetect/CascadeClassifier.java
9327
// // This file is auto-generated. Please don't modify it! // package org.opencv.objdetect; import org.opencv.core.Mat; import org.opencv.core.MatOfDouble; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfRect; import org.opencv.core.Size; // C++: class CascadeClassifier //javadoc: CascadeClassifier public class CascadeClassifier { protected final long nativeObj; protected CascadeClassifier(long addr) { nativeObj = addr; } // // C++: CascadeClassifier() // //javadoc: CascadeClassifier::CascadeClassifier() public CascadeClassifier() { nativeObj = CascadeClassifier_0(); return; } // // C++: CascadeClassifier(String filename) // //javadoc: CascadeClassifier::CascadeClassifier(filename) public CascadeClassifier(String filename) { nativeObj = CascadeClassifier_1(filename); return; } // // C++: bool load(String filename) // //javadoc: CascadeClassifier::convert(oldcascade, newcascade) public static boolean convert(String oldcascade, String newcascade) { boolean retVal = convert_0(oldcascade, newcascade); return retVal; } // // C++: bool empty() // // C++: CascadeClassifier() private static native long CascadeClassifier_0(); // // C++: bool read(FileNode node) // // Unknown type 'FileNode' (I), skipping the function // // C++: void detectMultiScale(Mat image, vector_Rect& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) // // C++: CascadeClassifier(String filename) private static native long CascadeClassifier_1(String filename); // C++: bool load(String filename) private static native boolean load_0(long nativeObj, String filename); // // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& numDetections, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) // // C++: bool empty() private static native boolean empty_0(long nativeObj); // C++: void detectMultiScale(Mat image, vector_Rect& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) private static native void detectMultiScale_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height); // // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& rejectLevels, vector_double& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false) // private static native void detectMultiScale_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj); // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& numDetections, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) private static native void detectMultiScale2_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long numDetections_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height); // // C++: bool isOldFormatCascade() // private static native void detectMultiScale2_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long numDetections_mat_nativeObj); // // C++: Size getOriginalWindowSize() // // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& rejectLevels, vector_double& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false) private static native void detectMultiScale3_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long rejectLevels_mat_nativeObj, long levelWeights_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height, boolean outputRejectLevels); // // C++: int getFeatureType() // private static native void detectMultiScale3_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long rejectLevels_mat_nativeObj, long levelWeights_mat_nativeObj); // // C++: static bool convert(String oldcascade, String newcascade) // // C++: bool isOldFormatCascade() private static native boolean isOldFormatCascade_0(long nativeObj); // C++: Size getOriginalWindowSize() private static native double[] getOriginalWindowSize_0(long nativeObj); // C++: int getFeatureType() private static native int getFeatureType_0(long nativeObj); // C++: static bool convert(String oldcascade, String newcascade) private static native boolean convert_0(String oldcascade, String newcascade); // native support for java finalize() private static native void delete(long nativeObj); //javadoc: CascadeClassifier::load(filename) public boolean load(String filename) { boolean retVal = load_0(nativeObj, filename); return retVal; } //javadoc: CascadeClassifier::empty() public boolean empty() { boolean retVal = empty_0(nativeObj); return retVal; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, scaleFactor, minNeighbors, flags, minSize, maxSize) public void detectMultiScale(Mat image, MatOfRect objects, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize) { Mat objects_mat = objects; detectMultiScale_0(nativeObj, image.nativeObj, objects_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects) public void detectMultiScale(Mat image, MatOfRect objects) { Mat objects_mat = objects; detectMultiScale_1(nativeObj, image.nativeObj, objects_mat.nativeObj); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, numDetections, scaleFactor, minNeighbors, flags, minSize, maxSize) public void detectMultiScale2(Mat image, MatOfRect objects, MatOfInt numDetections, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize) { Mat objects_mat = objects; Mat numDetections_mat = numDetections; detectMultiScale2_0(nativeObj, image.nativeObj, objects_mat.nativeObj, numDetections_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, numDetections) public void detectMultiScale2(Mat image, MatOfRect objects, MatOfInt numDetections) { Mat objects_mat = objects; Mat numDetections_mat = numDetections; detectMultiScale2_1(nativeObj, image.nativeObj, objects_mat.nativeObj, numDetections_mat.nativeObj); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, rejectLevels, levelWeights, scaleFactor, minNeighbors, flags, minSize, maxSize, outputRejectLevels) public void detectMultiScale3(Mat image, MatOfRect objects, MatOfInt rejectLevels, MatOfDouble levelWeights, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize, boolean outputRejectLevels) { Mat objects_mat = objects; Mat rejectLevels_mat = rejectLevels; Mat levelWeights_mat = levelWeights; detectMultiScale3_0(nativeObj, image.nativeObj, objects_mat.nativeObj, rejectLevels_mat.nativeObj, levelWeights_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height, outputRejectLevels); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, rejectLevels, levelWeights) public void detectMultiScale3(Mat image, MatOfRect objects, MatOfInt rejectLevels, MatOfDouble levelWeights) { Mat objects_mat = objects; Mat rejectLevels_mat = rejectLevels; Mat levelWeights_mat = levelWeights; detectMultiScale3_1(nativeObj, image.nativeObj, objects_mat.nativeObj, rejectLevels_mat.nativeObj, levelWeights_mat.nativeObj); return; } //javadoc: CascadeClassifier::isOldFormatCascade() public boolean isOldFormatCascade() { boolean retVal = isOldFormatCascade_0(nativeObj); return retVal; } //javadoc: CascadeClassifier::getOriginalWindowSize() public Size getOriginalWindowSize() { Size retVal = new Size(getOriginalWindowSize_0(nativeObj)); return retVal; } //javadoc: CascadeClassifier::getFeatureType() public int getFeatureType() { int retVal = getFeatureType_0(nativeObj); return retVal; } @Override protected void finalize() throws Throwable { delete(nativeObj); } }
mit
ZawilecxD/Social-Network-Simulator
GlidersGrid/src/GlidersGrid/Dead.java
1307
package GlidersGrid; import java.util.Iterator; import repast.simphony.context.Context; import repast.simphony.engine.schedule.ScheduledMethod; import repast.simphony.query.space.grid.MooreQuery; import repast.simphony.space.grid.Grid; import repast.simphony.space.grid.GridPoint; import repast.simphony.util.ContextUtils; public class Dead { private Grid<Object> grid; private int state; public Dead(Grid<Object> grid) { this.grid = grid; } // calculate the state for the next time tick for dead cells @ScheduledMethod(start = 1, interval = 1, priority = 4) public void step1() { MooreQuery<Dead> query = new MooreQuery(grid, this); int neighbours = 0; for (Object o : query.query()) { if (o instanceof Living) { neighbours++; if (neighbours ==3) { } } } if (neighbours == 3) { state = 1; } else { state = 0; } } // visualise the change into the underlay and grid @ScheduledMethod(start = 1, interval = 1, priority = 1) public void step2() { if (state == 1) { GridPoint gpt = grid.getLocation(this); Context<Object> context = ContextUtils.getContext(this); context.remove(this); Living livingCell = new Living(grid); context.add(livingCell); grid.moveTo(livingCell, gpt.getX(), gpt.getY()); context.add(livingCell); } } }
mit
crbanman/AstroidEscape
ios/src/ca/codybanman/AstroidEscape/IOSLauncher.java
772
package ca.codybanman.AstroidEscape; import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import ca.codybanman.AstroidEscape.AEGame; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); return new IOSApplication(new AEGame(), config); } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, IOSLauncher.class); pool.close(); } }
mit
Azure/azure-sdk-for-java
sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/fluent/SecureScoreControlDefinitionsClient.java
3054
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; import com.azure.resourcemanager.security.fluent.models.SecureScoreControlDefinitionItemInner; /** An instance of this class provides access to all the operations defined in SecureScoreControlDefinitionsClient. */ public interface SecureScoreControlDefinitionsClient { /** * List the available security controls, their assessments, and the max score. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> list(); /** * List the available security controls, their assessments, and the max score. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> list(Context context); /** * For a specified subscription, list the available security controls, their assessments, and the max score. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(); /** * For a specified subscription, list the available security controls, their assessments, and the max score. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(Context context); }
mit
7040210/SuperBoot
super-boot-global/src/main/java/org/superboot/service/ErrorLogService.java
1147
package org.superboot.service; import com.querydsl.core.types.Predicate; import org.springframework.data.domain.Pageable; import org.superboot.base.BaseException; import org.superboot.base.BaseResponse; /** * <b> 错误日志服务接口 </b> * <p> * 功能描述: * </p> */ public interface ErrorLogService { /** * 按照微服务模块进行分组统计 * * @return * @throws BaseException */ BaseResponse getErrorLogGroupByAppName() throws BaseException; /** * 获取错误日志列表信息 * * @param pageable 分页信息 * @param predicate 查询参数 * @return * @throws BaseException */ BaseResponse getErrorLogList(Pageable pageable, Predicate predicate) throws BaseException; /** * 获取错误日志记录数 * * @return * @throws BaseException */ BaseResponse getErrorLogCount(Predicate predicate) throws BaseException; /** * 查询错误日志详细信息 * * @param id * @return * @throws BaseException */ BaseResponse getErrorLogItem(String id) throws BaseException; }
mit
HenryLoenwind/AgriCraft
src/main/java/com/InfinityRaider/AgriCraft/utility/OreDictHelper.java
5607
package com.InfinityRaider.AgriCraft.utility; import com.InfinityRaider.AgriCraft.items.ItemAgricraft; import com.InfinityRaider.AgriCraft.items.ItemNugget; import com.InfinityRaider.AgriCraft.reference.Data; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class OreDictHelper { private static final Map<String, Block> oreBlocks = new HashMap<String, Block>(); private static final Map<String, Integer> oreBlockMeta = new HashMap<String, Integer>(); private static final Map<String, Item> nuggets = new HashMap<String, Item>(); private static final Map<String, Integer> nuggetMeta = new HashMap<String, Integer>(); public static Block getOreBlockForName(String name) { return oreBlocks.get(name); } public static int getOreMetaForName(String name) { return oreBlockMeta.get(name); } public static Item getNuggetForName(String name) { return nuggets.get(name); } public static int getNuggetMetaForName(String name) { return nuggetMeta.get(name); } //checks if an itemstack has this ore dictionary entry public static boolean hasOreId(ItemStack stack, String tag) { if(stack==null || stack.getItem()==null) { return false; } int[] ids = OreDictionary.getOreIDs(stack); for(int id:ids) { if(OreDictionary.getOreName(id).equals(tag)) { return true; } } return false; } public static boolean hasOreId(Block block, String tag) { return block != null && hasOreId(new ItemStack(block), tag); } //checks if two blocks have the same ore dictionary entry public static boolean isSameOre(Block block1, int meta1, Block block2, int meta2) { if(block1==block2 && meta1==meta2) { return true; } if(block1==null || block2==null) { return false; } int[] ids1 = OreDictionary.getOreIDs(new ItemStack(block1, 1, meta1)); int[] ids2 = OreDictionary.getOreIDs(new ItemStack(block2, 1, meta2)); for (int id1:ids1) { for (int id2:ids2) { if (id1==id2) { return true; } } } return false; } //finds the ingot for a nugget ore dictionary entry public static ItemStack getIngot(String ore) { ItemStack ingot = null; ArrayList<ItemStack> entries = OreDictionary.getOres("ingot" + ore); if (entries.size() > 0 && entries.get(0).getItem() != null) { ingot = entries.get(0); } return ingot; } //finds what ores and nuggets are already registered in the ore dictionary public static void getRegisteredOres() { //Vanilla for (String oreName : Data.vanillaNuggets) { getOreBlock(oreName); if(oreBlocks.get(oreName)!=null) { getNugget(oreName); } } //Modded for (String[] data : Data.modResources) { String oreName = data[0]; getOreBlock(oreName); if(oreBlocks.get(oreName)!=null) { getNugget(oreName); } } } private static void getOreBlock(String oreName) { for (ItemStack itemStack : OreDictionary.getOres("ore"+oreName)) { if (itemStack.getItem() instanceof ItemBlock) { ItemBlock block = (ItemBlock) itemStack.getItem(); oreBlocks.put(oreName, block.field_150939_a); oreBlockMeta.put(oreName, itemStack.getItemDamage()); break; } } } private static void getNugget(String oreName) { List<ItemStack> nuggets = OreDictionary.getOres("nugget" + oreName); if (!nuggets.isEmpty()) { Item nugget = nuggets.get(0).getItem(); OreDictHelper.nuggets.put(oreName, nugget); nuggetMeta.put(oreName, nuggets.get(0).getItemDamage()); } else { ItemAgricraft nugget = new ItemNugget(oreName); OreDictionary.registerOre("nugget"+oreName, nugget); OreDictHelper.nuggets.put(oreName, nugget); nuggetMeta.put(oreName, 0); } } public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed) { return getFruitsFromOreDict(seed, true); } public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed, boolean sameMod) { String seedModId = IOHelper.getModId(seed); ArrayList<ItemStack> fruits = new ArrayList<ItemStack>(); for(int id:OreDictionary.getOreIDs(seed)) { if(OreDictionary.getOreName(id).substring(0,4).equalsIgnoreCase("seed")) { String name = OreDictionary.getOreName(id).substring(4); ArrayList<ItemStack> fromOredict = OreDictionary.getOres("crop"+name); for(ItemStack stack:fromOredict) { if(stack==null || stack.getItem()==null) { continue; } String stackModId = IOHelper.getModId(stack); if((!sameMod) || stackModId.equals(seedModId)) { fruits.add(stack); } } } } return fruits; } }
mit
mrkoopa/jfbx
java/mrkoopa/jfbx/FbxCameraStereo.java
1258
/* * MIT License * * Copyright (c) 2017 Alessandro Arcangeli <alessandroarcangeli.rm@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mrkoopa.jfbx; public interface FbxCameraStereo extends FbxCamera { }
mit
zelark/test
src/main/java/App.java
119
public class App { public static void main(String[] args) { System.out.println("Old man, look at my life..."); } }
mit
Adam8234/the-blue-alliance-android
android/src/main/java/com/thebluealliance/androidclient/gcm/notifications/ScoreNotification.java
11766
package com.thebluealliance.androidclient.gcm.notifications; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.thebluealliance.androidclient.Constants; import com.thebluealliance.androidclient.R; import com.thebluealliance.androidclient.Utilities; import com.thebluealliance.androidclient.activities.ViewMatchActivity; import com.thebluealliance.androidclient.datafeed.JSONManager; import com.thebluealliance.androidclient.helpers.EventHelper; import com.thebluealliance.androidclient.helpers.MatchHelper; import com.thebluealliance.androidclient.helpers.MyTBAHelper; import com.thebluealliance.androidclient.listeners.GamedayTickerClickListener; import com.thebluealliance.androidclient.models.BasicModel; import com.thebluealliance.androidclient.models.Match; import com.thebluealliance.androidclient.models.StoredNotification; import com.thebluealliance.androidclient.views.MatchView; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * Created by Nathan on 7/24/2014. */ public class ScoreNotification extends BaseNotification { private String eventName, eventKey, matchKey; private Match match; public ScoreNotification(String messageData) { super("score", messageData); } @Override public void parseMessageData() throws JsonParseException { JsonObject jsonData = JSONManager.getasJsonObject(messageData); if (!jsonData.has("match")) { throw new JsonParseException("Notification data does not contain 'match"); } JsonObject match = jsonData.get("match").getAsJsonObject(); this.match = gson.fromJson(match, Match.class); try { this.matchKey = this.match.getKey(); } catch (BasicModel.FieldNotDefinedException e) { e.printStackTrace(); } this.eventKey = MatchHelper.getEventKeyFromMatchKey(matchKey); if (!jsonData.has("event_name")) { throw new JsonParseException("Notification data does not contain 'event_name"); } eventName = jsonData.get("event_name").getAsString(); } @Override public Notification buildNotification(Context context) { Resources r = context.getResources(); String matchKey; try { matchKey = match.getKey(); this.matchKey = matchKey; } catch (BasicModel.FieldNotDefinedException e) { Log.e(getLogTag(), "Incoming Match object does not have a key. Can't post score update"); e.printStackTrace(); return null; } String matchTitle = MatchHelper.getMatchTitleFromMatchKey(context, matchKey); String matchAbbrevTitle = MatchHelper.getAbbrevMatchTitleFromMatchKey(context, matchKey); JsonObject alliances; try { alliances = match.getAlliances(); } catch (BasicModel.FieldNotDefinedException e) { Log.e(getLogTag(), "Incoming match object does not contain alliance data. Can't post score update"); e.printStackTrace(); return null; } int redScore = Match.getRedScore(alliances); ArrayList<String> redTeamKeys = new ArrayList<>(); JsonArray redTeamsJson = Match.getRedTeams(alliances); for (int i = 0; i < redTeamsJson.size(); i++) { redTeamKeys.add(redTeamsJson.get(i).getAsString()); } int blueScore = Match.getBlueScore(alliances); ArrayList<String> blueTeamKeys = new ArrayList<>(); JsonArray blueTeamsJson = Match.getBlueTeams(alliances); for (int i = 0; i < blueTeamsJson.size(); i++) { blueTeamKeys.add(blueTeamsJson.get(i).getAsString()); } // TODO filter out teams that the user doesn't want notifications about // These arrays hold the numbers of teams that the user cares about ArrayList<String> redTeams = new ArrayList<>(); ArrayList<String> blueTeams = new ArrayList<>(); for (String key : redTeamKeys) { redTeams.add(key.replace("frc", "")); } for (String key : blueTeamKeys) { blueTeams.add(key.replace("frc", "")); } // Make sure the score string is formatted properly with the winning score first String scoreString; if (redScore > blueScore) { scoreString = redScore + "-" + blueScore; } else if (redScore < blueScore) { scoreString = blueScore + "-" + redScore; } else { scoreString = redScore + "-" + redScore; } String redTeamString = Utilities.stringifyListOfStrings(context, redTeams); String blueTeamString = Utilities.stringifyListOfStrings(context, blueTeams); boolean useSpecial2015Format; try { useSpecial2015Format = match.getYear() == 2015 && match.getType() != MatchHelper.TYPE.FINAL; } catch (BasicModel.FieldNotDefinedException e) { useSpecial2015Format = false; Log.w(Constants.LOG_TAG, "Couldn't determine if we should use 2015 score format. Defaulting to no"); } String eventShortName = EventHelper.shortName(eventName); String notificationString; if (redTeams.size() == 0 && blueTeams.size() == 0) { // We must have gotten this GCM message by mistake return null; } else if (useSpecial2015Format) { /* Only for 2015 non-finals matches. Ugh */ notificationString = context.getString(R.string.notification_score_2015_no_winner, eventShortName, matchTitle, redTeamString, redScore, blueTeamString, blueScore); } else if ((redTeams.size() > 0 && blueTeams.size() == 0)) { // The user only cares about some teams on the red alliance if (redScore > blueScore) { // Red won notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, redTeamString, matchTitle, scoreString); } else if (redScore < blueScore) { // Red lost notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, redTeamString, matchTitle, scoreString); } else { // Red tied notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, redTeamString, matchTitle, scoreString); } } else if ((blueTeams.size() > 0 && redTeams.size() == 0)) { // The user only cares about some teams on the blue alliance if (blueScore > redScore) { // Blue won notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, blueTeamString, matchTitle, scoreString); } else if (blueScore < redScore) { // Blue lost notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, blueTeamString, matchTitle, scoreString); } else { // Blue tied notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, blueTeamString, matchTitle, scoreString); } } else if ((blueTeams.size() > 0 && redTeams.size() > 0)) { // The user cares about teams on both alliances if (blueScore > redScore) { // Blue won notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, blueTeamString, redTeamString, matchTitle, scoreString); } else if (blueScore < redScore) { // Blue lost notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString); } else { // Blue tied notificationString = context.getString(R.string.notification_score_teams_tied_with_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString); } } else { // We should never, ever get here but if we do... return null; } // We can finally build the notification! Intent instance = getIntent(context); stored = new StoredNotification(); stored.setType(getNotificationType()); String eventCode = EventHelper.getEventCode(matchKey); String notificationTitle = r.getString(R.string.notification_score_title, eventCode, matchAbbrevTitle); stored.setTitle(notificationTitle); stored.setBody(notificationString); stored.setIntent(MyTBAHelper.serializeIntent(instance)); stored.setTime(Calendar.getInstance().getTime()); NotificationCompat.Builder builder = getBaseBuilder(context, instance) .setContentTitle(notificationTitle) .setContentText(notificationString) .setLargeIcon(getLargeIconFormattedForPlatform(context, R.drawable.ic_info_outline_white_24dp)); NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle().bigText(notificationString); builder.setStyle(style); return builder.build(); } @Override public void updateDataLocally(Context c) { if (match != null) { match.write(c); } } @Override public Intent getIntent(Context c) { return ViewMatchActivity.newInstance(c, matchKey); } @Override public int getNotificationId() { return (new Date().getTime() + ":" + getNotificationType() + ":" + matchKey).hashCode(); } @Override public View getView(Context c, LayoutInflater inflater, View convertView) { ViewHolder holder; if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) { convertView = inflater.inflate(R.layout.list_item_notification_score, null, false); holder = new ViewHolder(); holder.header = (TextView) convertView.findViewById(R.id.card_header); holder.title = (TextView) convertView.findViewById(R.id.title); holder.matchView = (MatchView) convertView.findViewById(R.id.match_details); holder.time = (TextView) convertView.findViewById(R.id.notification_time); holder.summaryContainer = convertView.findViewById(R.id.summary_container); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.header.setText(c.getString(R.string.gameday_ticker_event_title_format, EventHelper.shortName(eventName), EventHelper.getShortCodeForEventKey(eventKey).toUpperCase())); holder.title.setText(c.getString(R.string.notification_score_gameday_title, MatchHelper.getMatchTitleFromMatchKey(c, matchKey))); holder.time.setText(getNotificationTimeString(c)); holder.summaryContainer.setOnClickListener(new GamedayTickerClickListener(c, this)); match.render(false, false, false, true).getView(c, inflater, holder.matchView); return convertView; } private class ViewHolder { public TextView header; public TextView title; public MatchView matchView; public TextView time; private View summaryContainer; } }
mit
janisstreib/nan-hotline
webFrontend/src/me/streib/janis/nanhotline/web/Launcher.java
2118
package me.streib.janis.nanhotline.web; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.InetSocketAddress; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.SessionManager; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class Launcher { public static void main(String[] args) throws Exception { NANHotlineConfiguration conf; if (args.length != 1) { InputStream ins; File confFile = new File("conf/nanhotline.properties"); if (confFile.exists()) { ins = new FileInputStream(confFile); } else { ins = Launcher.class .getResourceAsStream("nanhotline.properties"); } conf = new NANHotlineConfiguration(ins); } else { conf = new NANHotlineConfiguration(new FileInputStream(new File( args[0]))); } DatabaseConnection.init(conf); Server s = new Server(new InetSocketAddress(conf.getHostName(), conf.getPort())); ((QueuedThreadPool) s.getThreadPool()).setMaxThreads(20); ServletContextHandler h = new ServletContextHandler( ServletContextHandler.SESSIONS); h.setInitParameter(SessionManager.__SessionCookieProperty, "DB-Session"); h.addServlet(NANHotline.class, "/*"); HandlerList hl = new HandlerList(); hl.setHandlers(new Handler[] { generateStaticContext(), h }); s.setHandler(hl); s.start(); } private static Handler generateStaticContext() { final ResourceHandler rh = new ResourceHandler(); rh.setResourceBase("static/"); ContextHandler ch = new ContextHandler("/static"); ch.setHandler(rh); return ch; } }
mit
VeryGame/gdx-surface
gdx-surface/src/main/java/de/verygame/surface/screen/base/SubScreenContext.java
4133
package de.verygame.surface.screen.base; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.Map; /** * @author Rico Schrage * * Context which can contain several subscreens. */ public class SubScreenContext implements ScreenContext { /** List of subScreen's plus visibility flag */ protected final ScreenSwitch screenSwitch; /** viewport of the screen (manages the glViewport) */ protected final Viewport viewport; /** True if a subScreen is visible */ protected boolean showSubScreen = false; /** * Constructs a context with the given viewport. * * @param viewport viewport viewport of the screen */ public SubScreenContext(Viewport viewport) { super(); this.viewport = viewport; this.screenSwitch = new ScreenSwitch(); } /** * Sets the dependency map of the screen switch. * * @param dependencies map of dependencies */ public void setDependencies(Map<String, Object> dependencies) { screenSwitch.setDependencyMap(dependencies); } /** * Sets the batch of the context. * * @param polygonSpriteBatch batch */ public void setBatch(PolygonSpriteBatch polygonSpriteBatch) { screenSwitch.setBatch(polygonSpriteBatch); } /** * Sets the inputHandler of the context. * * @param inputHandler inputHandler */ public void setInputHandler(InputMultiplexer inputHandler) { screenSwitch.setInputHandler(inputHandler); } public InputMultiplexer getInputHandler() { return screenSwitch.getInputHandler(); } public void onActivate(ScreenId screenKey) { if (screenSwitch.getActiveScreen() != null) { screenSwitch.getActiveScreen().onActivate(screenKey); } } public float onDeactivate(ScreenId screenKey) { if (screenSwitch.getActiveScreen() != null) { return screenSwitch.getActiveScreen().onDeactivate(screenKey); } return 0; } /** * Applies the viewport of the context. Calls {@link Viewport#apply(boolean)}. */ public void applyViewport() { viewport.apply(true); } /** * Updates the viewport of the context. Calls {@link Viewport#update(int, int, boolean)}. * * @param width width of the frame * @param height height of the frame */ public void updateViewport(int width, int height) { viewport.update(width, height, true); } public void update() { screenSwitch.updateSwitch(); screenSwitch.updateScreen(); } public void renderScreen() { if (showSubScreen) { screenSwitch.renderScreen(); } } public void resizeSubScreen(int width, int height) { screenSwitch.resize(width, height); } public void pauseSubScreen() { screenSwitch.pause(); } public void resumeSubScreen() { screenSwitch.resume(); } public void dispose() { screenSwitch.dispose(); } @Override public Viewport getViewport() { return viewport; } @Override public PolygonSpriteBatch getBatch() { return screenSwitch.getBatch(); } @Override public void addSubScreen(SubScreenId id, SubScreen subScreen) { if (screenSwitch.getBatch() == null) { throw new IllegalStateException("Parent screen have to be attached to a screen switch!"); } this.screenSwitch.addScreen(id, subScreen); } @Override public SubScreen getActiveSubScreen() { return (SubScreen) screenSwitch.getActiveScreen(); } @Override public void showScreen(SubScreenId id) { showSubScreen = true; screenSwitch.setActive(id); } @Override public void initialize(SubScreenId id) { showSubScreen = true; screenSwitch.setScreenSimple(id); } @Override public void hideScreen() { showSubScreen = false; } }
mit
Azure/azure-sdk-for-java
sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpRequestLogger.java
1343
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.http.policy; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.logging.LogLevel; import reactor.core.publisher.Mono; /** * Manages logging HTTP requests in {@link HttpLoggingPolicy}. */ @FunctionalInterface public interface HttpRequestLogger { /** * Gets the {@link LogLevel} used to log the HTTP request. * <p> * By default this will return {@link LogLevel#INFORMATIONAL}. * * @param loggingOptions The information available during request logging. * @return The {@link LogLevel} used to log the HTTP request. */ default LogLevel getLogLevel(HttpRequestLoggingContext loggingOptions) { return LogLevel.INFORMATIONAL; } /** * Logs the HTTP request. * <p> * To get the {@link LogLevel} used to log the HTTP request use {@link #getLogLevel(HttpRequestLoggingContext)}. * * @param logger The {@link ClientLogger} used to log the HTTP request. * @param loggingOptions The information available during request logging. * @return A reactive response that indicates that the HTTP request has been logged. */ Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions); }
mit
girinoboy/lojacasamento
pagseguro-api/src/main/java/br/com/uol/pagseguro/api/common/domain/Document.java
1173
/* * 2007-2016 [PagSeguro Internet Ltda.] * * NOTICE OF LICENSE * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright: 2007-2016 PagSeguro Internet Ltda. * Licence: http://www.apache.org/licenses/LICENSE-2.0 */ package br.com.uol.pagseguro.api.common.domain; import br.com.uol.pagseguro.api.common.domain.enums.DocumentType; /** * Interface for documents. * * @author PagSeguro Internet Ltda. */ public interface Document { /** * Get Document Type * * @return Document Type * @see DocumentType */ DocumentType getType(); /** * Get Value of document * * @return Value of document */ String getValue(); }
mit
github/codeql
java/ql/test/stubs/guava-30.0/com/google/common/collect/SortedSetMultimap.java
571
// Generated automatically from com.google.common.collect.SortedSetMultimap for testing purposes package com.google.common.collect; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.SortedSet; public interface SortedSetMultimap<K, V> extends SetMultimap<K, V> { Comparator<? super V> valueComparator(); Map<K, Collection<V>> asMap(); SortedSet<V> get(K p0); SortedSet<V> removeAll(Object p0); SortedSet<V> replaceValues(K p0, Iterable<? extends V> p1); }
mit
brucevsked/vskeddemolist
vskeddemos/projects/shirodemo/SpringMVC_Shiro/src/com/etop/service/UserService.java
930
package com.etop.service; import com.etop.dao.UserDAO; import com.etop.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户服务,与dao进行对接 * <p/> * Created by Jeremie on 2014/9/30. */ @Service("UserService") public class UserService implements Serializable { @Autowired private UserDAO userDAO; /** * 通过用户名查找用户信息 * * @param username * @return */ public User findByName(String username) { Map<String, Object> params = new HashMap<>(); params.put("name", username); return userDAO.findUniqueResult("from User u where u.username = :name", params); } public List<User> getAllUser() { return userDAO.find("from User u"); } }
mit
BrunoMarchi/Chess_Game-LCP_2017
ChessGame/src/states/MenuState.java
11128
package states; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.ArrayList; import database.DeleteGame; import database.LoadGame; import game.Game; import graphics.ButtonAction; import graphics.Text; import graphics.UIButton; import graphics.UIList; import graphics.UIScrollScreen; import loader.ImageLoader; public class MenuState extends State { /* Menu screen state it is the initial screen of the game it control the new button and the load button*/ //Main Menu private UIList menuButtons; private BufferedImage menuBackground; //Load Buttons Menu (second Screen) private UIScrollScreen loadScreen; private BufferedImage subMenuBackground; private boolean loadScreenMenu; //Selected Game Menu (Third Screen) private UIList loadSubMenu; private BufferedImage gameSelectedBackground; private boolean gameSelected; public MenuState(Game game) { super(game); State.loadMenuState = true; } @Override public UIList getUIButtons() { /*Control of active buttons*/ if (!gameSelected) { return menuButtons; } else { return loadSubMenu; } } @Override public UIScrollScreen getScreen() { /*control if scroll buttons are active*/ if (loadScreenMenu) return loadScreen; else return null; } @Override public void tick() { // If ESC is clicked on the menu screen then the game closes if(State.loadMenuState) { //loadMenuState is true then init menu screen initMenuScreen(); State.loadMenuState = false; } if (game.getKeyboard().mESC == true) { //If esc was pressed if (loadScreenMenu) { //Release loadScreen memory loadScreenMenu = false; loadScreen.getButtons().clear(); loadScreen = null; subMenuBackground = null; } else if(gameSelected) { //Release memory of the screen after choose a saved game gameSelected = false; loadSubMenu.getButtons().clear(); loadSubMenu = null; gameSelectedBackground = null; } else { // If esc was clicked on menu then close game game.stop(); } game.getKeyboard().mESC = false; } if(State.loadGame || State.newGame) // If load or new game true then it will change to gameState so release menu memory and changes state { menuButtons.getButtons().clear(); menuButtons = null; menuBackground = null; State.setCurrentState(game.getGameState()); } } @Override public void render(Graphics graph) { if(State.loadMenuState) // Make sure that only render after menu was loaded return; // Draw the menu background image and render the UI buttons graph.drawImage(menuBackground, 0, 0, game.getWidth(), game.getHeight(), null); menuButtons.render(graph); if (loadScreenMenu) { //Draw subMenu background and render buttons graph.drawImage(subMenuBackground, 0, 0, game.getWidth(), game.getHeight(), null); loadScreen.render(graph); } else if (gameSelected) { //Draw gameSelected background and render buttons graph.drawImage(gameSelectedBackground, 0, 0, game.getWidth(), game.getHeight(), null); loadSubMenu.render(graph); } } private void initMenuScreen() { /*Initialize the screen and buttons of the first menu screen*/ menuBackground = ImageLoader.loadImage("/background/menu_backgroud.png"); try { initMenuButtons(); } catch (Exception e) { e.printStackTrace(); } } private void initLoadScreen() { /*Initialize the screen and buttons of the second menu screen (list of saved games)*/ subMenuBackground = ImageLoader.loadImage("/background/submenu_background.png"); initLoadScreenButtons(); } private void initGameSelectedScreen() { /*Initialize the screen and of the third menu screen (game selected)*/ gameSelectedBackground = ImageLoader.loadImage("/background/load_submenu_background.png"); initGameSelectedButtons(); } private void initGameSelectedButtons() { /*Init buttons of the selected game load, delete and cancel*/ BufferedImage loadSaveButton[] = new BufferedImage[2]; BufferedImage deleteSaveButton[] = new BufferedImage[2]; BufferedImage cancelButton[] = new BufferedImage[2]; loadSubMenu = new UIList(); loadSaveButton[0] = ImageLoader.loadImage("/button/load_submenu_d.png"); loadSaveButton[1] = ImageLoader.loadImage("/button/load_submenu_s.png"); int buttonWidth = (int) (loadSaveButton[0].getWidth() * game.getScale()); int buttonHeight = (int) (loadSaveButton[0].getHeight() * game.getScale()); //Load a saved game loadSubMenu.getButtons().add(new UIButton((int) (50 * game.getScale()), (int)(300 * game.getScale()), buttonWidth, buttonHeight, loadSaveButton, -1, new ButtonAction() { @Override public void action() { State.loadGame = true; // Tells gameState to load a game game.getKeyboard().mESC = true; // Set esc true to release memory from this screen (GameSelected screen) } })); deleteSaveButton[0] = ImageLoader.loadImage("/button/delete_submenu_d.png"); deleteSaveButton[1] = ImageLoader.loadImage("/button/delete_submenu_s.png"); //Delete a saved game loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(430 * game.getScale()), buttonWidth, buttonHeight, deleteSaveButton, -1, new ButtonAction() { @Override public void action() { try { DeleteGame.Delete(State.savedGames.get(lastButtonIndex).split(" ")[0]); //Get the name of the button pressed and removes from database } catch (Exception e) { e.printStackTrace(); } State.savedGames.clear(); //Clear database name loaded State.savedGames = null; game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen) } })); cancelButton[0] = ImageLoader.loadImage("/button/cancel_submenu_d.png"); cancelButton[1] = ImageLoader.loadImage("/button/cancel_submenu_s.png"); //Cancel operation and goes back to the first menu screen loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(550 * game.getScale()), buttonWidth, buttonHeight, cancelButton, -1, new ButtonAction() { @Override public void action() { State.savedGames.clear(); //Clear database name loaded State.savedGames = null; game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen) } })); } private void initLoadScreenButtons() { /*Initialize all load screen buttons*/ BufferedImage loadScreenImage = ImageLoader.loadImage("/background/scrollScreen.png"); BufferedImage loadButton[] = new BufferedImage[2]; int scrollSpeed = 10; //Init load screen loadScreen = new UIScrollScreen(loadScreenImage, (int)(31 * game.getScale()), (int)(132 * game.getScale()), (int)(loadScreenImage.getWidth() * game.getScale()), (int)(loadScreenImage.getHeight() * game.getScale()), scrollSpeed); loadButton[0] = ImageLoader.loadImage("/button/submenu_button_d.png"); loadButton[1] = ImageLoader.loadImage("/button/submenu_button_s.png"); float buttonWidth = loadButton[0].getWidth() * game.getScale(); float buttonHeight = loadButton[0].getHeight() * game.getScale(); Font font = new Font("Castellar", Font.PLAIN, (int)(25 * game.getScale())); for (int i = 0, accumulator = (int) loadScreen.getScreen().getY(); (int) i < savedGames.size(); i++) { //Accumulator controls the button position on the screen String split[] = savedGames.get(i).split(" "); //split the name that came from the database float buttonX = (float) (loadScreen.getScreen().getX() + 3); Text text[] = new Text[2]; //Initialize both colors of the text and create the visible buttons text[0] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.black, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2)); text[1] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.white, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2)); loadScreen.getButtons().add(new UIButton((int) buttonX, accumulator, (int) (buttonWidth), (int) buttonHeight, loadButton, i, text, new ButtonAction() { public void action() { initGameSelectedScreen(); //Initialize gameSelect screen and buttons gameSelected = true; game.getKeyboard().mESC = true; // Select true to free memory used by the loadScreen } })); accumulator += (buttonHeight); } } private void initMenuButtons() throws Exception{ // Resize the button depending of the scale attribute of the game class BufferedImage[] buttonNewGame = new BufferedImage[2]; BufferedImage[] buttonLoadGame = new BufferedImage[2]; buttonNewGame[0] = ImageLoader.loadImage("/button/new_game.png"); buttonNewGame[1] = ImageLoader.loadImage("/button/new_game_b.png"); buttonLoadGame[0] = ImageLoader.loadImage("/button/load_game.png"); buttonLoadGame[1] = ImageLoader.loadImage("/button/load_game_b.png"); menuButtons = new UIList(); /* * Creates the load button and add to the UI button list, the first two * parameters has the position of the button on the screen it uses the * game.width to centralize the button and the game.height to control * the y position on the screen for every button a Button action is * defined when passing the argument, this way is possible to program * the button when creating it */ float buttonWidth = buttonLoadGame[0].getWidth() * game.getScale(); float buttonHeight = buttonLoadGame[0].getHeight() * game.getScale(); menuButtons.getButtons().add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3) + buttonHeight), (int) (buttonWidth), (int) buttonHeight, buttonLoadGame, -1, new ButtonAction() { public void action() { savedGames = new ArrayList<>(); try { savedGames = LoadGame.loadNames(); } catch (Exception e) { e.printStackTrace(); } initLoadScreen(); loadScreenMenu = true; } })); /* * Creates the game button and add to the UI button list, the first two * parameters has the position of the button on the screen it uses the * game.width to centralize the button and the game.height to control * the y position on the screen for every button a Button action is * defined when passing the argument, this way is possible to program * the button when creating it */ // Resize the button depending of the scale attribute of the game class buttonWidth = buttonNewGame[0].getWidth() * game.getScale(); buttonHeight = buttonNewGame[0].getHeight() * game.getScale(); menuButtons.getButtons() .add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3)), (int) (buttonWidth), (int) (buttonHeight), buttonNewGame, -1, new ButtonAction() { public void action() { State.newGame = true; } })); } }
mit
ShopwareHackathon/idea-php-shopware-plugin
src/de/espend/idea/shopware/util/dict/PsiParameterStorageRunnable.java
5005
package de.espend.idea.shopware.util.dict; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.MethodReference; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import org.apache.commons.lang.StringUtils; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; public class PsiParameterStorageRunnable implements Runnable { private final Project project; private final VirtualFile virtualFile; private final Map<String, Collection<String>> events; private final Set<String> configs; public PsiParameterStorageRunnable(Project project, VirtualFile virtualFile, Map<String, Collection<String>> events, Set<String> configs) { this.project = project; this.virtualFile = virtualFile; this.events = events; this.configs = configs; } public void run() { final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile != null) { psiFile.acceptChildren(new MyPsiRecursiveElementWalkingVisitor()); } } private class MyPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor { @Override public void visitElement(PsiElement element) { if (element instanceof MethodReference) { visitMethodReference((MethodReference) element); } super.visitElement(element); } private void visitMethodReference(MethodReference methodReference) { String name = methodReference.getName(); if (name != null && ("notify".equals(name) || "notifyUntil".equals(name) || "filter".equals(name))) { PsiElement[] parameters = methodReference.getParameters(); if(parameters.length > 1) { if(parameters[0] instanceof StringLiteralExpression) { PsiElement method = methodReference.resolve(); if(method instanceof Method) { PhpClass phpClass = ((Method) method).getContainingClass(); if(phpClass != null && new Symfony2InterfacesUtil().isInstanceOf(phpClass, "\\Enlight_Event_EventManager")) { String content = PhpElementsUtil.getStringValue(parameters[0]); if(StringUtils.isNotBlank(content)) { if(!events.containsKey(content)) { events.put(content, new HashSet<String>()); } Collection<String> data = events.get(content); Method parentOfType = PsiTreeUtil.getParentOfType(parameters[0], Method.class); if(parentOfType != null && parentOfType.getContainingClass() != null) { String methodName = parentOfType.getName(); String presentableFQN = parentOfType.getContainingClass().getPresentableFQN(); data.add(presentableFQN + '.' + methodName); events.put(content, data); } } } } } } } if (name != null && ("addElement".equals(name) || "setElement".equals(name))) { PsiElement[] parameters = methodReference.getParameters(); if(parameters.length > 2) { if(parameters[1] instanceof StringLiteralExpression) { PsiElement method = methodReference.resolve(); if(method instanceof Method) { PhpClass phpClass = ((Method) method).getContainingClass(); if(phpClass != null && new Symfony2InterfacesUtil().isInstanceOf(phpClass, "\\Shopware\\Models\\Config\\Form")) { String content = ((StringLiteralExpression) parameters[1]).getContents(); if(StringUtils.isNotBlank(content)) { configs.add(content); } } } } } } } } }
mit
zellerdev/jabref
src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java
3259
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.formatter.bibtexfields.ClearFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.help.HelpFile; import org.jabref.logic.importer.EntryBasedFetcher; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.OptionalUtil; public class DoiFetcher implements IdBasedFetcher, EntryBasedFetcher { public static final String NAME = "DOI"; private final ImportFormatPreferences preferences; public DoiFetcher(ImportFormatPreferences preferences) { this.preferences = preferences; } @Override public String getName() { return DoiFetcher.NAME; } @Override public Optional<HelpFile> getHelpPage() { return Optional.of(HelpFile.FETCHER_DOI); } @Override public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { Optional<DOI> doi = DOI.parse(identifier); try { if (doi.isPresent()) { URL doiURL = new URL(doi.get().getURIAsASCIIString()); // BibTeX data URLDownload download = new URLDownload(doiURL); download.addHeader("Accept", "application/x-bibtex"); String bibtexString = download.asString(); // BibTeX entry Optional<BibEntry> fetchedEntry = BibtexParser.singleFromString(bibtexString, preferences, new DummyFileUpdateMonitor()); fetchedEntry.ifPresent(this::doPostCleanup); return fetchedEntry; } else { throw new FetcherException(Localization.lang("Invalid DOI: '%0'.", identifier)); } } catch (IOException e) { throw new FetcherException(Localization.lang("Connection error"), e); } catch (ParseException e) { throw new FetcherException("Could not parse BibTeX entry", e); } } private void doPostCleanup(BibEntry entry) { new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); } @Override public List<BibEntry> performSearch(BibEntry entry) throws FetcherException { Optional<String> doi = entry.getField(StandardField.DOI); if (doi.isPresent()) { return OptionalUtil.toList(performSearchById(doi.get())); } else { return Collections.emptyList(); } } }
mit
blinkboxbooks/android-app
app/src/main/java/com/blinkboxbooks/android/list/LibraryLoader.java
5766
// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved. package com.blinkboxbooks.android.list; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.database.MergeCursor; import android.support.v4.content.AsyncTaskLoader; import android.util.SparseArray; import com.blinkboxbooks.android.model.Book; import com.blinkboxbooks.android.model.BookItem; import com.blinkboxbooks.android.model.Bookmark; import com.blinkboxbooks.android.model.Query; import com.blinkboxbooks.android.model.helper.BookHelper; import com.blinkboxbooks.android.model.helper.BookmarkHelper; import com.blinkboxbooks.android.util.LogUtils; import com.crashlytics.android.Crashlytics; import java.util.ArrayList; import java.util.List; /* * A loader that queries the {@link ContentResolver} and returns a {@link Cursor}. * This class implements the {@link Loader} protocol in a standard way for * querying cursors, building on {@link AsyncTaskLoader} to perform the cursor * query on a background thread so that it does not block the application's UI. * * <p>A LibraryLoader must be built with the full information for the query to * perform. */ public class LibraryLoader extends AsyncTaskLoader<List<BookItem>> { final ForceLoadContentObserver mObserver; List<BookItem> mBookItems; private List<Query> mQueryList; /** * Creates an empty unspecified CursorLoader. You must follow this with * calls to {@link #setQueryList(List<Query>)} to specify the query to * perform. */ public LibraryLoader(Context context) { super(context); mObserver = new ForceLoadContentObserver(); } /** * Creates a fully-specified LibraryLoader. */ public LibraryLoader(Context context, List<Query> queryList) { super(context); mObserver = new ForceLoadContentObserver(); mQueryList = queryList; } public void setQueryList(List<Query> queryList) { mQueryList = queryList; } /* Runs on a worker thread */ @Override public List<BookItem> loadInBackground() { Cursor cursor = null; List<Cursor> cursorList = new ArrayList<Cursor>(); for (Query query : mQueryList) { cursor = getContext().getContentResolver().query(query.uri, query.projection, query.selection, query.selectionArgs, query.sortOrder); if (cursor != null) { // Ensure the cursor window is filled cursor.getCount(); // registerContentObserver(cursor, mObserver); cursorList.add(cursor); } } Cursor[] cursorArray = new Cursor[cursorList.size()]; List<BookItem> bookItemList; if (cursorList.size() > 0) { bookItemList = createBookItems(new MergeCursor(cursorList.toArray(cursorArray))); for (Cursor c : cursorList) { c.close(); } } else { // Return an empty book list bookItemList = new ArrayList<BookItem>(); } return bookItemList; } /** * Registers an observer to get notifications from the content provider * when the cursor needs to be refreshed. */ void registerContentObserver(Cursor cursor, ContentObserver observer) { cursor.registerContentObserver(mObserver); } /* Runs on the UI thread */ @Override public void deliverResult(List<BookItem> bookItems) { if (isReset()) { // An async query came in while the loader is stopped return; } mBookItems = bookItems; if (isStarted()) { super.deliverResult(bookItems); } } /** * Starts an asynchronous load of the book list data. When the result is ready the callbacks * will be called on the UI thread. If a previous load has been completed and is still valid * the result may be passed to the callbacks immediately. * <p/> * Must be called from the UI thread */ @Override protected void onStartLoading() { if (mBookItems != null) { deliverResult(mBookItems); } if (takeContentChanged() || mBookItems == null) { forceLoad(); } } /** * Must be called from the UI thread */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); } /** * Takes a list of books from the Cursor and arranges them into a list of BookItem objects */ private List<BookItem> createBookItems(Cursor cursor) { // Check for error cases if (cursor == null || cursor.isClosed()) { String error = String.format("Trying to create a new library item list with %s cursor.", cursor == null ? "null" : "closed"); Crashlytics.logException(new Exception(error)); LogUtils.stack(); List<BookItem> bookItems = new ArrayList<BookItem>(); return bookItems; } cursor.moveToFirst(); Book book; Bookmark bookmark; BookItem bookItem; List<BookItem> booksList = new ArrayList<BookItem>(); while (!cursor.isAfterLast()) { book = BookHelper.createBook(cursor); bookmark = BookmarkHelper.createBookmark(cursor); bookItem = new BookItem(book, bookmark, "", "", null); booksList.add(bookItem); cursor.moveToNext(); } return booksList; } }
mit
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java
911
package com.gdgand.rxjava.rxjavasample.hotandcold; import android.app.Application; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; public class SampleApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = createComponent(); } private ApplicationComponent createComponent() { return DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .dataModule(new DataModule()) .build(); } public ApplicationComponent getApplicationComponent() { return applicationComponent; } }
mit
blitz-io/blitz-java
src/main/java/io/blitz/curl/exception/ValidationException.java
473
package io.blitz.curl.exception; /** * Exceptions thrown when a validation error occur during a test execution * @author ghermeto */ public class ValidationException extends BlitzException { /** * Constructs an instance of <code>ValidationException</code> with the * specified error and reason message. * @param reason the detailed error message. */ public ValidationException(String reason) { super("validation", reason); } }
mit
LiuHongtao/Dot
app/src/main/java/com/lht/dot/ui/view/PhotoShotRecyclerView.java
1901
package com.lht.dot.ui.view; import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.bumptech.glide.Glide; /** * Created by lht-Mac on 2017/7/11. */ public class PhotoShotRecyclerView extends RecyclerView { View mDispatchToView; public PhotoShotRecyclerView(Context context) { super(context); init(); } public PhotoShotRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private void init() { setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); switch (newState) { case RecyclerView.SCROLL_STATE_SETTLING: Glide.with(getContext()).pauseRequests(); break; case RecyclerView.SCROLL_STATE_DRAGGING: case RecyclerView.SCROLL_STATE_IDLE: Glide.with(getContext()).resumeRequests(); break; } } }); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if(mDispatchToView==null){ return super.dispatchTouchEvent(event); }else{ return mDispatchToView.dispatchTouchEvent(event); } } public View getDispatchToView() { return mDispatchToView; } public void setDispatchToView(View dispatchToView) { this.mDispatchToView = dispatchToView; } public void clearDispatchToView() { setDispatchToView(null); } }
mit
OtwartaPlatformaWyborcza/OPW-backend-JavaEE
opw/src/main/java/com/adamkowalewski/opw/entity/OpwLink.java
5602
/* * The MIT License * * Copyright 2015 Adam Kowalewski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.adamkowalewski.opw.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Adam Kowalewski */ @Entity @Table(name = "opw_link", catalog = "opw", schema = "") @XmlRootElement @NamedQueries({ @NamedQuery(name = "OpwLink.findAll", query = "SELECT o FROM OpwLink o"), @NamedQuery(name = "OpwLink.findById", query = "SELECT o FROM OpwLink o WHERE o.id = :id"), @NamedQuery(name = "OpwLink.findByLabel", query = "SELECT o FROM OpwLink o WHERE o.label = :label"), @NamedQuery(name = "OpwLink.findByUrl", query = "SELECT o FROM OpwLink o WHERE o.url = :url"), @NamedQuery(name = "OpwLink.findByComment", query = "SELECT o FROM OpwLink o WHERE o.comment = :comment"), @NamedQuery(name = "OpwLink.findByActive", query = "SELECT o FROM OpwLink o WHERE o.active = :active"), @NamedQuery(name = "OpwLink.findByDateCreated", query = "SELECT o FROM OpwLink o WHERE o.dateCreated = :dateCreated")}) public class OpwLink implements Serializable { @Column(name = "dateCreated") @Temporal(TemporalType.TIMESTAMP) private Date dateCreated; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Integer id; @Size(max = 128) @Column(name = "label", length = 128) private String label; @Size(max = 256) @Column(name = "url", length = 256) private String url; @Size(max = 256) @Column(name = "comment", length = 256) private String comment; @Column(name = "active") private Boolean active; @JoinColumn(name = "opw_user_id", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) private OpwUser opwUserId; @JoinColumn(name = "opw_wynik_id", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) private OpwWynik opwWynikId; public OpwLink() { } public OpwLink(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public OpwUser getOpwUserId() { return opwUserId; } public void setOpwUserId(OpwUser opwUserId) { this.opwUserId = opwUserId; } public OpwWynik getOpwWynikId() { return opwWynikId; } public void setOpwWynikId(OpwWynik opwWynikId) { this.opwWynikId = opwWynikId; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof OpwLink)) { return false; } OpwLink other = (OpwLink) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.adamkowalewski.opw.entity.OpwLink[ id=" + id + " ]"; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } }
mit
ztmark/managementsystem
src/com/management/dao/impl/calcs/ProjectCalcDaoImpl.java
2035
package com.management.dao.impl.calcs; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.management.bean.calculate.ProjectCalc; import com.management.bean.calculate.ProjectCalcs; import com.management.dao.calcs.ProjectCalcDao; import com.management.util.DBUtil; public class ProjectCalcDaoImpl implements ProjectCalcDao { @Override public List<ProjectCalc> find() { try { Connection conn = DBUtil.getConnection(); String sql = "select * from project_calc"; QueryRunner qr = new QueryRunner(); return qr.query(conn, sql, new BeanListHandler<>(ProjectCalc.class)); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void add(ProjectCalc c) { try { Connection conn = DBUtil.getConnection(); String sql = "insert into project_calc(rank,category,weight,high,low) values(?,?,?,?,?)"; QueryRunner qr = new QueryRunner(); Object[] params = {c.getRank(),c.getCategory(),c.getWeight(),c.getHigh(),c.getLow()}; qr.update(conn, sql, params); ProjectCalcs.update(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void update(ProjectCalc c) { try { Connection conn = DBUtil.getConnection(); String sql = "update project_calc set rank=?,category=?,weight=?,high=?,low=? where id=?"; QueryRunner qr = new QueryRunner(); Object[] params = {c.getRank(),c.getCategory(),c.getWeight(),c.getHigh(),c.getLow(),c.getId()}; qr.update(conn, sql, params); ProjectCalcs.update(); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void delete(int id) { try { Connection conn = DBUtil.getConnection(); String sql = "delete from project_calc where id=?"; QueryRunner qr = new QueryRunner(); qr.update(conn, sql,id); ProjectCalcs.update(); } catch (SQLException e) { throw new RuntimeException(e); } } }
mit
ISKU/Algorithm
BOJ/13169/Main.java
630
/* * Author: Minho Kim (ISKU) * Date: March 3, 2018 * E-mail: minho.kim093@gmail.com * * https://github.com/ISKU/Algorithm * https://www.acmicpc.net/problem/13169 */ import java.util.*; public class Main { private static long[] array; private static int N; public static void main(String... args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); array = new long[N]; for (int i = 0; i < N; i++) array[i] = sc.nextInt(); System.out.print(sum(0, 0)); } private static long sum(int i, long value) { if (i == N) return value; return sum(i + 1, value + array[i]) ^ sum(i + 1, value); } }
mit
tcoenraad/compiler-construction
lib/pp/iloc/model/Program.java
7199
package pp.iloc.model; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import pp.iloc.model.Num.NumKind; import pp.iloc.model.Operand.Type; import pp.iloc.parse.FormatException; /** ILOC program. * @author Arend Rensink */ public class Program { /** Indexed list of all instructions in the program. */ private final List<Instr> instrList; /** * Indexed list of all operations in the program. * This is the flattened list of instructions. */ private final List<Op> opList; /** Mapping from labels defined in the program to corresponding * index locations. */ private final Map<Label, Integer> labelMap; /** (Partial) mapping from symbolic constants used in the program * to corresponding numeric values. */ private final Map<Num, Integer> symbMap; /** Creates a program with an initially empty instruction list. */ public Program() { this.instrList = new ArrayList<>(); this.opList = new ArrayList<>(); this.labelMap = new LinkedHashMap<>(); this.symbMap = new LinkedHashMap<>(); } /** Adds an instruction to the instruction list of this program. * @throws IllegalArgumentException if the instruction has a known label */ public void addInstr(Instr instr) { instr.setProgram(this); instr.setLine(this.opList.size()); if (instr.hasLabel()) { registerLabel(instr); } this.instrList.add(instr); for (Op op : instr) { this.opList.add(op); } } /** Registers the label of a given instruction. */ void registerLabel(Instr instr) { Label label = instr.getLabel(); Integer loc = this.labelMap.get(label); if (loc != null) { throw new IllegalArgumentException(String.format( "Label %s already occurred at location %d", label, loc)); } this.labelMap.put(label, instr.getLine()); } /** Returns the current list of instructions of this program. */ public List<Instr> getInstr() { return Collections.unmodifiableList(this.instrList); } /** Returns the operation at a given line number. */ public Op getOpAt(int line) { return this.opList.get(line); } /** Returns the size of the program, in number of operations. */ public int size() { return this.opList.size(); } /** * Returns the location at which a given label is defined, if any. * @return the location of an instruction with the label, or {@code -1} * if the label is undefined */ public int getLine(Label label) { Integer result = this.labelMap.get(label); return result == null ? -1 : result; } /** Assigns a fixed numeric value to a symbolic constant. * It is an error to assign to the same constant twice. * @param name constant name, without preceding '@' */ public void setSymb(Num symb, int value) { if (this.symbMap.containsKey(symb)) { throw new IllegalArgumentException("Constant '" + symb + "' already assigned"); } this.symbMap.put(symb, value); } /** * Returns the value with which a given symbol has been * initialised, if any. */ public Integer getSymb(Num symb) { return this.symbMap.get(symb); } /** * Returns the value with which a given named symbol has been * initialised, if any. * @param name name of the symbol, without '@'-prefix */ public Integer getSymb(String name) { return getSymb(new Num(name)); } /** * Checks for internal consistency, in particular whether * all used labels are defined. */ public void check() throws FormatException { List<String> messages = new ArrayList<>(); for (Instr instr : getInstr()) { for (Op op : instr) { messages.addAll(checkOpnds(op.getLine(), op.getArgs())); } } if (!messages.isEmpty()) { throw new FormatException(messages); } } private List<String> checkOpnds(int loc, List<Operand> opnds) { List<String> result = new ArrayList<>(); for (Operand opnd : opnds) { if (opnd instanceof Label) { if (getLine((Label) opnd) < 0) { result.add(String.format("Line %d: Undefined label '%s'", loc, opnd)); } } } return result; } /** * Returns a mapping from registers to line numbers * in which they appear. */ public Map<String, Set<Integer>> getRegLines() { Map<String, Set<Integer>> result = new LinkedHashMap<>(); for (Op op : this.opList) { for (Operand opnd : op.getArgs()) { if (opnd.getType() == Type.REG) { Set<Integer> ops = result.get(((Reg) opnd).getName()); if (ops == null) { result.put(((Reg) opnd).getName(), ops = new LinkedHashSet<>()); } ops.add(op.getLine()); } } } return result; } /** * Returns a mapping from (symbolic) variables to line numbers * in which they appear. */ public Map<String, Set<Integer>> getSymbLines() { Map<String, Set<Integer>> result = new LinkedHashMap<>(); for (Op op : this.opList) { for (Operand opnd : op.getArgs()) { if (!(opnd instanceof Num)) { continue; } if (((Num) opnd).getKind() != NumKind.SYMB) { continue; } String name = ((Num) opnd).getName(); Set<Integer> lines = result.get(name); if (lines == null) { result.put(name, lines = new LinkedHashSet<>()); } lines.add(op.getLine()); } } return result; } /** Returns a line-by-line printout of this program. */ @Override public String toString() { StringBuilder result = new StringBuilder(); for (Map.Entry<Num, Integer> symbEntry : this.symbMap.entrySet()) { result.append(String.format("%s <- %d%n", symbEntry.getKey() .getName(), symbEntry.getValue())); } for (Instr instr : getInstr()) { result.append(instr.toString()); result.append('\n'); } return result.toString(); } @Override public int hashCode() { return this.instrList.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Program)) { return false; } Program other = (Program) obj; if (!this.instrList.equals(other.instrList)) { return false; } return true; } /** Returns a string consisting of this program in a nice layout. */ public String prettyPrint() { StringBuilder result = new StringBuilder(); // first print the symbolic declaration map int idSize = 0; for (Num symb : this.symbMap.keySet()) { idSize = Math.max(idSize, symb.getName().length()); } for (Map.Entry<Num, Integer> symbEntry : this.symbMap.entrySet()) { result.append(String.format("%-" + idSize + "s <- %d%n", symbEntry .getKey().getName(), symbEntry.getValue())); } if (idSize > 0) { result.append('\n'); } // then print the instructions int labelSize = 0; int sourceSize = 0; int targetSize = 0; for (Instr i : getInstr()) { labelSize = Math.max(labelSize, i.toLabelString().length()); if (i instanceof Op && ((Op) i).getOpCode() != OpCode.out) { Op op = (Op) i; sourceSize = Math.max(sourceSize, op.toSourceString().length()); targetSize = Math.max(targetSize, op.toTargetString().length()); } } for (Instr i : getInstr()) { result.append(i.prettyPrint(labelSize, sourceSize, targetSize)); } return result.toString(); } }
mit
mikeqian/hprose-java
src/main/java/hprose/util/concurrent/Callback.java
1155
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Callback.java * * * * Callback interface for Java. * * * * LastModified: Apr 10, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ package hprose.util.concurrent; public interface Callback<V> {}
mit
dooma/falconcms
src/main/java/com/falcon/cms/web/rest/LogsResource.java
1166
package com.falcon.cms.web.rest; import com.falcon.cms.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Controller for view and managing Log Level at runtime. */ @RestController @RequestMapping("/management") public class LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } }
mit
tranquvis/SimpleSmsRemote
app/src/androidTest/java/tranquvis/simplesmsremote/CommandManagement/Modules/ModuleAudioTest.java
172
package tranquvis.simplesmsremote.CommandManagement.Modules; /** * Created by Andreas Kaltenleitner on 31.10.2016. */ public class ModuleAudioTest extends ModuleTest { }
mit
dranawhite/test-java
test-framework/test-mybatis/src/main/java/com/dranawhite/mybatis/handler/FullAddressJsonHandler.java
1582
package com.dranawhite.mybatis.handler; import com.alibaba.fastjson.JSON; import com.dranawhite.mybatis.model.Address; import com.dranawhite.mybatis.model.FullAddress; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import org.apache.ibatis.type.TypeHandler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author dranawhite 2018/1/2 * @version 1.0 */ @MappedTypes(FullAddress.class) @MappedJdbcTypes(JdbcType.VARCHAR) public class FullAddressJsonHandler implements TypeHandler<FullAddress> { @Override public void setParameter(PreparedStatement ps, int i, FullAddress parameter, JdbcType jdbcType) throws SQLException { String address = JSON.toJSONString(parameter); ps.setString(i, address); } @Override public FullAddress getResult(ResultSet rs, String columnName) throws SQLException { String address = rs.getString(columnName); return JSON.parseObject(address, FullAddress.class); } @Override public FullAddress getResult(ResultSet rs, int columnIndex) throws SQLException { String address = rs.getString(columnIndex); return JSON.parseObject(address, FullAddress.class); } @Override public FullAddress getResult(CallableStatement cs, int columnIndex) throws SQLException { String address = cs.getString(columnIndex); return JSON.parseObject(address, FullAddress.class); } }
mit
cedar-renjun/RemoteControl-Car
App/BluetoothLeGatt/Application/src/main/java/com/example/android/bluetoothlegatt/DeviceControlActivity.java
25314
/* * Copyright (C) 2013 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.bluetoothlegatt; import android.app.Activity; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CompoundButton; import android.widget.ExpandableListView; import android.widget.SeekBar; import android.widget.SimpleExpandableListAdapter; import android.widget.Switch; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * For a given BLE device, this Activity provides the user interface to connect, display data, * and display GATT services and characteristics supported by the device. The Activity * communicates with {@code BluetoothLeService}, which in turn interacts with the * Bluetooth LE API. */ public class DeviceControlActivity extends Activity implements SeekBar.OnSeekBarChangeListener ,SensorEventListener { private final static String TAG = DeviceControlActivity.class.getSimpleName(); public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME"; public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS"; public static String CLIENT_CHARACTERISTIC_MOTOR = "0000fff1-0000-1000-8000-00805f9b34fb"; private TextView mConnectionState; private TextView mDataField; private String mDeviceName; private String mDeviceAddress; private ExpandableListView mGattServicesList; private BluetoothLeService mBluetoothLeService; private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>(); private boolean mConnected = false; private BluetoothGattCharacteristic mNotifyCharacteristic; private final String LIST_NAME = "NAME"; private final String LIST_UUID = "UUID"; private byte[] value = new byte[8]; private boolean motor_run = false; private TextView mShowSpeed0,mShowSpeed1,mShowSpeed2,mShowSpeed3; private SeekBar mSetSpeed0,mSetSpeed1,mSetSpeed2,mSetSpeed3; private BluetoothGattCharacteristic mMotorChars; private SensorManager mSensorManager; private Switch mDevState = null; private Switch mConState = null; private Switch mCtlState = null; private PowerManager pm = null; PowerManager.WakeLock wl = null; // Code to manage Service lifecycle. private final ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService(); if (!mBluetoothLeService.initialize()) { Log.e(TAG, "Unable to initialize Bluetooth"); finish(); } // Automatically connects to the device upon successful start-up initialization. mBluetoothLeService.connect(mDeviceAddress); } @Override public void onServiceDisconnected(ComponentName componentName) { mBluetoothLeService = null; } }; // Handles various events fired by the Service. // ACTION_GATT_CONNECTED: connected to a GATT server. // ACTION_GATT_DISCONNECTED: disconnected from a GATT server. // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services. // ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read // or notification operations. private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { mConnected = true; updateConnectionState(R.string.connected); invalidateOptionsMenu(); } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) { mConnected = false; updateConnectionState(R.string.disconnected); invalidateOptionsMenu(); clearUI(); } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { // Show all the supported services and characteristics on the user interface. displayGattServices(mBluetoothLeService.getSupportedGattServices()); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)); } } }; // If a given GATT characteristic is selected, check for supported features. This sample // demonstrates 'Read' and 'Notify' features. See // http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete // list of supported characteristic features. private final ExpandableListView.OnChildClickListener servicesListClickListner = new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (mGattCharacteristics != null) { final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(groupPosition).get(childPosition); // final int charaProp = characteristic.getProperties(); // if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) { // // If there is an active notification on a characteristic, clear // // it first so it doesn't update the data field on the user interface. // if (mNotifyCharacteristic != null) { // mBluetoothLeService.setCharacteristicNotification( // mNotifyCharacteristic, false); // mNotifyCharacteristic = null; // } // mBluetoothLeService.readCharacteristic(characteristic); // } // if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { // mNotifyCharacteristic = characteristic; // mBluetoothLeService.setCharacteristicNotification( // characteristic, true); // } if(characteristic.getUuid().toString().equals(CLIENT_CHARACTERISTIC_MOTOR)) { mMotorChars = characteristic; value[0] = 0x04; value[5] += 10; value[5] %= 100; value[6] += 10; value[6] %= 100; characteristic.setValue(value); mBluetoothLeService.writeCharacteristic(characteristic); Log.d("BLE_TEST", "Write Begin"); Log.d("BLE_TEST", "value" + value[7]); } return true; } return false; } }; private void clearUI() { mGattServicesList.setAdapter((SimpleExpandableListAdapter) null); mDataField.setText(R.string.no_data); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gatt_services_characteristics); mShowSpeed0 = (TextView) findViewById(R.id.ShowSpeed0); mSetSpeed0 = (SeekBar) findViewById(R.id.SetSpeed0); mShowSpeed1 = (TextView) findViewById(R.id.ShowSpeed1); mSetSpeed1 = (SeekBar) findViewById(R.id.SetSpeed1); mShowSpeed2 = (TextView) findViewById(R.id.ShowSpeed2); mSetSpeed2 = (SeekBar) findViewById(R.id.SetSpeed2); mShowSpeed3 = (TextView) findViewById(R.id.ShowSpeed3); mSetSpeed3 = (SeekBar) findViewById(R.id.SetSpeed3); mDevState = (Switch) findViewById(R.id.DevState); mConState = (Switch) findViewById(R.id.ConState); mCtlState = (Switch) findViewById(R.id.CtlState); // mDevState.setEnabled(false); // 玩家模式 // mConState.setEnabled(true); // 连接状态 // mCtlState.setEnabled(false); // 停止控制 // 开发者模式 or 玩家模式 mDevState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { SetPlayMode(b); } }); // 连接 or 断开 mConState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { // TODO mBluetoothLeService.disconnect(); AppRun(); } }); // 开始控制 or 停止控制 mCtlState.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { // TODO } }); mShowSpeed0.setText("Ch0 PWM Duty " + 0); mSetSpeed0.setMax(100); mSetSpeed0.setProgress(0); mSetSpeed0.setOnSeekBarChangeListener(this); mShowSpeed1.setText("Ch1 PWM Duty " + 0); mSetSpeed1.setMax(100); mSetSpeed1.setProgress(0); mSetSpeed1.setOnSeekBarChangeListener(this); mShowSpeed2.setText("Ch2 PWM Duty " + 0); mSetSpeed2.setMax(100); mSetSpeed2.setProgress(0); mSetSpeed2.setOnSeekBarChangeListener(this); mShowSpeed3.setText("Ch3 PWM Duty " + 0); mSetSpeed3.setMax(100); mSetSpeed3.setProgress(0); mSetSpeed3.setOnSeekBarChangeListener(this); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), //SensorManager.SENSOR_DELAY_NORMAL); 50000); final Intent intent = getIntent(); mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME); mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS); // Sets up UI references. ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress); mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list); mGattServicesList.setOnChildClickListener(servicesListClickListner); mConnectionState = (TextView) findViewById(R.id.connection_state); mDataField = (TextView) findViewById(R.id.data_value); getActionBar().setTitle(mDeviceName); getActionBar().setDisplayHomeAsUpEnabled(true); Intent gattServiceIntent = new Intent(this, BluetoothLeService.class); bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); SetPlayMode(false); } private void AppRun() { Intent intent = new Intent(this, DeviceScanActivity.class); startActivity(intent); finish(); } private void SetPlayMode(boolean mode) { // true----developer mode // false---player mode TextView mText = null; if (true == mode) { // Address mText = (TextView) findViewById(R.id.device_address_0); mText.setVisibility(TextView.VISIBLE); mText = (TextView) findViewById(R.id.device_address); mText.setVisibility(TextView.VISIBLE); // Connect State mText = (TextView) findViewById(R.id.connection_state_0); mText.setVisibility(TextView.VISIBLE); mText = (TextView) findViewById(R.id.connection_state); mText.setVisibility(TextView.VISIBLE); // Data mText = (TextView) findViewById(R.id.data_value_0); mText.setVisibility(TextView.VISIBLE); mText = (TextView) findViewById(R.id.data_value); mText.setVisibility(TextView.VISIBLE); ExpandableListView mList = (ExpandableListView) findViewById(R.id.gatt_services_list); mList.setVisibility(ExpandableListView.VISIBLE); } else { // Address mText = (TextView) findViewById(R.id.device_address_0); mText.setVisibility(TextView.INVISIBLE); mText = (TextView) findViewById(R.id.device_address); mText.setVisibility(TextView.INVISIBLE); // Connect State mText = (TextView) findViewById(R.id.connection_state_0); mText.setVisibility(TextView.INVISIBLE); mText = (TextView) findViewById(R.id.connection_state); mText.setVisibility(TextView.INVISIBLE); // Data mText = (TextView) findViewById(R.id.data_value_0); mText.setVisibility(TextView.INVISIBLE); mText = (TextView) findViewById(R.id.data_value); mText.setVisibility(TextView.INVISIBLE); ExpandableListView mList = (ExpandableListView) findViewById(R.id.gatt_services_list); mList.setVisibility(ExpandableListView.INVISIBLE); } } @Override public void onProgressChanged(SeekBar var1, int var2, boolean var3) { /* value[0] = 0x04; if(mSetSpeed0 == var1) { value[4] = (byte) var1.getProgress(); mShowSpeed0.setText("Ch0 PWM Duty " + var1.getProgress()); } if(mSetSpeed1 == var1) { value[5] = (byte) var1.getProgress(); mShowSpeed1.setText("Ch1 PWM Duty " + var1.getProgress()); } if(mSetSpeed2 == var1) { value[6] = (byte) var1.getProgress(); mShowSpeed2.setText("Ch2 PWM Duty " + var1.getProgress()); } if(mSetSpeed3 == var1) { value[7] = (byte) var1.getProgress(); mShowSpeed3.setText("Ch3 PWM Duty " + var1.getProgress()); } */ //mMotorChars.setValue(value); //mBluetoothLeService.writeCharacteristic(mMotorChars); } @Override public void onStartTrackingTouch(SeekBar var1){ } @Override public void onStopTrackingTouch(SeekBar var1){ } @Override public void onSensorChanged(SensorEvent var1){ if (var1.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float[] values = var1.values; // Log.d("BLE_SENSOR", "Length" + values.length); // for(int i = 0; i < values.length; i++) { // Log.d("BLE_SENSOR", "value " + i + values[0]); // } // Control Car int speed_fb = (int)(-20*values[1]); int speed_rl = (int)(20*values[0]); //mShowSpeed0.setText("X Acc value " + speed_fb); //mShowSpeed1.setText("Y Acc value " + speed_rl); if(false == mCtlState.isChecked()){ RemoteCar(0, 0); } else { RemoteCar(speed_fb, speed_rl); } } } // Forward-Back +F-B // Right-Left +L-R void RemoteCar(int speed_fb, int speed_rl){ int speed_l = speed_fb+speed_rl/2; int speed_r = speed_fb-speed_rl/2; for(int i = 0; i < value.length; i++) { value[i] = 0; } if(speed_l > 100) speed_l = 100; if(speed_l < -100) speed_l = -100; if(speed_r > 100) speed_r = 100; if(speed_r < -100) speed_r = -100; value[0] = 0x04; if(speed_l > 0) { value[4] = (byte)speed_l; value[5] = 0; } else if(speed_l < 0){ value[4] = 0; value[5] = (byte)-speed_l; } else { // Do nothing } if(speed_r < 0) { value[6] = (byte)-speed_r; value[7] = 0; } else if(speed_r > 0){ value[6] = 0; value[7] = (byte)speed_r; } else { // Do nothing } /////// mShowSpeed0.setText("Ch0 PWM Duty " + value[4]); mShowSpeed1.setText("Ch1 PWM Duty " + value[5]); mShowSpeed2.setText("Ch2 PWM Duty " + value[6]); mShowSpeed3.setText("Ch3 PWM Duty " + value[7]); mSetSpeed0.setProgress(value[4]); mSetSpeed1.setProgress(value[5]); mSetSpeed2.setProgress(value[6]); mSetSpeed3.setProgress(value[7]); // int progress = (int)value[4]; // mSetSpeed0.setProgress(progress); // progress = (int)value[5]; // mSetSpeed1.setProgress(progress); // progress = (int)value[6]; // mSetSpeed2.setProgress(progress); // progress = (int)value[7]; // mSetSpeed3.setProgress(progress); if(null != mMotorChars) { mMotorChars.setValue(value); if(null != mBluetoothLeService) mBluetoothLeService.writeCharacteristic(mMotorChars); } else { Log.d("BLE_SENSOR", "Error"); } Log.d("BLE_SENSOR", "Update"); /////// } @Override public void onAccuracyChanged(Sensor var1, int var2){ // Do Nothing } @Override protected void onResume() { super.onResume(); if(null == pm) { pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag"); wl.acquire(); } registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); if (mBluetoothLeService != null) { final boolean result = mBluetoothLeService.connect(mDeviceAddress); Log.d(TAG, "Connect request result=" + result); } if(null != mSensorManager) { mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), //SensorManager.SENSOR_DELAY_NORMAL); 2000000); } } @Override protected void onPause() { super.onPause(); unregisterReceiver(mGattUpdateReceiver); mSensorManager.unregisterListener(this); if(null != wl) { wl.release(); wl = null; } } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); mBluetoothLeService = null; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.gatt_services, menu); if (mConnected) { menu.findItem(R.id.menu_connect).setVisible(false); menu.findItem(R.id.menu_disconnect).setVisible(true); } else { menu.findItem(R.id.menu_connect).setVisible(true); menu.findItem(R.id.menu_disconnect).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_connect: mBluetoothLeService.connect(mDeviceAddress); return true; case R.id.menu_disconnect: mBluetoothLeService.disconnect(); return true; case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private void updateConnectionState(final int resourceId) { runOnUiThread(new Runnable() { @Override public void run() { mConnectionState.setText(resourceId); } }); } private void displayData(String data) { if (data != null) { mDataField.setText(data); } } // Demonstrates how to iterate through the supported GATT Services/Characteristics. // In this sample, we populate the data structure that is bound to the ExpandableListView // on the UI. private void displayGattServices(List<BluetoothGattService> gattServices) { if (gattServices == null) return; String uuid = null; String unknownServiceString = getResources().getString(R.string.unknown_service); String unknownCharaString = getResources().getString(R.string.unknown_characteristic); ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>(); ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>(); mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>(); // Loops through available GATT Services. for (BluetoothGattService gattService : gattServices) { HashMap<String, String> currentServiceData = new HashMap<String, String>(); uuid = gattService.getUuid().toString(); currentServiceData.put( LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString)); currentServiceData.put(LIST_UUID, uuid); gattServiceData.add(currentServiceData); ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>(); List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics(); ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>(); // Loops through available Characteristics. for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { charas.add(gattCharacteristic); HashMap<String, String> currentCharaData = new HashMap<String, String>(); uuid = gattCharacteristic.getUuid().toString(); currentCharaData.put( LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString)); currentCharaData.put(LIST_UUID, uuid); gattCharacteristicGroupData.add(currentCharaData); // Set if(gattCharacteristic.getUuid().toString().equals(CLIENT_CHARACTERISTIC_MOTOR)) { mMotorChars = gattCharacteristic; } } mGattCharacteristics.add(charas); gattCharacteristicData.add(gattCharacteristicGroupData); } SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter( this, gattServiceData, android.R.layout.simple_expandable_list_item_2, new String[] {LIST_NAME, LIST_UUID}, new int[] { android.R.id.text1, android.R.id.text2 }, gattCharacteristicData, android.R.layout.simple_expandable_list_item_2, new String[] {LIST_NAME, LIST_UUID}, new int[] { android.R.id.text1, android.R.id.text2 } ); mGattServicesList.setAdapter(gattServiceAdapter); } private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED); intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED); intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE); return intentFilter; } }
mit
tantaman/commons
src/examples/java/com/tantaman/commons/examples/ParallelForDemo.java
2605
/* * Copyright 2011 Matt Crinklaw-Vogt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.tantaman.commons.examples; import java.util.Collection; import java.util.LinkedList; import org.debian.alioth.shootout.u32.nbody.NBodySystem; import com.tantaman.commons.concurrent.Parallel; public class ParallelForDemo { public static void main(String[] args) { Collection<Integer> elems = new LinkedList<Integer>(); for (int i = 0; i < 40; ++i) { elems.add(i*55000 + 100); } Parallel.For(elems, new Parallel.Operation<Integer>() { public void perform(Integer pParameter) { // do something with the parameter }; }); Parallel.Operation<Integer> bodiesOp = new Parallel.Operation<Integer>() { @Override public void perform(Integer pParameter) { NBodySystem bodies = new NBodySystem(); for (int i = 0; i < pParameter; ++i) bodies.advance(0.01); } }; System.out.println("RUNNING THE Parallel.For vs Parallel.ForFJ performance comparison"); System.out.println("This could take a while."); // warm up.. it really does have a large impact. Parallel.ForFJ(elems, bodiesOp); long start = System.currentTimeMillis(); Parallel.For(elems, bodiesOp); long stop = System.currentTimeMillis(); System.out.println("DELTA TIME VIA NORMAL PARALLEL FOR: " + (stop - start)); start = System.currentTimeMillis(); Parallel.ForFJ(elems, bodiesOp); stop = System.currentTimeMillis(); System.out.println("DELTA TIME VIA FOR FORK JOIN: " + (stop - start)); System.out.println("Finished"); } }
mit
daflockinger/spongeblogSP
src/main/java/com/flockinger/spongeblogSP/config/SwaggerConfig.java
1216
package com.flockinger.spongeblogSP.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { ApiInfo apiInfo() { return new ApiInfoBuilder().title("SpongeblogSP API").description("Spongeblog blogging API") .license("").licenseUrl("http://unlicense.org").termsOfServiceUrl("").version("1.0.0") .build(); } @Bean public Docket customImplementation() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage("com.flockinger.spongeblogSP.api.impl")).build() .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } }
mit
RudyZH/Aim2Offer
042_ReverseWordsInSequence.java
1796
/** * Created by Administrator on 2017/3/11. */ public class ReverseWordsInSequence { public void reverseSequence(String str) { if (str == null) return; String[] strArray = str.split(" "); StringBuilder sb = new StringBuilder(); for (int i = strArray.length-1; i >= 0; --i) sb.append(strArray[i] + " "); System.out.println(sb); } public static void main(String[] args) { ReverseWordsInSequence r = new ReverseWordsInSequence(); String str = "I am a Students."; r.reverseSequence(str); } } /** * Created by Administrator on 2017/3/11. */ public class ReverseWordsInSequence { public String reverseSequence(String str) { if (str == null || str.length() <= 1) return str; StringBuilder sb = new StringBuilder(str); reverse(sb, 0, str.length() - 1); int begin = 0, end = 0; while (end < str.length()) { while (end < str.length() && sb.charAt(end) != ' ') end++; reverse(sb, begin, end - 1); begin = end + 1; end = begin; } return sb.toString(); } public void reverse(StringBuilder sb, int start, int end) { if (sb == null || end <= start) return; while (start < end) { char temp = sb.charAt(start); sb.setCharAt(start, sb.charAt(end)); sb.setCharAt(end, temp); start++; end--; } } public static void main(String[] args) { ReverseWordsInSequence r = new ReverseWordsInSequence(); String str = "i am a students."; System.out.print(r.reverseSequence(str)); } }
mit
johnathandavis/H1Z1
src/main/java/h1z1/screens/PlayGameScreenManager.java
1193
package h1z1.screens; import h1z1.MainFrame; import h1z1.game.GameState; import h1z1.input.ButtonHandler; import h1z1.input.InputButton; import h1z1.input.InputProvider; import h1z1.io.ResourceManager; import javax.imageio.ImageIO; import java.awt.*; import java.util.List; import h1z1.game.Maze; public class PlayGameScreenManager extends ScreenManager { private Maze maze = new Maze(); public PlayGameScreenManager(MainFrame mainFrame) throws Exception { super(mainFrame); } @Override public void update(List<InputProvider> inputs) { } @Override public void paint(Frame frame, Graphics2D graphics) { for(int x = 0; x < Maze.WIDTH; x++){ for(int y = 0; y < Maze.HEIGHT; y++) { boolean value = maze.getValue(x, y); if (value) {graphics.setColor(Color.RED);} else{ graphics.setColor(Color.WHITE); } graphics.fillRect(Maze.OFFSET + Maze.SIZE * x, Maze.OFFSET + Maze.SIZE * y, Maze.SIZE, Maze.SIZE); } } } }
mit
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/net/message/play/entity/DestroyEntitiesMessage.java
242
package net.glowstone.net.message.play.entity; import com.flowpowered.network.Message; import java.util.List; import lombok.Data; @Data public final class DestroyEntitiesMessage implements Message { private final List<Integer> ids; }
mit
aureliano/da-mihi-logs
evt-bridge-converter/src/test/java/com/github/aureliano/evtbridge/converter/ConfigurationConverterTest.java
1411
package com.github.aureliano.evtbridge.converter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.github.aureliano.evtbridge.core.config.EventCollectorConfiguration; import com.github.aureliano.evtbridge.core.helper.DataHelper; public class ConfigurationConverterTest { @Test public void testConvert() { Map<String, Object> map = this.createConfigurationMap(); EventCollectorConfiguration configuration = new ConfigurationConverter().convert(map); assertEquals("xpto-collector", configuration.getCollectorId()); assertFalse(configuration.isPersistExecutionLog()); assertTrue(configuration.isMultiThreadingEnabled()); assertEquals(DataHelper.mapToProperties(this.createMetadata()), configuration.getMetadata()); } private Map<String, Object> createConfigurationMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("collectorId", "xpto-collector"); map.put("persistExecutionLog", false); map.put("multiThreadingEnabled", "true"); map.put("metadata", this.createMetadata()); return map; } private Map<String, Object> createMetadata() { Map<String, Object> map = new HashMap<String, Object>(); map.put("test", true); map.put("host", "127.0.0.1"); return map; } }
mit
kimikage/oiri
app/src/main/java/com/github/kimikage/oiri/svg/Transform.java
2233
/* * Copyright (c) 2016 Oiri Project * * This software is distributed under an MIT-style license. * See LICENSE file for more information. */ package com.github.kimikage.oiri.svg; import org.w3c.dom.svg.SVGMatrix; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Transform { private static final String sNumber = "([-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)"; private static final Pattern sPatternTranslate = Pattern.compile( "^\\s*translate\\s*\\(\\s*" + sNumber + "(?:\\s*[, ]\\s*" + sNumber + ")?\\s*\\)"); private static final Pattern sPatternScale = Pattern.compile( "^\\s*scale\\s*\\(\\s*" + sNumber + "(?:\\s*[, ]\\s*" + sNumber + ")?\\s*\\)"); private Matrix mMatrix; private android.graphics.Matrix mAndroidMatrix; public Transform(String list) { mMatrix = new Matrix(); String l = list; for (; ; ) { Matcher m = sPatternTranslate.matcher(l); if (m.find()) { float tx = Float.parseFloat(m.group(1)); String g2 = m.group(2); float ty = g2 != null ? Float.parseFloat(g2) : 0.0f; mMatrix = (Matrix) mMatrix.translate(tx, ty); l = l.substring(m.end()); continue; } m = sPatternScale.matcher(l); if (m.find()) { float sx = Float.parseFloat(m.group(1)); String g2 = m.group(2); float sy = g2 != null ? Float.parseFloat(g2) : sx; mMatrix = (Matrix) mMatrix.scaleNonUniform(sx, sy); l = l.substring(m.end()); continue; } break; } } public SVGMatrix getMatrix() { return mMatrix; } public android.graphics.Matrix getAndroidMatrix() { if (mAndroidMatrix == null) { mAndroidMatrix = new android.graphics.Matrix(); mAndroidMatrix.setValues(mMatrix.getValues()); } return mAndroidMatrix; } public void getMatrixValues(float[] dest) { mMatrix.getValues(dest); } }
mit
PiotrJakubiak/GymNotes
src/main/java/pl/edu/wat/tim/webstore/service/UploadFileService.java
256
package pl.edu.wat.tim.webstore.service; import pl.edu.wat.tim.webstore.model.UploadFile; /** * Created by Piotr on 15.06.2017. */ public interface UploadFileService { void save(UploadFile uploadFile); UploadFile getUploadFile(String name); }
mit
leicheng6563/MybatisTemplate
MybatisTemplate/src/main/java/com/mybatistemplate/adapter/TemplateExAdapter.java
673
package com.mybatistemplate.adapter; import com.mybatistemplate.core.GeneratorIdSqlCallback; import com.mybatistemplate.core.IdGeneratorType; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ResultMap; /** * Created by leicheng on 2016/7/12. */ public abstract class TemplateExAdapter { public void insertBatch(MappedStatement ms, ResultMap resultMap, String table, Class entity, IdGeneratorType idGeneratorType, GeneratorIdSqlCallback generatorIdSqlCallback) throws Exception{ } public void updateBatch(MappedStatement ms, ResultMap resultMap, String table, Class entity) throws Exception{ } }
mit
sanjaymandadi/mozu-java
mozu-java-core/src/main/java/com/mozu/api/resources/commerce/orders/FulfillmentActionResource.java
6320
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.resources.commerce.orders; import com.mozu.api.ApiContext; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Fulfillment resource to manage shipments or pickups of collections of packages for an order. * </summary> */ public class FulfillmentActionResource { /// /// <see cref="Mozu.Api.ApiContext"/> /// private ApiContext _apiContext; public FulfillmentActionResource(ApiContext apiContext) { _apiContext = apiContext; } /** * Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order. * <p><pre><code> * FulfillmentAction fulfillmentaction = new FulfillmentAction(); * Order order = fulfillmentaction.performFulfillmentAction( action, orderId); * </code></pre></p> * @param orderId Unique identifier of the order. * @param action Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction */ public com.mozu.api.contracts.commerceruntime.orders.Order performFulfillmentAction(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId) throws Exception { return performFulfillmentAction( action, orderId, null); } /** * Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order. * <p><pre><code> * FulfillmentAction fulfillmentaction = new FulfillmentAction(); * Order order = fulfillmentaction.performFulfillmentAction( action, orderId, responseFields); * </code></pre></p> * @param orderId Unique identifier of the order. * @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu. * @param action Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction */ public com.mozu.api.contracts.commerceruntime.orders.Order performFulfillmentAction(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.FulfillmentActionClient.performFulfillmentActionClient( action, orderId, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * orders-fulfillment Post ResendPackageFulfillmentEmail description DOCUMENT_HERE * <p><pre><code> * FulfillmentAction fulfillmentaction = new FulfillmentAction(); * Order order = fulfillmentaction.resendPackageFulfillmentEmail( action, orderId); * </code></pre></p> * @param orderId Unique identifier of the order. * @param action Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction */ public com.mozu.api.contracts.commerceruntime.orders.Order resendPackageFulfillmentEmail(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId) throws Exception { return resendPackageFulfillmentEmail( action, orderId, null); } /** * orders-fulfillment Post ResendPackageFulfillmentEmail description DOCUMENT_HERE * <p><pre><code> * FulfillmentAction fulfillmentaction = new FulfillmentAction(); * Order order = fulfillmentaction.resendPackageFulfillmentEmail( action, orderId, responseFields); * </code></pre></p> * @param orderId Unique identifier of the order. * @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu. * @param action Properties of an action to perform when fulfilling an item in an order, whether through in-store pickup or direct shipping. * @return com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction */ public com.mozu.api.contracts.commerceruntime.orders.Order resendPackageFulfillmentEmail(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> client = com.mozu.api.clients.commerce.orders.FulfillmentActionClient.resendPackageFulfillmentEmailClient( action, orderId, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } }
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/xmltext/src/main/java/at/ac/tuwien/big/xmlintelledit/xmltext/ecoretransform/impl/TransformatorStructure.java
62302
package at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.activation.UnsupportedDataTypeException; import org.apache.commons.lang3.StringEscapeUtils; import org.eclipse.emf.common.util.Enumerator; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.util.BasicExtendedMetaData; import org.eclipse.emf.ecore.util.ExtendedMetaData; import org.eclipse.emf.ecore.util.FeatureMap; import org.eclipse.emf.ecore.util.FeatureMapUtil; import org.eclipse.emf.ecore.xmi.XMLResource; import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.CollectionValueTransformation; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.EAttributeTransformator; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.EReferenceTransformator; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.PartialObjectCopier; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.SingleObjectTransformator; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.Transformator; import at.ac.tuwien.big.xmlintelledit.xmltext.ecoretransform.ValueTransformator; import at.ac.tuwien.big.xtext.util.MyEcoreUtil; @SuppressWarnings({"rawtypes", "unchecked", "unused"}) public class TransformatorStructure { private Map<EAttribute, EAttributeTransformator> xmlToEcoreAttr = new HashMap<EAttribute, EAttributeTransformator>(); private Map<EAttribute, EAttributeTransformator> ecoreToXmlAttr = new HashMap<EAttribute, EAttributeTransformator>(); private Map<EStructuralFeature, PartialObjectCopier> xmlToEcoreChanger = new HashMap<>(); private Map<EStructuralFeature, PartialObjectCopier> ecoreToXmlChanger = new HashMap<>(); private TypeTransformatorStore store; private Map<EReference, EReferenceTransformator> xmlToEcoreRef = new HashMap<EReference, EReferenceTransformator>(); private Map<EReference, EReferenceTransformator> ecoreToXmlRef = new HashMap<EReference, EReferenceTransformator>(); private Map<String, EObject> fragmentToXmlObject = new HashMap<String, EObject>(); private Map<EReference,EReference> xmlToEcoreReferences = new HashMap<EReference, EReference>(); private Map<EAttribute,EAttribute> xmlToEcoreAttribute = new HashMap<>(); private Map<EEnum,EEnum> copiedEEnums = new HashMap<EEnum, EEnum>(); private Map<EEnumLiteral,EEnumLiteral> copiedEEnumLiterals = new HashMap<EEnumLiteral, EEnumLiteral>(); private Map<EEnumLiteral,EEnumLiteral> backEEnumLiteral = new HashMap<EEnumLiteral, EEnumLiteral>(); private Map<String,EEnumLiteral> backEEnumLiteralStr = new HashMap<String, EEnumLiteral>(); private Map<EClass, EClass> xmlToEcoreClasses = new HashMap<EClass, EClass>(); private Map<EClass, EClass> ecoreToXmlClasses = new HashMap<EClass, EClass>(); private Map<EStructuralFeature,EStructuralFeature> ecoreToXmlFeature = new HashMap<EStructuralFeature, EStructuralFeature>(); private Map<String,EObject> targetMap = new HashMap<String, EObject>(); private Set<EObject> handledTargets = new HashSet<EObject>(); private Map<String,String> restrictedDatatypes = new HashMap<String,String>(); public Map<String, String> getRestrictedDatatypes() { return restrictedDatatypes; } public String getStoreName(EObject eobj) { if (eobj instanceof EClass) { return ((EClass) eobj).getName(); } else if (eobj instanceof EEnum) { return ((EEnum)eobj).getName(); } else if (eobj instanceof EStructuralFeature) { EStructuralFeature esf = (EStructuralFeature)eobj; return esf.getEContainingClass().getName()+"."+esf.getName(); } return null; } public void readInBasicTarget(Resource targetRes) { for (EObject eobj: (Iterable<EObject>)()->targetRes.getAllContents()) { String storeName = getStoreName(eobj); if (storeName != null) { targetMap.put(storeName, eobj); } } } public EObject getIfExists(String targetName) { EObject ret = targetMap.get(targetName); if (ret != null) { handledTargets.add(ret); } return ret; } //1 to one correspondance public TransformatorStructure(Resource source, Resource target) { for (EObject eobj: (Iterable<EObject>)source.getAllContents()) { if (eobj instanceof EClass) { EClass cl = (EClass)eobj; EClass ecoreClass = (EClass)target.getEObject(source.getURIFragment(eobj)); xmlToEcoreClasses.put(cl, ecoreClass); ecoreToXmlClasses.put(ecoreClass,cl); System.out.println("Associating "+ cl+ " to "+ecoreClass); //Not all, because then we would do something multiple times for (EAttribute eattr: cl.getEAttributes()) { EAttribute newA = (EAttribute)target.getEObject(source.getURIFragment(eattr)); xmlToEcoreAttribute.put(eattr, newA); } for (EReference eattr: cl.getEReferences()) { EReference newRef = (EReference)target.getEObject(source.getURIFragment(eattr)); xmlToEcoreReferences.put(eattr, newRef); } } else if (eobj instanceof EEnum) { EEnum eenum = (EEnum)eobj; copiedEEnums.put(eenum, (EEnum)target.getEObject(source.getURIFragment(eenum))); for (EEnumLiteral lit: eenum.getELiterals()) { EEnumLiteral back = (EEnumLiteral)target.getEObject(source.getURIFragment(lit)); copiedEEnumLiterals.put(lit, back); backEEnumLiteral.put(back, lit); backEEnumLiteralStr.put(eenum.getName()+"."+lit.getLiteral(), lit); } //Ignore for now } else if (eobj instanceof EDataType) { //??? } else if (eobj instanceof EAttribute) { //Have handled every important above? } else if (eobj instanceof EReference) { //Have handled every important above? } } //TODO: F�r kopierte ist es gef�hrlich ... for (Entry<EClass,EClass> entr: xmlToEcoreClasses.entrySet()) { if (!augmentEClassBasic(entr.getKey(), entr.getValue())) { //TODO: Das stimmt so nicht ... entr.setValue(null); } } for (Entry<EAttribute,EAttribute> entr: xmlToEcoreAttribute.entrySet()) { if (!augmentAttributeBasic(entr.getKey(), entr.getValue())) { entr.setValue(null); } } for (Entry<EReference,EReference> entr: xmlToEcoreReferences.entrySet()) { if (!augmentReferenceBasic(entr.getKey(), entr.getValue())) { entr.setValue(null); } } } private EClass mixedData; private EClass mixedText; private EClass mixedFeature; private EClass mixedBaseClass; private EReference mixedBaseMixedAttr; private EAttribute mixedValueAttr; private EPackage ecorePackage; public void generateMixClasses() { if (mixedData == null) { mixedData = (EClass)getIfExists("MixedData"); if (mixedData == null) { mixedData = EcoreFactory.eINSTANCE.createEClass(); mixedData.setName("MixedData"); mixedData.setAbstract(true); mixedValueAttr = EcoreFactory.eINSTANCE.createEAttribute(); mixedValueAttr.setName("value"); mixedValueAttr.setEType(EcorePackage.Literals.ESTRING); mixedValueAttr.setLowerBound(1); mixedValueAttr.setUpperBound(1); mixedData.getEStructuralFeatures().add(mixedValueAttr); ecorePackage.getEClassifiers().add(mixedData); } else { mixedValueAttr = (EAttribute)mixedData.getEStructuralFeature("value"); } mixedText = (EClass)getIfExists("MixedText"); if (mixedText == null) { mixedText = EcoreFactory.eINSTANCE.createEClass(); mixedText.setName("MixedText"); mixedText.getESuperTypes().add(mixedData); ecorePackage.getEClassifiers().add(mixedText); } mixedFeature = (EClass)getIfExists("MixedFeature"); if (mixedFeature == null) { mixedFeature = EcoreFactory.eINSTANCE.createEClass(); mixedFeature.setName("MixedFeature"); mixedFeature.getESuperTypes().add(mixedData); ecorePackage.getEClassifiers().add(mixedFeature); } mixedBaseClass = (EClass)getIfExists("MixedBaseClass"); if (mixedBaseClass == null) { mixedBaseClass = EcoreFactory.eINSTANCE.createEClass(); mixedBaseClass.setName("MixedBaseClass"); mixedBaseClass.setAbstract(true); mixedBaseMixedAttr = EcoreFactory.eINSTANCE.createEReference(); mixedBaseMixedAttr.setName("mixed"); mixedBaseMixedAttr.setLowerBound(0); mixedBaseMixedAttr.setUpperBound(-1); mixedBaseMixedAttr.setContainment(true); mixedBaseMixedAttr.setEType(mixedData); mixedBaseClass.getEStructuralFeatures().add(mixedBaseMixedAttr); ecorePackage.getEClassifiers().add(mixedBaseClass); } else { mixedBaseMixedAttr = (EReference)mixedBaseClass.getEStructuralFeature("mixed"); } } } public boolean isMixed(EStructuralFeature feat) { //TODO: ... faster if (!"mixed".equals(feat.getName())) { return false; } if ((feat.getEType() instanceof EClass && mixedData.isSuperTypeOf((EClass)feat.getEType())) || (feat.getEType() != null && "EFeatureMapEntry".equals(feat.getEType().getName()))) { return true; } return false; } public TransformatorStructure(TypeTransformatorStore store, ResourceSet resourceSet, File xmlEcore) { this.store = store; parseXmlEcore(resourceSet,xmlEcore); } private TransformatorStructure() { } public static TransformatorStructure withKnownResult(TypeTransformatorStore store, ResourceSet resourceSet, Resource xmlResource, Resource ecoreResource) { TransformatorStructure ret = new TransformatorStructure(); ret.store = store; ret.xmlResource = ()->xmlResource.getAllContents(); ret.ecoreResources.add(ecoreResource); ret.readInBasicTarget(ecoreResource); ret.parseXmlEcoreBasic(ecoreResource, resourceSet, xmlResource.getURI(), ()->xmlResource.getAllContents(), false); return ret; } public static TransformatorStructure fromXmlEcore(TypeTransformatorStore store, ResourceSet resourceSet, Resource ecoreXmlResource, String targetFilename) { TransformatorStructure ret = new TransformatorStructure(); ret.store = store; ret.xmlResource = ()->ecoreXmlResource.getAllContents(); ret.parseXmlEcore(null,resourceSet,targetFilename==null?null:URI.createFileURI(targetFilename),ret.xmlResource, false); return ret; } public static TransformatorStructure fromXmlEcores(TypeTransformatorStore store, ResourceSet resourceSet, List<Resource> ecoreXmlResources, String targetFilename) { TransformatorStructure ret = new TransformatorStructure(); ret.store = store; int ind = 0; for (Resource ecoreXmlResource: ecoreXmlResources) { ret.xmlResource = ()->ecoreXmlResource.getAllContents(); ret.parseXmlEcore(null,resourceSet,targetFilename==null?null:URI.createFileURI(targetFilename+(++ind)+".ecore"),ret.xmlResource, false); } return ret; } public TransformatorStructure(TypeTransformatorStore store, ResourceSet resourceSet, Resource xmlResource) { this.store = store; this.xmlResource = ()->xmlResource.getAllContents(); parseXmlEcore(null,resourceSet,URI.createURI(xmlResource.getURI()+"simplified"),this.xmlResource,false); } public TransformatorStructure(TypeTransformatorStore store, ResourceSet resourceSet, File xmlResourceFile, Iterable<EObject> xmlResource) { this.store = store; this.xmlResource = xmlResource; parseXmlEcore(null,resourceSet,URI.createFileURI(xmlResourceFile.getAbsolutePath()+".simple.ecore"),xmlResource,false); } private EAttribute commonIdAttribute = null; private EClass commonIdClass = null; private Map<EClass, EAttribute> realId = new HashMap<EClass, EAttribute>(); //private Map<EAttribute, EReference> attributeToReference = new HashMap<>(); //private Map<EReference, EAttribute> referenceToAttribute = new HashMap<>(); private void buildChangers() { for (Entry<EAttribute,EAttributeTransformator> entry: xmlToEcoreAttr.entrySet()) { // EAttribute attr = entry.getKey(); // TODO remove unused? EAttributeTransformator tf = entry.getValue(); PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl trans, EObject xmlObject, EObject ret) { //Workaround - remove if ressource is always correct try { if (xmlObject.eIsSet(tf.getXml())) { Collection c = MyEcoreUtil.getAsCollection(xmlObject, tf.getXml()); c = tf.convertToEcore(c); MyEcoreUtil.setAsCollectionBasic(ret,tf.getEcore(),c); } else { ret.eUnset(tf.getEcore()); } } catch (IllegalArgumentException e) { EStructuralFeature esf = xmlObject.eClass().getEStructuralFeature(tf.getXml().getName()); System.err.println(e.getMessage()+" => replaced by " + esf); if (esf != null) { if (xmlObject.eIsSet(esf)) { Collection c = MyEcoreUtil.getAsCollection(xmlObject, esf); c = tf.convertToEcore(c); MyEcoreUtil.setAsCollectionBasic(ret,tf.getEcore(),c); } else { ret.eUnset(tf.getEcore()); } } } } }; xmlToEcoreChanger.put(tf.getXml(),poc); xmlToEcoreChanger.put(tf.getEcore(),poc); } for (Entry<EAttribute,EAttributeTransformator> entry: ecoreToXmlAttr.entrySet()) { // EAttribute attr = entry.getKey(); // TODO remove unused? EAttributeTransformator tf = entry.getValue(); PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl trans, EObject eobject, EObject ret) { if (eobject.eIsSet(tf.getEcore())) { // String bla = attr.getName(); // TODO remove unused? Collection c = MyEcoreUtil.getAsCollection(eobject, tf.getEcore()); c = tf.convertToXml(c); MyEcoreUtil.setAsCollectionBasic(ret,tf.getXml(),c); } else { ret.eUnset(tf.getXml()); } } }; ecoreToXmlChanger.put(tf.getXml(),poc); ecoreToXmlChanger.put(tf.getEcore(),poc); } for (Entry<EReference,EReferenceTransformator> entry: xmlToEcoreRef.entrySet()) { // EReference ref = entry.getKey(); // TODO remove unused? EReferenceTransformator tf = entry.getValue(); // ResourceSet rs; // TODO remove unused? PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl trans, EObject xmlObject, EObject ret) { try { if (xmlObject.eIsSet(tf.getXml())) { Collection c = MyEcoreUtil.getAsCollection(xmlObject, tf.getXml()); c = tf.convertToEcore(c, trans); MyEcoreUtil.setAsCollectionBasic(ret,tf.getEcore(),c); } else { ret.eUnset(tf.getEcore()); } } catch (IllegalArgumentException e) { EStructuralFeature esf = xmlObject.eClass().getEStructuralFeature(tf.getXml().getName()); System.err.println(e.getMessage()+" => replaced by " + esf); if (esf != null) { if (xmlObject.eIsSet(esf)) { Collection c = MyEcoreUtil.getAsCollection(xmlObject, esf); c = tf.convertToEcore(c, trans); MyEcoreUtil.setAsCollectionBasic(ret,tf.getEcore(),c); } else { ret.eUnset(tf.getEcore()); } } } } }; xmlToEcoreChanger.put(tf.getXml(),poc); xmlToEcoreChanger.put(tf.getEcore(),poc); } for (Entry<EReference,EReferenceTransformator> entry: ecoreToXmlRef.entrySet()) { // EReference ref = entry.getKey(); // TODO remove unused? EReferenceTransformator tf = entry.getValue(); PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl trans, EObject eobject, EObject ret) { if (eobject.eIsSet(tf.getEcore())) { Collection c = MyEcoreUtil.getAsCollection(eobject, tf.getEcore()); c = tf.convertToXml(c, trans); MyEcoreUtil.setAsCollectionBasic(ret,tf.getXml(),c); } else { ret.eUnset(tf.getXml()); } } }; ecoreToXmlChanger.put(tf.getXml(),poc); ecoreToXmlChanger.put(tf.getEcore(),poc); } } private void calcId() { //Baue �berklasse �ber alle IDs List<EClass> allIdClasses = new ArrayList<EClass>(); for (EClass ecl: ecoreToXmlClasses.keySet()) { for (EAttribute attr: ecl.getEAttributes()) { if (attr.isID()) { allIdClasses.add(ecl); } } } Set<EClass> allIdClassesSet = new HashSet<EClass>(allIdClasses); if (allIdClasses.isEmpty()) { //Nothing to do return; } //If there is only one, just pick the first ID you find and you are done! if (allIdClassesSet.size() == 1) { commonIdClass = allIdClasses.get(0); commonIdAttribute = commonIdClass.getEIDAttribute(); } else { //Check if there is a superclass which is a superclass of all id classes Set<EClass> superClasses = new HashSet<EClass>(); EClass first = allIdClasses.get(0); superClasses.add(first); superClasses.addAll(first.getEAllSuperTypes()); for (int i = 1; i < allIdClasses.size(); ++i) { EClass cl = allIdClasses.get(i); Set<EClass> subSuper = new HashSet<EClass>(cl.getEAllSuperTypes()); subSuper.add(cl); superClasses.retainAll(subSuper); } //All of these classes are candidates, but there must exist no class which has an attribute added due to that fact for (EClass cl: ecoreToXmlClasses.keySet()) { if (allIdClassesSet.contains(cl)) { continue; } Set<EClass> superTypes = new HashSet<>(cl.getEAllSuperTypes()); superTypes.retainAll(allIdClassesSet); if (!superTypes.isEmpty()) { continue; } superClasses.remove(cl); superClasses.removeAll(cl.getEAllSuperTypes()); } boolean idAttributeExisted = false; //Now you can arbitrarily pick one of the remaining candidates to add the ID attribute if (!superClasses.isEmpty()) { commonIdClass = superClasses.iterator().next(); } else { //Create commonIdClass = (EClass)getIfExists("CommonIdClass"); if (commonIdClass == null) { commonIdClass = EcoreFactory.eINSTANCE.createEClass(); commonIdClass.setAbstract(true); commonIdClass.setName("CommonIdClass"); ecorePackage.getEClassifiers().add(commonIdClass); } else { idAttributeExisted = true; } } Object commonIdAttributeO = getIfExists("CommonIdClass.name"); if (commonIdAttributeO instanceof EAttribute) { commonIdAttribute = (EAttribute)commonIdAttributeO; } else { commonIdAttribute = EcoreFactory.eINSTANCE.createEAttribute(); } commonIdAttribute.setName("name"); //Good to provide an xtext ID! commonIdAttribute.setUnique(true); commonIdAttribute.setID(true); commonIdAttribute.setLowerBound(1); commonIdAttribute.setUpperBound(1); commonIdAttribute.setEType(EcorePackage.Literals.ESTRING); if (!idAttributeExisted) { commonIdClass.getEStructuralFeatures().add(commonIdAttribute); } for (EClass cl: ecoreToXmlClasses.keySet()) { realId.put(cl, cl.getEIDAttribute()); } if (!idAttributeExisted) { for (EClass cl: allIdClasses) { EAttribute id = cl.getEIDAttribute(); if (cl != commonIdClass) { if (id != null && id.getEContainingClass() == cl) { cl.getEStructuralFeatures().remove(id); } if (!cl.getEAllSuperTypes().contains(commonIdClass)) { cl.getESuperTypes().add(commonIdClass); } } } } } //Whenever you have an attribute which is an IDREF, replace it by a reference for (Entry<EAttribute,EAttributeTransformator> entry: xmlToEcoreAttr.entrySet()) { EAttribute attr = entry.getKey(); String attrEType = (attr.getEType() != null)?attr.getEType().getName():""; if ("IDREF".equals(attrEType)) { EAttribute ecoreAttr = entry.getValue().getEcore(); EObject erefO = getIfExists(getEcoreClassName(attr.getEContainingClass())+"."+getEcoreAttributeName(attr)); EReference ref = null; boolean hadReference = false; if (erefO instanceof EReference) { ref = (EReference)erefO; hadReference = true; } else { ref = EcoreFactory.eINSTANCE.createEReference(); setSimple(ecoreAttr, ref); ref.setName(ecoreAttr.getName()); ref.setEType(commonIdClass); } EReference fref = ref; //attributeToReference.put(ecoreAttr, ref); //referenceToAttribute.put(ref, ecoreAttr); if (!hadReference && ecoreAttr.getEContainingClass() != null) { int idx = ecoreAttr.getEContainingClass().getEStructuralFeatures().indexOf(ecoreAttr); ecoreAttr.getEContainingClass().getEStructuralFeatures().add(idx,ref); ecoreAttr.getEContainingClass().getEStructuralFeatures().remove(ecoreAttr); } //Konvertiere jedes Objekt in seine ID PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl transformator, EObject from, EObject to) { Collection c = MyEcoreUtil.getAsCollection(from, fref); List<Object> targetIds = new ArrayList<Object>(); for (Object o: c) { EObject eo = (EObject)o; EAttribute idAttr = null; if (eo != null && eo.eClass() != null && eo.eClass().getEIDAttribute() != null) { idAttr = eo.eClass().getEIDAttribute(); } Collection ids = MyEcoreUtil.getAsCollection(eo, idAttr); targetIds.addAll(ids); } MyEcoreUtil.setAsCollectionBasic(to, attr, targetIds); } }; ecoreToXmlChanger.put(ref,poc); ecoreToXmlChanger.put(attr,poc); ecoreToXmlFeature.put(ref, attr); poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl transformator, EObject from, EObject to) { Collection c = MyEcoreUtil.getAsCollection(from, attr); List<EObject> targetObjects = new ArrayList<>(); for (Object o: c) { EObject eo = transformator.getXmlObject(String.valueOf(o)); if (eo != null) { targetObjects.add(transformator.xml2Eobject(eo)); } } MyEcoreUtil.setAsCollectionBasic(to, fref, targetObjects); } }; xmlToEcoreChanger.put(attr, poc); xmlToEcoreChanger.put(ref, poc); } if (attr.isID()) { //Konvertiere jedes Objekt in seine ID PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl transformator, EObject from, EObject to) { Collection c = MyEcoreUtil.getAsCollection(from, commonIdAttribute); MyEcoreUtil.setAsCollectionBasic(to, to.eClass().getEIDAttribute(), c); } }; ecoreToXmlChanger.put(commonIdAttribute,poc); ecoreToXmlChanger.put(attr,poc); poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl transformator, EObject from, EObject to) { Collection c = MyEcoreUtil.getAsCollection(from, from.eClass().getEIDAttribute()); MyEcoreUtil.setAsCollectionBasic(to, commonIdAttribute, c); } }; xmlToEcoreChanger.put(attr, poc); xmlToEcoreChanger.put(commonIdAttribute, poc); } } } public void augmentWithStandardDatatypes() { //Whenever you have an attribute which is an IDREF, replace it by a reference for (Entry<EAttribute,EAttributeTransformator> entry: xmlToEcoreAttr.entrySet()) { EAttribute attr = entry.getKey(); String attrEType = (attr.getEType() != null)?attr.getEType().getName():""; EAttribute ecoreAttr = entry.getValue().getEcore(); if (ecoreAttr != null) { String name = attr.getEAttributeType().getName(); String instanceClassName = attr.getEAttributeType().getInstanceClassName(); System.out.println("Have attribute with name "+name+ " of type "+attrEType+" with instance class "+instanceClassName); //TODO: Warum ist das so? Gibt es auch andere unterschiede? if ("AnyURI".equals(attrEType)) { attrEType = "URI"; } if (store.isStandardDatatype(attrEType)) { EAnnotation annot = ecoreAttr.getEAnnotation("http://big.tuwien.ac.at/standardXMLDatatype"); if (annot == null) { ecoreAttr.getEAnnotations().add(annot = EcoreFactory.eINSTANCE.createEAnnotation()); annot.setSource("http://big.tuwien.ac.at/standardXMLDatatype"); } annot.getDetails().put("type",attrEType); } } } } public EAttribute transformatorEcoreAttribute(EClass cl, EAttribute base) { if (base == commonIdAttribute) { return realId.getOrDefault(cl,base); } return base; } public EAttribute getIdAttribute() { if (commonIdAttribute == null) { calcId(); } return commonIdAttribute; } private List<Resource> ecoreResources = new ArrayList<Resource>(); private Iterable<EObject> xmlResource; public EClass getEcoreEClass(EClass xml) { return xmlToEcoreClasses.get(xml); } public EClass getXmlEClass(EClass ecore) { return ecoreToXmlClasses.get(ecore); } public PartialObjectCopier getChangerForXml(EStructuralFeature ecorefeat) { return ecoreToXmlChanger.get(ecorefeat); } public PartialObjectCopier getChangerForEcore(EStructuralFeature xmlfeat) { return xmlToEcoreChanger.get(xmlfeat); } private EAttributeTransformator getTransformatorForXml(EAttribute xml) { EAttributeTransformator trafo = xmlToEcoreAttr.get(xml); if (trafo == null) { String fragment = xml.eResource().getURIFragment(xml); EObject eobj = fragmentToXmlObject.get(fragment); EAttributeTransformator ftrafo = xmlToEcoreAttr.get(eobj); if (ftrafo == null) { System.err.println("No transformator for "+xml +" found, eobject: " +eobj+"!"); } else { trafo = new EAttributeTransformatorImpl(xml, ftrafo.getEcore(), ftrafo.getTransformation()); } } if (trafo.getEcore().isID() && trafo.getEcore() != commonIdAttribute) { EAttributeTransformator ftrafo = trafo; return new EAttributeTransformator() { @Override public EAttribute getXml() { return xml; } @Override public CollectionValueTransformation getTransformation() { return ftrafo.getTransformation(); } @Override public EAttribute getEcore() { return commonIdAttribute; } }; } return trafo; } private EAttributeTransformator getTransformatorForEcore(EClass eClass, EAttribute ecore) { return ecoreToXmlAttr.get(transformatorEcoreAttribute(eClass,ecore)); } private EReferenceTransformator getTransformatorForXml(EReference xml) { EReferenceTransformator trafo = xmlToEcoreRef.get(xml); if (trafo == null) { String fragment = xml.eResource().getURIFragment(xml); EObject eobj = fragmentToXmlObject.get(fragment); trafo = xmlToEcoreRef.get((EReference)eobj); if (trafo == null) { System.err.println("No transformator for "+xml +" found, eobject: " +eobj+"!"); } else { trafo = new EReferenceTransformatorImpl(xml, trafo.getEcore(), trafo.getTransformation()); } } return trafo; } private EReferenceTransformator getTransformatorForEcore(EReference ecore) { return ecoreToXmlRef.get(ecore); } private boolean addedAnyAnnotations = false; private EClass documentRootClassXml; private EClass rootClassXml; private EClass rootClassEcore; private EReference rootReferenceXml; public void parseXmlEcoreBasic(Resource localEcore, ResourceSet resourceSet, URI targetEcoreUri, Iterable<EObject> xmlResource, boolean generateFile) { EPackage xmlEPkg = null; for (EObject eobj: xmlResource) { if (eobj instanceof EPackage) { xmlEPkg = (EPackage)eobj; resourceSet.getPackageRegistry().put(xmlEPkg.getNsURI(), eobj); } } ecorePackage = (EPackage)localEcore.getContents().get(0); List<EAttribute> eattrs = new ArrayList<>(); List<EReference> erefs = new ArrayList<>(); List<EClass> eclasses = new ArrayList<>(); List<EEnum> eenums = new ArrayList<>(); resourceSet.getPackageRegistry().put(ecorePackage.getNsURI(), ecorePackage); for (EObject eobj: xmlResource) { if (eobj.eResource() != null) { fragmentToXmlObject.put(eobj.eResource().getURIFragment(eobj),eobj); } if (eobj instanceof EClass) { EClass cl = (EClass)eobj; if (!cl.getName().equals("DocumentRoot")) { EClass ecoreClass = generateShallowEClass(cl); eclasses.add(cl); xmlToEcoreClasses.put(cl, ecoreClass); ecoreToXmlClasses.put(ecoreClass,cl); System.out.println("Associating "+ cl+ " to "+ecoreClass); //Not all, because then we would do something multiple times for (EAttribute eattr: cl.getEAttributes()) { xmlToEcoreAttribute.put(eattr, generateShallowAttribute(cl, ecoreClass, eattr)); eattrs.add(eattr); } for (EReference eattr: cl.getEReferences()) { xmlToEcoreReferences.put(eattr, generateShallowReference(cl, ecoreClass, eattr)); erefs.add(eattr); } } else { //Analyze subclass documentRootClassXml = cl; rootReferenceXml = TransformatorImpl.getRootFeature(cl); rootClassXml = rootReferenceXml.getEReferenceType(); } } else if (eobj instanceof EEnum) { // EEnum eenum = (EEnum)eobj; // TODO remove unused? EEnum targetEEnum = generateEEnum((EEnum)eobj); eenums.add(targetEEnum); //Ignore for now } else if (eobj instanceof EDataType) { //?? } else if (eobj instanceof EAttribute) { //Have handled every important above? } else if (eobj instanceof EReference) { //Have handled every important above? } } rootClassEcore = xmlToEcoreClasses.get(rootClassXml); for (EClass key: eclasses) { if (!augmentEClassBasic(key, xmlToEcoreClasses.get(key))) { //TODO: Das stimmt so nicht ... xmlToEcoreClasses.remove(key); } } for (EAttribute attr: eattrs) { if (!augmentAttributeBasic(attr, xmlToEcoreAttribute.get(attr))) { xmlToEcoreAttribute.remove(attr); } } for (EReference key: erefs) { if (!augmentReferenceBasic(key, xmlToEcoreReferences.get(key))) { xmlToEcoreReferences.remove(key); } } buildChangers(); calcId(); augmentWithStandardDatatypes(); if (generateFile) { try { int ind = 0; for (Resource ecoreRes: ecoreResources) { ecoreRes.save(new FileOutputStream("testoutput"+(++ind)+".ecore"),null); } } catch (IOException e) { e.printStackTrace(); } } } public void parseXmlEcore(Resource localECoreResource, ResourceSet resourceSet, /*String xmlEcoreName, */URI targetEcoreUri, Iterable<EObject> xmlResource, boolean generateFile) { EPackage xmlEPkg = null; for (EObject eobj: xmlResource) { if (eobj instanceof EPackage) { xmlEPkg = (EPackage)eobj; resourceSet.getPackageRegistry().put(xmlEPkg.getNsURI(), eobj); } } if (xmlEPkg == null) { for (EObject eobj: xmlResource) { System.out.println("Found object: "+eobj); } } if (localECoreResource == null) { localECoreResource = targetEcoreUri==null?new XMIResourceImpl(): new XMIResourceImpl( resourceSet.getURIConverter().normalize(targetEcoreUri) ); this.ecoreResources.add(localECoreResource); ecorePackage = EcoreFactory.eINSTANCE.createEPackage(); ecorePackage.setNsURI(xmlEPkg.getNsURI()+"simplified"); //epkg.setNsURI(xmlEPkg.getNsURI()+"-simplified"); //String xmlEcoreShortName = xmlEcoreName.split("\\.", 2)[0]; ecorePackage.setName((xmlEPkg.getName()+"Simplified").replace(".", "")); ecorePackage.setNsPrefix(xmlEPkg.getNsPrefix()+"s"); localECoreResource.getContents().add(ecorePackage); } else { ecorePackage = (EPackage)localECoreResource.getContents().get(0); } List<EAttribute> eattrs = new ArrayList<>(); List<EReference> erefs = new ArrayList<>(); List<EClass> eclasses = new ArrayList<>(); List<EEnum> eenums = new ArrayList<>(); resourceSet.getPackageRegistry().put(ecorePackage.getNsURI(), ecorePackage); for (EObject eobj: xmlResource) { if (eobj.eResource() != null) { fragmentToXmlObject.put(eobj.eResource().getURIFragment(eobj),eobj); } if (eobj instanceof EClass) { EClass cl = (EClass)eobj; if (!cl.getName().equals("DocumentRoot")) { EClass ecoreClass = generateShallowEClass(cl); eclasses.add(cl); xmlToEcoreClasses.put(cl, ecoreClass); ecoreToXmlClasses.put(ecoreClass,cl); System.out.println("Associating "+ cl+ " to "+ecoreClass); //Not all, because then we would do something multiple times for (EAttribute eattr: cl.getEAttributes()) { xmlToEcoreAttribute.put(eattr, generateShallowAttribute(cl, ecoreClass, eattr)); eattrs.add(eattr); } for (EReference eattr: cl.getEReferences()) { xmlToEcoreReferences.put(eattr, generateShallowReference(cl, ecoreClass, eattr)); erefs.add(eattr); } ecorePackage.getEClassifiers().add(ecoreClass); } else { //Analyze subclass if (rootReferenceXml == null) { rootReferenceXml = TransformatorImpl.getRootFeature(cl); if (rootReferenceXml != null) { rootClassXml = rootReferenceXml.getEReferenceType(); documentRootClassXml = cl; } } } } else if (eobj instanceof EEnum) { // EEnum eenum = (EEnum)eobj; // TODO remove unused? EEnum targetEEnum = generateEEnum((EEnum)eobj); ecorePackage.getEClassifiers().add(targetEEnum); eenums.add(targetEEnum); //Ignore for now } else if (eobj instanceof EDataType) { //??? } else if (eobj instanceof EAttribute) { //Have handled every important above? } else if (eobj instanceof EReference) { //Have handled every important above? } } rootClassEcore = xmlToEcoreClasses.get(rootClassXml); for (EClass key: eclasses) { if (!augmentEClass(key, xmlToEcoreClasses.get(key))) { //TODO: Das stimmt so nicht ... xmlToEcoreClasses.remove(key); } } for (EAttribute attr: eattrs) { if (!augmentAttribute(attr, xmlToEcoreAttribute.get(attr))) { xmlToEcoreAttribute.remove(attr); } } for (EReference key: erefs) { if (!augmentReference(key, xmlToEcoreReferences.get(key))) { xmlToEcoreReferences.remove(key); } } //Add OCL expressions for (EObject eobj: xmlResource) { parseExtendedMetadata(eobj); } if (addedAnyAnnotations) { EAnnotation annot = ecorePackage.getEAnnotation("http://www.eclipse.org/emf/2002/Ecore"); if (annot == null) { annot = EcoreFactory.eINSTANCE.createEAnnotation(); annot.setSource("http://www.eclipse.org/emf/2002/Ecore"); ecorePackage.getEAnnotations().add(annot); } annot.getDetails().put("invocationDelegates","http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot"); annot.getDetails().put("settingDelegates","http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot"); annot.getDetails().put("validationDelegates","http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot"); } buildChangers(); calcId(); augmentWithStandardDatatypes(); if (generateFile) { try { int ind = 0; for (Resource ecoreRes: ecoreResources) { ecoreRes.save(new FileOutputStream("testoutput"+(++ind)+".ecore"),null); } } catch (IOException e) { e.printStackTrace(); } } } public void parseXmlEcore(ResourceSet resourceSet, File xmlEcore) { Resource.Factory.Registry reg = resourceSet.getResourceFactoryRegistry(); reg.getExtensionToFactoryMap().put( "xmi", new XMIResourceFactoryImpl()); reg.getExtensionToFactoryMap().put( "ecore", new EcoreResourceFactoryImpl()); //Register ecore file final ExtendedMetaData extendedMetaData = new BasicExtendedMetaData(resourceSet.getPackageRegistry()); resourceSet.getLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA, extendedMetaData); Resource res = resourceSet.getResource(resourceSet.getURIConverter().normalize(URI.createFileURI(xmlEcore.getAbsolutePath())), true); this.xmlResource = ()->res.getAllContents(); parseXmlEcore(null,resourceSet, URI.createFileURI(xmlEcore.getAbsolutePath()+".simple.ecore"), xmlResource, true); } public void parseExtendedMetadata(EClass xml, EClass ecore) { } public String toFirstUpper(String str) { if (str.length() <= 1) { return str.toUpperCase(); } return Character.toUpperCase(str.charAt(0))+str.substring(1); } public void parseExtendedMetadata(EAttribute xmlAttr, EAttribute ecoreAttr, EClass xmlClass, EClass ecoreClass) { if (ecoreAttr == null) { System.err.println("No attribute matching for "+xmlAttr); return; } EDataType dataType = xmlAttr.getEAttributeType(); //Also parse that for (EAnnotation dataTypeAnnot: dataType.getEAnnotations()) { System.out.println("DataTypeAnnotation: "+dataTypeAnnot.getSource()); if ("http:///org/eclipse/emf/ecore/util/ExtendedMetaData".equals(dataTypeAnnot.getSource())) { String pattern = dataTypeAnnot.getDetails().get("pattern"); EAnnotation additonal = ecoreClass.getEAnnotation("http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot"); /* <eAnnotations source="http://www.eclipse.org/emf/2002/Ecore"> <details key="constraints" value="sameServics goodSpeed onlyOneImportant backupDifferent"/> </eAnnotations> <eAnnotations source="http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot"> <details key="sameServics" value="backup = null or backup.services->includesAll(services)"/> <details key="goodSpeed" value="designSpeed &lt;= server.speed->sum()"/> <details key="onlyOneImportant" value="services->select(s | s.type = ServiceType::IMPORTANT)->size() &lt;= 1"/> <details key="backupDifferent" value="backup &lt;> self"/> </eAnnotations>*/ boolean needAdd = false; boolean needAdd2 = false; String curConstraints = ""; if (additonal == null) { needAdd = true; additonal = EcoreFactory.eINSTANCE.createEAnnotation(); additonal.setSource("http://www.eclipse.org/emf/2002/Ecore/OCL/Pivot"); } EAnnotation general = ecoreClass.getEAnnotation("http://www.eclipse.org/emf/2002/Ecore"); if (general != null) { curConstraints = general.getDetails().get("constraints"); if (curConstraints == null) { curConstraints = ""; } } else { needAdd2 = true; general = EcoreFactory.eINSTANCE.createEAnnotation(); general.setSource("http://www.eclipse.org/emf/2002/Ecore"); } String prepend = "self."+ecoreAttr.getName()+(MyEcoreUtil.isMany(ecoreAttr)?"->forAll(x | x":""); String postpend = MyEcoreUtil.isMany(ecoreAttr)?")":""; if (pattern != null) { // 162 occurrences in eclass case study, but where do they all come from? there are only 84 occurrences of restrictions, which are not enumerations or length, and 143 in total EAnnotation typeAnnotation = ((EClass) xmlAttr.eContainer()).getEAnnotations().get(0); restrictedDatatypes.put(typeAnnotation.getDetails().get("name"), xmlAttr.getEAttributeType().getName()); String constraintName = "pattern"+toFirstUpper(ecoreAttr.getName()); String constraintValue = null; constraintValue = ".matches('"+StringEscapeUtils.unescapeXml(pattern).replace("%20"," ").replace("\\", "\\\\").replace("'", "\\\"")+"')"; String[] baseConstraintValues = pattern.split("\\ "); StringBuilder totalValue = new StringBuilder(); for (int bc = 0; bc < baseConstraintValues.length; ++bc) { if (bc > 0) { totalValue.append(" or "); } String spattern = baseConstraintValues[bc]; constraintValue = ".matches('"+StringEscapeUtils.unescapeXml(spattern).replace("%20"," ").replace("\\", "\\\\").replace("'", "\\\"")+"')"; String newValue = prepend+constraintValue+postpend; totalValue.append(newValue); } String totalString = totalValue.toString(); if (xmlAttr.getLowerBound() == 0 && !xmlAttr.isMany() && baseConstraintValues.length > 0) { totalString = "("+prepend+"=null) or "+totalString; } additonal.getDetails().put(constraintName, totalString); curConstraints = curConstraints+ " "+constraintName; } String minLength = dataTypeAnnot.getDetails().get("minLength"); if (minLength != null) { String constraintName = "minLength"+toFirstUpper(ecoreAttr.getName()); String constraintValue = ".size() >= "+minLength; String prefix = (!xmlAttr.isMany()&&xmlAttr.getLowerBound()==0)?("("+prepend + " = null) or " + prepend):prepend; additonal.getDetails().put(constraintName, prefix+constraintValue+postpend); curConstraints = curConstraints+ " "+constraintName; } String maxLength = dataTypeAnnot.getDetails().get("maxLength"); if (maxLength != null) { String constraintName = "maxLength"+toFirstUpper(ecoreAttr.getName()); String constraintValue = ".size() <= "+maxLength; String prefix = (!xmlAttr.isMany()&&xmlAttr.getLowerBound()==0)?("("+prepend + " = null) or " + prepend):prepend; additonal.getDetails().put(constraintName, prefix+constraintValue+postpend); curConstraints = curConstraints+ " "+constraintName; } general.getDetails().put("constraints", curConstraints.trim()); if (needAdd2 && !curConstraints.trim().isEmpty()) { ecoreClass.getEAnnotations().add(general); } if (needAdd && !additonal.getDetails().isEmpty()) { ecoreClass.getEAnnotations().add(additonal); addedAnyAnnotations = true; } } } } public void parseExtendedMetadata(EReference xmlAttr, EReference ecoreAttr, EClass xmlClass, EClass ecoreClass) { } public void parseExtendedMetadata(EEnum xmlEnum, EEnum ecoreEnum) { } public void parseExtendedMetadata(EObject eobj) { if (eobj instanceof EClass) { parseExtendedMetadata((EClass)eobj,(EClass)xmlToEcoreClasses.get(eobj)); } else if (eobj instanceof EStructuralFeature) { EStructuralFeature esf = (EStructuralFeature)eobj; EClass srcCl = esf.getEContainingClass(); EClass trgCl = xmlToEcoreClasses.get(srcCl); if (eobj instanceof EAttribute) { parseExtendedMetadata((EAttribute)eobj, (EAttribute)xmlToEcoreAttribute.get(eobj),srcCl,trgCl ); } else { parseExtendedMetadata((EReference)eobj, (EReference)xmlToEcoreReferences.get(eobj),srcCl,trgCl ); } } else if (eobj instanceof EEnum) { parseExtendedMetadata((EEnum)eobj,this.copiedEEnums.get(eobj)); } } public SingleObjectTransformator matchingObjectTransformation = new SingleObjectTransformator() { @Override public EObject convertToXml(EObject eobject, Transformator transformator) { return transformator.eobject2xml(eobject); } @Override public EObject convertToEcore(EObject xml, Transformator transformator) { return transformator.xml2Eobject(xml); } }; private void setSimple(EStructuralFeature xmlFeature, EStructuralFeature target) { target.setChangeable(true); target.setLowerBound(xmlFeature.getLowerBound()); target.setUpperBound(xmlFeature.getUpperBound()); target.setOrdered(xmlFeature.isOrdered()); target.setTransient(false); target.setUnique(xmlFeature.isUnique()); target.setVolatile(false); } public EEnum generateEEnum(EEnum from) { EEnum ret = copiedEEnums.get(from); if (ret != null) { return ret; } copiedEEnums.put(from, ret = EcoreFactory.eINSTANCE.createEEnum()); ret.setName(from.getName()); for (EEnumLiteral lit: from.getELiterals()) { EEnumLiteral target = copiedEEnumLiterals.get(lit); if (target == null) { copiedEEnumLiterals.put(lit, target = EcoreFactory.eINSTANCE.createEEnumLiteral()); backEEnumLiteral.put(target, lit); backEEnumLiteralStr.put(from.getName()+"."+lit.getLiteral(), lit); target.setLiteral(lit.getLiteral()); target.setName(lit.getName()); target.setValue(lit.getValue()); } ret.getELiterals().add(target); } return ret; } public ValueTransformator<Object, Object> eenumTransformator(EEnum forEEnum) { return new ValueTransformator<Object,Object>() { @Override public Object convertToEcore(Object xml) { System.err.println("Convert to ecore needs to be reworked: was enumliteral->enumliteral, but appearanly others can be there too"); Object ret = copiedEEnumLiterals.get(xml); if (ret == null && xml instanceof EEnumLiteral) { String fragment = ((EEnumLiteral)xml).eResource().getURIFragment((EEnumLiteral)xml); EObject eobj = fragmentToXmlObject.get(fragment); ret = copiedEEnumLiterals.get(eobj); } else { // ret = ret;//xml; //Try?? TODO remove no-effect statement? } return ret; } @Override public Object convertToXml(Object eobject) { Object ret = backEEnumLiteral.get(eobject); if (ret == null && eobject instanceof Enumerator) { Enumerator enumerator = (Enumerator)eobject; String totalStr = forEEnum.getName()+"."+enumerator.getLiteral(); ret = backEEnumLiteralStr.get(totalStr); } return ret; } }; } public boolean augmentAttributeBasic(EAttribute xmlAttribute, EAttribute ecoreAttribute) { EClass contCl = xmlToEcoreClasses.get(xmlAttribute.getEContainingClass()); if (contCl == null) { System.err.println("No matching source found for "+xmlAttribute); return false; } if (xmlAttribute.getEAttributeType() instanceof EEnum) { //Directly reuse that enum (is this supported in the grammar?) EEnum targetEEnum = copiedEEnums.get(xmlAttribute.getEAttributeType()); if (targetEEnum == null) { System.err.println("I have not copied the eenum "+xmlAttribute.getEAttributeType()); return false; } else { EAttributeTransformatorImpl tfi = new EAttributeTransformatorImpl(xmlAttribute, ecoreAttribute, new CollectionValueTransformationImpl(EEnumLiteral.class, EEnumLiteral.class, eenumTransformator(targetEEnum))); xmlToEcoreAttr.put(xmlAttribute, tfi); ecoreToXmlAttr.put(ecoreAttribute, tfi); return true; } } CollectionValueTransformation trafo = store.getValueTransformationOrNull(xmlAttribute); if (trafo == null) { Boolean ret = checkMixedAttribute(contCl,xmlAttribute); if (ret != null) { return ret; } System.err.println("No transformation found for "+xmlAttribute); return false; } EAttributeTransformatorImpl tfi = new EAttributeTransformatorImpl(xmlAttribute, ecoreAttribute, trafo); xmlToEcoreAttr.put(xmlAttribute, tfi); ecoreToXmlAttr.put(ecoreAttribute, tfi); return true; } //There is no need to be a 1:1 correspondance! public EStructuralFeature getXmlFeature(EStructuralFeature ecoreFeature) { //Check id if (java.util.Objects.equals(ecoreFeature,commonIdAttribute)) { ecoreFeature = realId.getOrDefault(ecoreFeature,(EAttribute)ecoreFeature); } //Check reference - not necessary, I added it to ecoreToXmlFeature! return ecoreToXmlFeature.get(ecoreFeature); } public Object getXmlValue(EObject eobj, EStructuralFeature ecoreFeature, int index) { Collection col = MyEcoreUtil.getAsCollection(eobj, getXmlFeature(ecoreFeature)); if (col instanceof List) { return ((List)col).get(index); } else { Object ret = null; Iterator iter = col.iterator(); while (index >= 0) { if (iter.hasNext()) { ret = iter.next(); } else { if (ecoreFeature instanceof EAttribute) { EDataType dt = ((EAttribute)ecoreFeature).getEAttributeType(); ret = dt.getDefaultValue(); } else { EReference ref = (EReference)ecoreFeature; ret = MyEcoreUtil.createInstanceStatic(ref.getEReferenceType()); } } --index; } return ret; } } public Boolean checkMixedAttribute(EClass contCl, EAttribute xmlAttribute) { EDataType dt = xmlAttribute.getEAttributeType(); if (dt != null && "EFeatureMapEntry".equals(dt.getName()) && "mixed".equals(xmlAttribute.getName())) { generateMixClasses(); contCl.getESuperTypes().add(mixedBaseClass); PartialObjectCopier poc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl transformator, EObject from, EObject to) { //This must NOT refer to ecoreAttribute!! //TODO: Store in a map or something like that ... //Because there is only one target attribute EStructuralFeature ecoreAttribute = from.eClass().getEStructuralFeature("mixed"); Collection c = MyEcoreUtil.getAsCollection(from, ecoreAttribute); Collection t = MyEcoreUtil.getAsCollection(to, mixedBaseMixedAttr); t.clear(); for (Object o: c) { FeatureMap.Entry entry = (FeatureMap.Entry)o; EStructuralFeature esf = entry.getEStructuralFeature(); if (esf.getEContainingClass().isSuperTypeOf(from.eClass())) { //It is a class attribute EObject feature = MyEcoreUtil.createInstanceStatic(mixedFeature); feature.eSet(mixedValueAttr, getTargetName(esf)); t.add(feature); } else if ("text".equals(esf.getName())) { //TODO: Improve filtering //It is a string literal EObject feature = MyEcoreUtil.createInstanceStatic(mixedText); feature.eSet(mixedValueAttr, entry.getValue()); t.add(feature); } else { //TODO: Implement me throw new RuntimeException(new UnsupportedDataTypeException("I currently only support text features and owned structural features in mixed content")); } } } }; //1. Add Object-Delta of this object (!) - this is automatically done by other methods //2. Add Feature-Map-Delta of this object, so this POC has to be executed last //Ist ok, da das Attribut bekannt ist, kann man es ja im transformer sp�ter ausf�hren, muss nur //das letzte pro objekt sein! xmlToEcoreChanger.put(xmlAttribute, poc); xmlToEcoreChanger.put(mixedBaseMixedAttr, poc); PartialObjectCopier ecoreToXmlPoc = new PartialObjectCopier() { @Override public void copyFrom(TransformatorImpl transformator, EObject ecore, EObject xml) { //This must NOT use any of this attributes since it must be generic! Collection c = MyEcoreUtil.getAsCollection(ecore, mixedBaseMixedAttr); EStructuralFeature xmlFeature = xml.eClass().getEStructuralFeature("mixed"); List t = new ArrayList<>(); //TODO: Ber�cksichtige gleich, wenn das target eine Sequence ist ... Map<EStructuralFeature,Integer> usedIndices = new HashMap<EStructuralFeature, Integer>(); for (Object o: c) { EObject eo = (EObject)o; if (mixedFeature.isSuperTypeOf(eo.eClass())) { EStructuralFeature ecorefeat = ecore.eClass().getEStructuralFeature((String)eo.eGet(mixedValueAttr)); //Jetzt brauche ich aber den korrespondierenden Wert (und das korrespondierende Feature) //Wenn es eine Referenz ist, ist das vielleicht nicht gespeichert EStructuralFeature xmlFeat = getXmlFeature(ecorefeat); Integer index = usedIndices.getOrDefault(xmlFeat, 0); Object value = getXmlValue(xml, ecorefeat, index); FeatureMap.Entry entry = FeatureMapUtil.createEntry(xmlFeat, value); usedIndices.put(xmlFeat, index+1); t.add(entry); } else if (mixedText.isSuperTypeOf(eo.eClass())) { FeatureMap.Entry entry = FeatureMapUtil.createTextEntry((String)eo.eGet(mixedValueAttr)); t.add(entry); } } //Add remaining features for (EStructuralFeature esf: xml.eClass().getEAllStructuralFeatures()) { if (isMixed(esf)) {continue;} Integer curIndex = usedIndices.getOrDefault(esf, 0); Collection col = MyEcoreUtil.getAsCollection(xml, esf); Iterator iter = col.iterator(); int lind = 0; while (iter.hasNext() && lind < curIndex) { iter.next(); } while(iter.hasNext()) { FeatureMap.Entry entry = FeatureMapUtil.createEntry(esf, iter.next()); t.add(entry); } } MyEcoreUtil.setAsCollectionBasic(xml, xmlFeature, t); } }; ecoreToXmlChanger.put(xmlAttribute, ecoreToXmlPoc); ecoreToXmlChanger.put(mixedBaseMixedAttr, ecoreToXmlPoc); return false; //Remove this attribute because it is replaced! } return null; } public boolean augmentAttribute(EAttribute xmlAttribute, EAttribute ecoreAttribute) { if (handledTargets.contains(ecoreAttribute)) { return augmentAttributeBasic(xmlAttribute, ecoreAttribute); } EClass contCl = xmlToEcoreClasses.get(xmlAttribute.getEContainingClass()); if (xmlAttribute.getName().contains("pages")) { System.out.println("Pages found!"); } if (contCl == null) { System.err.println("No matching source found for "+xmlAttribute); return false; } if (xmlAttribute.getEAttributeType() instanceof EEnum) { //Directly reuse that enum (is this supported in the grammar?) EEnum targetEEnum = copiedEEnums.get(xmlAttribute.getEAttributeType()); if (targetEEnum == null) { System.err.println("I have not copied the eenum "+xmlAttribute.getEAttributeType()); return false; } else { ecoreAttribute.setEType(targetEEnum); contCl.getEStructuralFeatures().add(ecoreAttribute); EAttributeTransformatorImpl tfi = new EAttributeTransformatorImpl(xmlAttribute, ecoreAttribute, new CollectionValueTransformationImpl(EEnumLiteral.class, EEnumLiteral.class, eenumTransformator(targetEEnum))); xmlToEcoreAttr.put(xmlAttribute, tfi); ecoreToXmlAttr.put(ecoreAttribute, tfi); // EObject eobj; // TODO remove unused? return true; } } CollectionValueTransformation trafo = store.getValueTransformationOrNull(xmlAttribute); if (trafo == null) { //Check special case: mixed + EFeatureMapEntry Boolean ret = checkMixedAttribute(contCl,xmlAttribute); if (ret != null) { return ret; } System.err.println("Cannot translate attribute "+xmlAttribute.getEContainingClass().getName()+"."+xmlAttribute.getName()+" of type "+xmlAttribute.getEAttributeType()+" (cannot find transformator)"); return false; } EDataType dt = store.getStandardDatatypeOrNull(trafo.getEcoreClass()); if (dt == null) { System.err.println("Cannot translate attribute "+xmlAttribute.getEContainingClass().getName()+"."+xmlAttribute.getName()+" of type "+xmlAttribute.getEAttributeType()+" (cannot transform datatype)"); return false; } EAttributeTransformatorImpl tfi = new EAttributeTransformatorImpl(xmlAttribute, ecoreAttribute, trafo); xmlToEcoreAttr.put(xmlAttribute, tfi); ecoreToXmlAttr.put(ecoreAttribute, tfi); ecoreAttribute.setEType(dt); contCl.getEStructuralFeatures().add(ecoreAttribute); return true; } public boolean augmentReferenceBasic(EReference xmlReference, EReference ecoreReference) { EClass contCl = xmlToEcoreClasses.get(xmlReference.getEContainingClass()); if (contCl == null) { System.err.println("No matching source found for "+xmlReference); return false; } EClass targetClass = xmlToEcoreClasses.get(xmlReference.getEReferenceType()); if (targetClass == null) { System.err.println("No matching type found for "+xmlReference.getEContainingClass().getName()+"."+xmlReference.getName()+" ("+xmlReference.getEReferenceType()+")"); return false; } EReferenceTransformatorImpl tfi = new EReferenceTransformatorImpl(xmlReference, ecoreReference, new SingleBasedCollectionObjectTransformation(new InformatedSingleObjectTransformation(xmlReference.getEReferenceType(), ecoreReference.getEReferenceType(), matchingObjectTransformation))); xmlToEcoreRef.put(xmlReference, tfi); ecoreToXmlRef.put(ecoreReference, tfi); //contCl.getEStructuralFeatures().add(ecoreReference); return true; } public boolean augmentReference(EReference xmlReference, EReference ecoreReference) { if (handledTargets.contains(ecoreReference)) { return augmentReferenceBasic(xmlReference, ecoreReference); } EClass contCl = xmlToEcoreClasses.get(xmlReference.getEContainingClass()); if (contCl == null) { System.err.println("No matching source found for "+xmlReference); return false; } EClass targetClass = xmlToEcoreClasses.get(xmlReference.getEReferenceType()); if (targetClass == null) { System.err.println("No matching type found for "+xmlReference.getEContainingClass().getName()+"."+xmlReference.getName()+" ("+xmlReference.getEReferenceType()+")"); return false; } ecoreReference.setEType(targetClass); EReferenceTransformatorImpl tfi = new EReferenceTransformatorImpl(xmlReference, ecoreReference, new SingleBasedCollectionObjectTransformation(new InformatedSingleObjectTransformation(xmlReference.getEReferenceType(), ecoreReference.getEReferenceType(), matchingObjectTransformation))); xmlToEcoreRef.put(xmlReference, tfi); ecoreToXmlRef.put(ecoreReference, tfi); contCl.getEStructuralFeatures().add(ecoreReference); return true; } public boolean augmentEClass(EClass xmlClass, EClass ecoreClass) { if (handledTargets.contains(ecoreClass)) { return augmentEClassBasic(xmlClass, ecoreClass); } for (EClass superType: xmlClass.getESuperTypes()) { EClass ecoreSup = xmlToEcoreClasses.get(superType); ecoreClass.getESuperTypes().add(ecoreSup); } //Ich glaube sonst ist nichts zu tun? return true; } public boolean augmentEClassBasic(EClass xmlClass, EClass ecoreReference) { return true; } public String getTargetName(EStructuralFeature xmlFeature){ String targetName = xmlFeature.getName(); if (xmlFeature.isMany() && !targetName.endsWith("s")) { targetName = targetName+"s"; } return targetName; } public String getEcoreAttributeName(EStructuralFeature xmlFeature) { return getTargetName(xmlFeature); } public EAttribute generateShallowAttribute(EClass xmlClass, EClass ecoreClass, EAttribute xmlAttribute) { String featName = getTargetName(xmlAttribute); Object existing = getIfExists(ecoreClass.getName()+"."+featName); EAttribute target = (existing instanceof EAttribute)?((EAttribute)existing):null; if (target == null) { target = EcoreFactory.eINSTANCE.createEAttribute(); target.setName(featName); setSimple(xmlAttribute, target); target.setID(xmlAttribute.isID()); } ecoreToXmlFeature.put(target, xmlAttribute); return target; } public void fixOpposites() { //Don't fix it since it can't be handled by XText! } public EReference generateShallowReference(EClass xmlClass, EClass ecoreClass, EReference xmlReference) { String featName = getTargetName(xmlReference); EReference target = (EReference)getIfExists(ecoreClass.getName()+"."+featName); if (target == null) { target = EcoreFactory.eINSTANCE.createEReference(); target.setName(featName); setSimple(xmlReference, target); target.setContainment(xmlReference.isContainment()); } ecoreToXmlFeature.put(target, xmlReference); return target; } public String getEcoreClassName(EClass xmlClass) { String targetName = xmlClass.getName(); if (targetName.endsWith("Type")) { //targetName = targetName.substring(0,targetName.length()-"Type".length()); } return targetName; } public EClass generateShallowEClass(EClass xmlClass) { String targetName = getEcoreClassName(xmlClass); EClass target = (EClass)getIfExists(targetName); if (target == null) { target = EcoreFactory.eINSTANCE.createEClass(); target.setName(targetName); } return target; } // TODO move this to a test class public static void main(String[] args) { TypeTransformatorStore store = new TypeTransformatorStore(); ResourceSet basicSet = new ResourceSetImpl(); TransformatorStructure structure = new TransformatorStructure(store, basicSet, new File("library3-base.ecore")); } public EObject getXmlEObject(String uriFragment) { return fragmentToXmlObject.get(uriFragment); } public EClass getDocumentRoot() { return documentRootClassXml; } public EClass getXmlRoot() { return rootClassXml; } public EReference getXmlRootReference() { return rootReferenceXml; } public EClass getEcoreRoot() { return rootClassEcore; } public List<Resource> getEcoreResources() { return ecoreResources; } }
mit
krystiankaluzny/springboot-javafx-support
src/test/java/de/felixroske/jfxsupport/util/InactiveSpringBootAppExcludeFilter.java
812
package de.felixroske.jfxsupport.util; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import java.io.IOException; /** * Created by Krystian Kałużny on 03.07.2017. */ class InactiveSpringBootAppExcludeFilter extends ExcludeFilter { @Override public boolean exclude(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { try { if (isAnnotated(metadataReader, SpringBootApplication.class)) { return !activeSpringBootClass.getName().equals(metadataReader.getClassMetadata().getClassName()); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } return false; } }
mit
liwangadd/Coding
app/src/main/java/com/nicolas/coding/common/photopick/GridPhotoAdapter.java
3262
package com.nicolas.coding.common.photopick; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CursorAdapter; import android.widget.ImageView; import com.nostra13.universalimageloader.core.ImageLoader; import com.nicolas.coding.MyApp; import com.nicolas.coding.R; import com.nicolas.coding.common.photopick.PhotoPickActivity.GridViewCheckTag; /** * Created by chenchao on 15/5/6. */ class GridPhotoAdapter extends CursorAdapter { final int itemWidth; LayoutInflater mInflater; PhotoPickActivity mActivity; // // enum Mode { All, Folder } // private Mode mMode = Mode.All; // // void setmMode(Mode mMode) { // this.mMode = mMode; // } View.OnClickListener mClickItem = new View.OnClickListener() { @Override public void onClick(View v) { mActivity.clickPhotoItem(v); } }; GridPhotoAdapter(Context context, Cursor c, boolean autoRequery, PhotoPickActivity activity) { super(context, c, autoRequery); mInflater = LayoutInflater.from(context); mActivity = activity; int spacePix = context.getResources().getDimensionPixelSize(R.dimen.pickimage_gridlist_item_space); itemWidth = (MyApp.sWidthPix - spacePix * 4) / 3; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View convertView = mInflater.inflate(R.layout.photopick_gridlist_item, parent, false); ViewGroup.LayoutParams layoutParams = convertView.getLayoutParams(); layoutParams.height = itemWidth; layoutParams.width = itemWidth; convertView.setLayoutParams(layoutParams); GridViewHolder holder = new GridViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.icon); holder.iconFore = (ImageView) convertView.findViewById(R.id.iconFore); holder.check = (CheckBox) convertView.findViewById(R.id.check); GridViewCheckTag checkTag = new GridViewCheckTag(holder.iconFore); holder.check.setTag(checkTag); holder.check.setOnClickListener(mClickItem); convertView.setTag(holder); ViewGroup.LayoutParams iconParam = holder.icon.getLayoutParams(); iconParam.width = itemWidth; iconParam.height = itemWidth; holder.icon.setLayoutParams(iconParam); return convertView; } @Override public void bindView(View view, Context context, Cursor cursor) { GridViewHolder holder; holder = (GridViewHolder) view.getTag(); ImageLoader imageLoader = ImageLoader.getInstance(); String path = ImageInfo.pathAddPreFix(cursor.getString(1)); imageLoader.displayImage(path, holder.icon, PhotoPickActivity.optionsImage); ((GridViewCheckTag) holder.check.getTag()).path = path; boolean picked = mActivity.isPicked(path); holder.check.setChecked(picked); holder.iconFore.setVisibility(picked ? View.VISIBLE : View.INVISIBLE); } static class GridViewHolder { ImageView icon; ImageView iconFore; CheckBox check; } }
mit
eity0323/aimanager
app/src/main/java/com/sien/aimanager/MainApp.java
1651
package com.sien.aimanager; import android.content.Intent; import android.os.Handler; import com.sien.aimanager.services.MonitorServices; import com.sien.lib.baseapp.BaseApplication; import com.sien.lib.databmob.config.DatappConfig; import cn.bmob.v3.Bmob; import cn.bmob.v3.BmobConfig; /** * @author sien * @date 2017/2/5 * @descript */ public class MainApp extends BaseApplication { @Override public void onCreate() { super.onCreate(); //启动监听服务 并 延时触发创建检测机制 startMonitorServiceAndDelayInitialCheckMechanism(); initBmobConfig(); } private void initBmobConfig(){ BmobConfig config =new BmobConfig.Builder(this) //设置appkey .setApplicationId(DatappConfig.BMOB_APPID) //请求超时时间(单位为秒):默认15s .setConnectTimeout(30) //文件分片上传时每片的大小(单位字节),默认512*1024 .setUploadBlockSize(1024*1024) //文件的过期时间(单位为秒):默认1800s .setFileExpiration(2500) .build(); Bmob.initialize(config); } /** * 触发创建检测机制 */ private void startMonitorServiceAndDelayInitialCheckMechanism(){ //启动监听定时创建检查机制(可放到监听服务启动时触发) Handler tempHandler = new Handler(); tempHandler.postDelayed(new Runnable() { @Override public void run() { startService(new Intent(MainApp.this, MonitorServices.class)); } },200); } }
mit
devnull-tools/boteco
main/boteco/src/test/java/tools/devnull/boteco/predicates/TargetPredicateTest.java
2605
/* * The MIT License * * Copyright (c) 2016 Marcelo "Ataxexe" Guimarães <ataxexe@devnull.tools> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package tools.devnull.boteco.predicates; import org.junit.Before; import org.junit.Test; import tools.devnull.boteco.message.IncomeMessage; import tools.devnull.boteco.Predicates; import tools.devnull.kodo.Spec; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static tools.devnull.boteco.TestHelper.accept; import static tools.devnull.boteco.TestHelper.notAccept; import static tools.devnull.kodo.Expectation.it; import static tools.devnull.kodo.Expectation.to; public class TargetPredicateTest { private IncomeMessage messageFromTarget; private IncomeMessage messageFromOtherTarget; private IncomeMessage messageFromUnknownTarget; @Before public void initialize() { messageFromTarget = mock(IncomeMessage.class); when(messageFromTarget.target()).thenReturn("target"); messageFromOtherTarget = mock(IncomeMessage.class); when(messageFromOtherTarget.target()).thenReturn("other-target"); messageFromUnknownTarget = mock(IncomeMessage.class); when(messageFromUnknownTarget.target()).thenReturn("unknown-target"); } @Test public void test() { Spec.given(Predicates.target("target")) .expect(it(), to(accept(messageFromTarget))) .expect(it(), to(notAccept(messageFromOtherTarget))) .expect(it(), to(notAccept(messageFromUnknownTarget))); } }
mit
rrajath/Orange
app/src/main/java/com/rrajath/orange/MainActivity.java
1118
package com.rrajath.orange; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
mit
zezutom/schematic
src/test/java/org/zezutom/schematic/model/json/StringNodeTest.java
521
package org.zezutom.schematic.model.json; import org.zezutom.schematic.service.generator.json.StringGenerator; public class StringNodeTest extends NodeTestCase<String, StringGenerator, StringNode> { @Override StringNode newInstance(String name, StringGenerator generator) { return new StringNode(name, generator); } @Override Class<StringGenerator> getGeneratorClass() { return StringGenerator.class; } @Override String getTestValue() { return "test"; } }
mit
mustafaneguib/tag-augmented-reality-android
gen/com/google/android/gms/R.java
13382
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms; public final class R { public static final class attr { public static final int adSize = 0x7f01006a; public static final int adSizes = 0x7f01006b; public static final int adUnitId = 0x7f01006c; public static final int buyButtonAppearance = 0x7f010082; public static final int buyButtonHeight = 0x7f01007f; public static final int buyButtonText = 0x7f010081; public static final int buyButtonWidth = 0x7f010080; public static final int cameraBearing = 0x7f01006e; public static final int cameraTargetLat = 0x7f01006f; public static final int cameraTargetLng = 0x7f010070; public static final int cameraTilt = 0x7f010071; public static final int cameraZoom = 0x7f010072; public static final int environment = 0x7f01007c; public static final int fragmentMode = 0x7f01007e; public static final int fragmentStyle = 0x7f01007d; public static final int mapType = 0x7f01006d; public static final int maskedWalletDetailsBackground = 0x7f010085; public static final int maskedWalletDetailsButtonBackground = 0x7f010087; public static final int maskedWalletDetailsButtonTextAppearance = 0x7f010086; public static final int maskedWalletDetailsHeaderTextAppearance = 0x7f010084; public static final int maskedWalletDetailsLogoImageType = 0x7f010089; public static final int maskedWalletDetailsLogoTextColor = 0x7f010088; public static final int maskedWalletDetailsTextAppearance = 0x7f010083; public static final int theme = 0x7f01007b; public static final int uiCompass = 0x7f010073; public static final int uiRotateGestures = 0x7f010074; public static final int uiScrollGestures = 0x7f010075; public static final int uiTiltGestures = 0x7f010076; public static final int uiZoomControls = 0x7f010077; public static final int uiZoomGestures = 0x7f010078; public static final int useViewLifecycle = 0x7f010079; public static final int zOrderOnTop = 0x7f01007a; } public static final class color { public static final int common_action_bar_splitter = 0x7f07000c; public static final int common_signin_btn_dark_text_default = 0x7f070003; public static final int common_signin_btn_dark_text_disabled = 0x7f070005; public static final int common_signin_btn_dark_text_focused = 0x7f070006; public static final int common_signin_btn_dark_text_pressed = 0x7f070004; public static final int common_signin_btn_default_background = 0x7f07000b; public static final int common_signin_btn_light_text_default = 0x7f070007; public static final int common_signin_btn_light_text_disabled = 0x7f070009; public static final int common_signin_btn_light_text_focused = 0x7f07000a; public static final int common_signin_btn_light_text_pressed = 0x7f070008; public static final int common_signin_btn_text_dark = 0x7f070020; public static final int common_signin_btn_text_light = 0x7f070021; public static final int wallet_bright_foreground_disabled_holo_light = 0x7f070012; public static final int wallet_bright_foreground_holo_dark = 0x7f07000d; public static final int wallet_bright_foreground_holo_light = 0x7f070013; public static final int wallet_dim_foreground_disabled_holo_dark = 0x7f07000f; public static final int wallet_dim_foreground_holo_dark = 0x7f07000e; public static final int wallet_dim_foreground_inverse_disabled_holo_dark = 0x7f070011; public static final int wallet_dim_foreground_inverse_holo_dark = 0x7f070010; public static final int wallet_highlighted_text_holo_dark = 0x7f070017; public static final int wallet_highlighted_text_holo_light = 0x7f070016; public static final int wallet_hint_foreground_holo_dark = 0x7f070015; public static final int wallet_hint_foreground_holo_light = 0x7f070014; public static final int wallet_holo_blue_light = 0x7f070018; public static final int wallet_link_text_light = 0x7f070019; public static final int wallet_primary_text_holo_light = 0x7f070022; public static final int wallet_secondary_text_holo_dark = 0x7f070023; } public static final class drawable { public static final int common_signin_btn_icon_dark = 0x7f02006c; public static final int common_signin_btn_icon_disabled_dark = 0x7f02006d; public static final int common_signin_btn_icon_disabled_focus_dark = 0x7f02006e; public static final int common_signin_btn_icon_disabled_focus_light = 0x7f02006f; public static final int common_signin_btn_icon_disabled_light = 0x7f020070; public static final int common_signin_btn_icon_focus_dark = 0x7f020071; public static final int common_signin_btn_icon_focus_light = 0x7f020072; public static final int common_signin_btn_icon_light = 0x7f020073; public static final int common_signin_btn_icon_normal_dark = 0x7f020074; public static final int common_signin_btn_icon_normal_light = 0x7f020075; public static final int common_signin_btn_icon_pressed_dark = 0x7f020076; public static final int common_signin_btn_icon_pressed_light = 0x7f020077; public static final int common_signin_btn_text_dark = 0x7f020078; public static final int common_signin_btn_text_disabled_dark = 0x7f020079; public static final int common_signin_btn_text_disabled_focus_dark = 0x7f02007a; public static final int common_signin_btn_text_disabled_focus_light = 0x7f02007b; public static final int common_signin_btn_text_disabled_light = 0x7f02007c; public static final int common_signin_btn_text_focus_dark = 0x7f02007d; public static final int common_signin_btn_text_focus_light = 0x7f02007e; public static final int common_signin_btn_text_light = 0x7f02007f; public static final int common_signin_btn_text_normal_dark = 0x7f020080; public static final int common_signin_btn_text_normal_light = 0x7f020081; public static final int common_signin_btn_text_pressed_dark = 0x7f020082; public static final int common_signin_btn_text_pressed_light = 0x7f020083; public static final int ic_plusone_medium_off_client = 0x7f02008d; public static final int ic_plusone_small_off_client = 0x7f02008e; public static final int ic_plusone_standard_off_client = 0x7f02008f; public static final int ic_plusone_tall_off_client = 0x7f020090; public static final int powered_by_google_dark = 0x7f02009f; public static final int powered_by_google_light = 0x7f0200a0; } public static final class id { public static final int book_now = 0x7f050026; public static final int buyButton = 0x7f050020; public static final int buy_now = 0x7f050025; public static final int buy_with_google = 0x7f050024; public static final int classic = 0x7f050027; public static final int grayscale = 0x7f050028; public static final int holo_dark = 0x7f05001b; public static final int holo_light = 0x7f05001c; public static final int hybrid = 0x7f05001a; public static final int match_parent = 0x7f050022; public static final int monochrome = 0x7f050029; public static final int none = 0x7f050010; public static final int normal = 0x7f050000; public static final int production = 0x7f05001d; public static final int sandbox = 0x7f05001e; public static final int satellite = 0x7f050018; public static final int selectionDetails = 0x7f050021; public static final int strict_sandbox = 0x7f05001f; public static final int terrain = 0x7f050019; public static final int wrap_content = 0x7f050023; } public static final class integer { public static final int google_play_services_version = 0x7f090001; } public static final class string { public static final int auth_client_needs_enabling_title = 0x7f0a000e; public static final int auth_client_needs_installation_title = 0x7f0a000f; public static final int auth_client_needs_update_title = 0x7f0a0010; public static final int auth_client_play_services_err_notification_msg = 0x7f0a0011; public static final int auth_client_requested_by_msg = 0x7f0a0012; public static final int auth_client_using_bad_version_title = 0x7f0a000d; public static final int common_google_play_services_enable_button = 0x7f0a001e; public static final int common_google_play_services_enable_text = 0x7f0a001d; public static final int common_google_play_services_enable_title = 0x7f0a001c; public static final int common_google_play_services_error_notification_requested_by_msg = 0x7f0a0017; public static final int common_google_play_services_install_button = 0x7f0a001b; public static final int common_google_play_services_install_text_phone = 0x7f0a0019; public static final int common_google_play_services_install_text_tablet = 0x7f0a001a; public static final int common_google_play_services_install_title = 0x7f0a0018; public static final int common_google_play_services_invalid_account_text = 0x7f0a0024; public static final int common_google_play_services_invalid_account_title = 0x7f0a0023; public static final int common_google_play_services_needs_enabling_title = 0x7f0a0016; public static final int common_google_play_services_network_error_text = 0x7f0a0022; public static final int common_google_play_services_network_error_title = 0x7f0a0021; public static final int common_google_play_services_notification_needs_installation_title = 0x7f0a0014; public static final int common_google_play_services_notification_needs_update_title = 0x7f0a0015; public static final int common_google_play_services_notification_ticker = 0x7f0a0013; public static final int common_google_play_services_unknown_issue = 0x7f0a0025; public static final int common_google_play_services_unsupported_date_text = 0x7f0a0028; public static final int common_google_play_services_unsupported_text = 0x7f0a0027; public static final int common_google_play_services_unsupported_title = 0x7f0a0026; public static final int common_google_play_services_update_button = 0x7f0a0029; public static final int common_google_play_services_update_text = 0x7f0a0020; public static final int common_google_play_services_update_title = 0x7f0a001f; public static final int common_signin_button_text = 0x7f0a002a; public static final int common_signin_button_text_long = 0x7f0a002b; public static final int wallet_buy_button_place_holder = 0x7f0a002c; } public static final class style { public static final int Theme_IAPTheme = 0x7f0b007f; public static final int WalletFragmentDefaultButtonTextAppearance = 0x7f0b0082; public static final int WalletFragmentDefaultDetailsHeaderTextAppearance = 0x7f0b0081; public static final int WalletFragmentDefaultDetailsTextAppearance = 0x7f0b0080; public static final int WalletFragmentDefaultStyle = 0x7f0b0083; } public static final class styleable { public static final int[] AdsAttrs = { 0x7f01006a, 0x7f01006b, 0x7f01006c }; public static final int AdsAttrs_adSize = 0; public static final int AdsAttrs_adSizes = 1; public static final int AdsAttrs_adUnitId = 2; public static final int[] MapAttrs = { 0x7f01006d, 0x7f01006e, 0x7f01006f, 0x7f010070, 0x7f010071, 0x7f010072, 0x7f010073, 0x7f010074, 0x7f010075, 0x7f010076, 0x7f010077, 0x7f010078, 0x7f010079, 0x7f01007a }; public static final int MapAttrs_cameraBearing = 1; public static final int MapAttrs_cameraTargetLat = 2; public static final int MapAttrs_cameraTargetLng = 3; public static final int MapAttrs_cameraTilt = 4; public static final int MapAttrs_cameraZoom = 5; public static final int MapAttrs_mapType = 0; public static final int MapAttrs_uiCompass = 6; public static final int MapAttrs_uiRotateGestures = 7; public static final int MapAttrs_uiScrollGestures = 8; public static final int MapAttrs_uiTiltGestures = 9; public static final int MapAttrs_uiZoomControls = 10; public static final int MapAttrs_uiZoomGestures = 11; public static final int MapAttrs_useViewLifecycle = 12; public static final int MapAttrs_zOrderOnTop = 13; public static final int[] WalletFragmentOptions = { 0x7f01007b, 0x7f01007c, 0x7f01007d, 0x7f01007e }; public static final int WalletFragmentOptions_environment = 1; public static final int WalletFragmentOptions_fragmentMode = 3; public static final int WalletFragmentOptions_fragmentStyle = 2; public static final int WalletFragmentOptions_theme = 0; public static final int[] WalletFragmentStyle = { 0x7f01007f, 0x7f010080, 0x7f010081, 0x7f010082, 0x7f010083, 0x7f010084, 0x7f010085, 0x7f010086, 0x7f010087, 0x7f010088, 0x7f010089 }; public static final int WalletFragmentStyle_buyButtonAppearance = 3; public static final int WalletFragmentStyle_buyButtonHeight = 0; public static final int WalletFragmentStyle_buyButtonText = 2; public static final int WalletFragmentStyle_buyButtonWidth = 1; public static final int WalletFragmentStyle_maskedWalletDetailsBackground = 6; public static final int WalletFragmentStyle_maskedWalletDetailsButtonBackground = 8; public static final int WalletFragmentStyle_maskedWalletDetailsButtonTextAppearance = 7; public static final int WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance = 5; public static final int WalletFragmentStyle_maskedWalletDetailsLogoImageType = 10; public static final int WalletFragmentStyle_maskedWalletDetailsLogoTextColor = 9; public static final int WalletFragmentStyle_maskedWalletDetailsTextAppearance = 4; } }
mit
sim642/shy
app/src/main/java/ee/shy/cli/HelptextBuilder.java
2440
package ee.shy.cli; import ee.shy.Builder; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Class for building help text with preset format */ public class HelptextBuilder implements Builder<String> { /** * Data structure that contains command's argument and its corresponding description. */ private final Map<String, String> commandWithArgs = new LinkedHashMap<>(); /** * List that provides information about executing the command without arguments. */ private final List<String> commandWithoutArgs = new ArrayList<>(); /** * List containing additional information about the command. */ private final List<String> descriptions = new ArrayList<>(); public HelptextBuilder addWithArgs(String command, String description) { commandWithArgs.put(command, description); return this; } public HelptextBuilder addWithoutArgs(String description) { commandWithoutArgs.add(description); return this; } public HelptextBuilder addDescription(String description) { descriptions.add(description); return this; } /** * Create a StringBuilder object to create a formatted help text. * * @return formatted help text */ @Override public String create() { StringBuilder helptext = new StringBuilder(); if (!commandWithArgs.isEmpty()) { helptext.append("Usage with arguments:\n"); for (Map.Entry<String, String> entry : commandWithArgs.entrySet()) { helptext.append("\t").append(entry.getKey()).append("\n"); helptext.append("\t\t- ").append(entry.getValue()).append("\n"); } helptext.append("\n"); } if (!commandWithoutArgs.isEmpty()) { helptext.append("Usage without arguments:\n"); for (String commandWithoutArg : commandWithoutArgs) { helptext.append("\t").append(commandWithoutArg).append("\n"); } helptext.append("\n"); } if (!descriptions.isEmpty()) { helptext.append("Description:\n"); for (String description : descriptions) { helptext.append("\t").append(description).append("\n"); } helptext.append("\n"); } return helptext.toString(); } }
mit
asciiCerebrum/neocortexEngine
src/main/java/org/asciicerebrum/neocortexengine/domain/events/EventType.java
1310
package org.asciicerebrum.neocortexengine.domain.events; /** * * @author species8472 */ public enum EventType { /** * Event thrown directly after the initialization of a new combat round. */ COMBATROUND_POSTINIT, /** * Event thrown before the initialization of a new combat round. */ COMBATROUND_PREINIT, /** * The event of gaining a new condition. */ CONDITION_GAIN, /** * The event of losing a condition. */ CONDITION_LOSE, /** * The event of applying the inflicted damage. */ DAMAGE_APPLICATION, /** * The event of inflicting damage. */ DAMAGE_INFLICTED, /** * The event of some character ending its turn. */ END_TURN_END, /** * The event of some character starting its turn after the end turn of the * previous character. */ END_TURN_START, /** * The event thrown when the single attack hits normally. */ SINGLE_ATTACK_HIT, /** * The event thrown when the single attack hits critically. */ SINGLE_ATTACK_HIT_CRITICAL, /** * The event thrown when the single attack misses. */ SINGLE_ATTACK_MISS, /** * The event thrown before a single attack is performed. */ SINGLE_ATTACK_PRE, }
mit
jely2002/Walk-Simulator
src/shadows/ShadowMapMasterRenderer.java
7992
package shadows; import java.util.List; import java.util.Map; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; import entities.Camera; import entities.Entity; import entities.Light; import entities.Player; import models.TexturedModel; public class ShadowMapMasterRenderer { private static final int SHADOW_MAP_SIZE = 5200; private ShadowFrameBuffer shadowFbo; private ShadowShader shader; private ShadowBox shadowBox; private Matrix4f projectionMatrix = new Matrix4f(); private Matrix4f lightViewMatrix = new Matrix4f(); private Matrix4f projectionViewMatrix = new Matrix4f(); private Matrix4f offset = createOffset(); private ShadowMapEntityRenderer entityRenderer; /** * Creates instances of the important objects needed for rendering the scene * to the shadow map. This includes the {@link ShadowBox} which calculates * the position and size of the "view cuboid", the simple renderer and * shader program that are used to render objects to the shadow map, and the * {@link ShadowFrameBuffer} to which the scene is rendered. The size of the * shadow map is determined here. * * @param camera * - the camera being used in the scene. */ public ShadowMapMasterRenderer(Camera camera) { shader = new ShadowShader(); shadowBox = new ShadowBox(lightViewMatrix, camera); shadowFbo = new ShadowFrameBuffer(SHADOW_MAP_SIZE, SHADOW_MAP_SIZE); entityRenderer = new ShadowMapEntityRenderer(shader, projectionViewMatrix); } /** * Carries out the shadow render pass. This renders the entities to the * shadow map. First the shadow box is updated to calculate the size and * position of the "view cuboid". The light direction is assumed to be * "-lightPosition" which will be fairly accurate assuming that the light is * very far from the scene. It then prepares to render, renders the entities * to the shadow map, and finishes rendering. * * @param entities * - the lists of entities to be rendered. Each list is * associated with the {@link TexturedModel} that all of the * entities in that list use. * @param sun * - the light acting as the sun in the scene. */ public void render(Map<TexturedModel, List<Entity>> entities, Light sun) { shadowBox.update(); Vector3f sunPosition = sun.getPosition(); Vector3f lightDirection = new Vector3f(-sunPosition.x, -sunPosition.y, -sunPosition.z); prepare(lightDirection, shadowBox); entityRenderer.render(entities); finish(); } /** * This biased projection-view matrix is used to convert fragments into * "shadow map space" when rendering the main render pass. It converts a * world space position into a 2D coordinate on the shadow map. This is * needed for the second part of shadow mapping. * * @return The to-shadow-map-space matrix. */ public Matrix4f getToShadowMapSpaceMatrix() { return Matrix4f.mul(offset, projectionViewMatrix, null); } /** * Clean up the shader and FBO on closing. */ public void cleanUp() { shader.cleanUp(); shadowFbo.cleanUp(); } /** * @return The ID of the shadow map texture. The ID will always stay the * same, even when the contents of the shadow map texture change * each frame. */ public int getShadowMap() { return shadowFbo.getShadowMap(); } /** * @return The light's "view" matrix. */ protected Matrix4f getLightSpaceTransform() { return lightViewMatrix; } /** * Prepare for the shadow render pass. This first updates the dimensions of * the orthographic "view cuboid" based on the information that was * calculated in the {@link SHadowBox} class. The light's "view" matrix is * also calculated based on the light's direction and the center position of * the "view cuboid" which was also calculated in the {@link ShadowBox} * class. These two matrices are multiplied together to create the * projection-view matrix. This matrix determines the size, position, and * orientation of the "view cuboid" in the world. This method also binds the * shadows FBO so that everything rendered after this gets rendered to the * FBO. It also enables depth testing, and clears any data that is in the * FBOs depth attachment from last frame. The simple shader program is also * started. * * @param lightDirection * - the direction of the light rays coming from the sun. * @param box * - the shadow box, which contains all the info about the * "view cuboid". */ private void prepare(Vector3f lightDirection, ShadowBox box) { updateOrthoProjectionMatrix(box.getWidth(), box.getHeight(), box.getLength()); updateLightViewMatrix(lightDirection, box.getCenter()); Matrix4f.mul(projectionMatrix, lightViewMatrix, projectionViewMatrix); shadowFbo.bindFrameBuffer(); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); shader.start(); } /** * Finish the shadow render pass. Stops the shader and unbinds the shadow * FBO, so everything rendered after this point is rendered to the screen, * rather than to the shadow FBO. */ private void finish() { shader.stop(); shadowFbo.unbindFrameBuffer(); } /** * Updates the "view" matrix of the light. This creates a view matrix which * will line up the direction of the "view cuboid" with the direction of the * light. The light itself has no position, so the "view" matrix is centered * at the center of the "view cuboid". The created view matrix determines * where and how the "view cuboid" is positioned in the world. The size of * the view cuboid, however, is determined by the projection matrix. * * @param direction * - the light direction, and therefore the direction that the * "view cuboid" should be pointing. * @param center * - the center of the "view cuboid" in world space. */ private void updateLightViewMatrix(Vector3f direction, Vector3f center) { direction.normalise(); center.negate(); lightViewMatrix.setIdentity(); float pitch = (float) Math.acos(new Vector2f(direction.x, direction.z).length()); Matrix4f.rotate(pitch, new Vector3f(1, 0, 0), lightViewMatrix, lightViewMatrix); float yaw = (float) Math.toDegrees(((float) Math.atan(direction.x / direction.z))); yaw = direction.z > 0 ? yaw - 180 : yaw; Matrix4f.rotate((float) -Math.toRadians(yaw), new Vector3f(0, 1, 0), lightViewMatrix, lightViewMatrix); Matrix4f.translate(center, lightViewMatrix, lightViewMatrix); } /** * Creates the orthographic projection matrix. This projection matrix * basically sets the width, length and height of the "view cuboid", based * on the values that were calculated in the {@link ShadowBox} class. * * @param width * - shadow box width. * @param height * - shadow box height. * @param length * - shadow box length. */ private void updateOrthoProjectionMatrix(float width, float height, float length) { projectionMatrix.setIdentity(); projectionMatrix.m00 = 2f / width; projectionMatrix.m11 = 2f / height; projectionMatrix.m22 = -2f / length; projectionMatrix.m33 = 1; } /** * Create the offset for part of the conversion to shadow map space. This * conversion is necessary to convert from one coordinate system to the * coordinate system that we can use to sample to shadow map. * * @return The offset as a matrix (so that it's easy to apply to other matrices). */ private static Matrix4f createOffset() { Matrix4f offset = new Matrix4f(); offset.translate(new Vector3f(0.5f, 0.5f, 0.5f)); offset.scale(new Vector3f(0.5f, 0.5f, 0.5f)); return offset; } }
mit
puras/mo-common
src/main/java/me/puras/common/controller/CrudController.java
2669
package me.puras.common.controller; import me.puras.common.domain.DomainModel; import me.puras.common.error.BaseErrCode; import me.puras.common.json.Response; import me.puras.common.json.ResponseHelper; import me.puras.common.service.CrudService; import me.puras.common.util.ClientListSlice; import me.puras.common.util.ListSlice; import me.puras.common.util.Pagination; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; public abstract class CrudController<T> extends BaseController { public abstract CrudService<T> getService(); protected boolean beforeCheck(T t) { return true; } protected void doCreateBefore(T t) {} protected void doUpdateBefore(T t) {} @GetMapping("") public Response<ClientListSlice<T>> list(Pagination pagination) { ListSlice<T> slice = getService().findAll(getBounds(pagination)); return updateResultResponse(pagination, slice); } @GetMapping("{id}") public Response<T> detail(@PathVariable("id") Long id) { T t = getService().findById(id); notFoundIfNull(t); return ResponseHelper.createSuccessResponse(t); } @PostMapping("") public Response<T> create(@Valid @RequestBody T t, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return ResponseHelper.createResponse(BaseErrCode.DATA_BIND_ERR.getCode(), BaseErrCode.DATA_BIND_ERR.getDesc()); } if (!beforeCheck(t)) { return ResponseHelper.createResponse(BaseErrCode.DATA_ALREADY_EXIST.getCode(), BaseErrCode.DATA_ALREADY_EXIST.getDesc()); } doCreateBefore(t); getService().create(t); return ResponseHelper.createSuccessResponse(t); } @PutMapping("{id}") public Response<T> update(@PathVariable("id") Long id, @RequestBody T t) { T oldT = getService().findById(id); notFoundIfNull(oldT); if (t instanceof DomainModel) { ((DomainModel)t).setId(id); } if (!beforeCheck(t)) { return ResponseHelper.createResponse(BaseErrCode.DATA_ALREADY_EXIST.getCode(), BaseErrCode.DATA_ALREADY_EXIST.getDesc()); } doUpdateBefore(t); getService().update(t); return ResponseHelper.createSuccessResponse(t); } @DeleteMapping("{id}") public Response<Boolean> delete(@PathVariable("id") Long id) { T t = getService().findById(id); notFoundIfNull(t); int result = getService().delete(id); return ResponseHelper.createSuccessResponse(result > 0 ? true : false); } }
mit
Juffik/JavaRush-1
src/com/javarush/test/level14/lesson08/bonus03/Singleton.java
381
package com.javarush.test.level14.lesson08.bonus03; /** * Created by Алексей on 12.04.2014. */ public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if ( instance == null ) { instance = new Singleton(); } return instance; } }
mit
NautiluX/yukan
java_backend/src/main/java/com/ntlx/exception/BoardNotFoundException.java
326
package com.ntlx.exception; public class BoardNotFoundException extends KanbanException { private static final long serialVersionUID = 1L; private int boardId; public BoardNotFoundException (int boardId) { this.boardId = boardId; } public String getMessage() { return "Board not found. (ID: " + boardId + ")"; } }
mit
EricHyh/FileDownloader
ArithmeticDemo/src/main/java/com/hyh/arithmetic/skills/Solution4.java
4599
package com.hyh.arithmetic.skills; import android.annotation.SuppressLint; import java.util.ArrayList; import java.util.List; /** * 规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」 * ( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。 * 所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。 * 我们可以用每个人的编号来表示团队中的成员:例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0],people[1],和 people[3] 的备选人员。 * 请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按任意顺序返回答案,本题保证答案存在。 * <p> * 示例 1: * 输入:req_skills = ["java","nodejs","reactjs"], * people = [["java"],["nodejs"],["nodejs","reactjs"]] * 输出:[0,2] * <p> * 示例 2: * 输入:req_skills = ["algorithms","math","java","reactjs","csharp","aws"], * people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] * 输出:[1,2] * <p> * <p> * 1 <= req_skills.length <= 16 * 1 <= people.length <= 60 * 1 <= people[i].length, req_skills[i].length, people[i][j].length <= 16 * req_skills 和 people[i] 中的元素分别各不相同 * req_skills[i][j], people[i][j][k] 都由小写英文字母组成 * 本题保证「必要团队」一定存在 */ public class Solution4 { @SuppressLint("UseSparseArrays") public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) { int req_skills_code = (int) (Math.pow(2, req_skills.length) - 1); List<Integer> people_code = new ArrayList<>(); for (int i = 0; i < people.size(); i++) { List<String> person_skills = people.get(i); int person_code = 0; for (int j = 0; j < person_skills.size(); j++) { String skill = person_skills.get(j); int index = indexOf(req_skills, skill); if (index >= 0) { person_code += Math.pow(2, index); } } people_code.add(person_code); } for (int i = 0; i < people_code.size(); i++) { Integer i_person_code = people_code.get(i); if (i_person_code == 0) continue; if (i == people_code.size() - 1) break; for (int j = i + 1; j < people_code.size(); j++) { Integer j_person_code = people_code.get(j); if ((i_person_code | j_person_code) == j_person_code) { people_code.set(i, 0); } else if ((i_person_code | j_person_code) == i_person_code) { people_code.set(j, 0); } } } Object[] preResult = new Object[req_skills.length]; Object[] result = new Object[req_skills.length]; /*Integer person_code = people_code.get(0); for (int i = 0; i < req_skills.length; i++) { int skills_code = (int) (Math.pow(2, i + 1) - 1); if ((person_code | skills_code) == person_code) { preResult[i] = new int[]{0}; } else { break; } }*/ int person_code = 0; for (int i = 0; i < people_code.size(); i++) { person_code |= people_code.get(i); for (int j = 0; j < req_skills.length; j++) { int skills_code = (int) (Math.pow(2, j + 1) - 1); if ((person_code | skills_code) == person_code) { //result[i] = new int[]{0}; } else { } } } /*for (int i = 0; i < req_skills.length; i++) { int skills_code = (int) (Math.pow(2, i + 1) - 1); int people_code_temp = 0; for (int j = 0; j < people_code.size(); j++) { people_code_temp |= people_code.get(j); if () { } } preResult = result; }*/ return null; } private int indexOf(String[] req_skills, String skill) { for (int index = 0; index < req_skills.length; index++) { String req_skill = req_skills[index]; if (req_skill.equals(skill)) return index; } return -1; } }
mit
habibmasuro/XChange
xchange-justcoin/src/main/java/com/xeiam/xchange/justcoin/service/polling/JustcoinBasePollingService.java
2758
/** * Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.xeiam.xchange.justcoin.service.polling; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import si.mazi.rescu.RestProxyFactory; import com.xeiam.xchange.ExchangeSpecification; import com.xeiam.xchange.currency.CurrencyPair; import com.xeiam.xchange.justcoin.Justcoin; import com.xeiam.xchange.justcoin.JustcoinAdapters; import com.xeiam.xchange.justcoin.dto.marketdata.JustcoinTicker; import com.xeiam.xchange.service.BaseExchangeService; import com.xeiam.xchange.utils.AuthUtils; public class JustcoinBasePollingService<T extends Justcoin> extends BaseExchangeService { protected final T justcoin; private final Set<CurrencyPair> currencyPairs = new HashSet<CurrencyPair>(); /** * Constructor * * @param exchangeSpecification The {@link ExchangeSpecification} */ public JustcoinBasePollingService(Class<T> type, ExchangeSpecification exchangeSpecification) { super(exchangeSpecification); this.justcoin = RestProxyFactory.createProxy(type, exchangeSpecification.getSslUri()); } @Override public Collection<CurrencyPair> getExchangeSymbols() throws IOException { if (currencyPairs.isEmpty()) { for (final JustcoinTicker ticker : justcoin.getTickers()) { final CurrencyPair currencyPair = JustcoinAdapters.adaptCurrencyPair(ticker.getId()); currencyPairs.add(currencyPair); } } return currencyPairs; } protected String getBasicAuthentication() { return AuthUtils.getBasicAuth(exchangeSpecification.getUserName(), exchangeSpecification.getPassword()); } }
mit
flow/react
src/main/java/com/flowpowered/react/collision/narrowphase/EPA/EPAAlgorithm.java
18355
/* * This file is part of React, licensed under the MIT License (MIT). * * Copyright (c) 2013 Flow Powered <https://flowpowered.com/> * Original ReactPhysics3D C++ library by Daniel Chappuis <http://danielchappuis.ch> * React is re-licensed with permission from ReactPhysics3D author. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.flowpowered.react.collision.narrowphase.EPA; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; import com.flowpowered.react.ReactDefaults; import com.flowpowered.react.collision.narrowphase.GJK.GJKAlgorithm; import com.flowpowered.react.collision.narrowphase.GJK.Simplex; import com.flowpowered.react.collision.shape.CollisionShape; import com.flowpowered.react.constraint.ContactPoint.ContactPointInfo; import com.flowpowered.react.math.Matrix3x3; import com.flowpowered.react.math.Quaternion; import com.flowpowered.react.math.Transform; import com.flowpowered.react.math.Vector3; /** * This class is the implementation of the Expanding Polytope Algorithm (EPA). The EPA algorithm computes the penetration depth and contact points between two enlarged objects (with margin) where the * original objects (without margin) intersect. The penetration depth of a pair of intersecting objects A and B is the length of a point on the boundary of the Minkowski sum (A-B) closest to the * origin. The goal of the EPA algorithm is to start with an initial simplex polytope that contains the origin and expend it in order to find the point on the boundary of (A-B) that is closest to the * origin. An initial simplex that contains the origin has been computed with the GJK algorithm. The EPA Algorithm will extend this simplex polytope to find the correct penetration depth. The * implementation of the EPA algorithm is based on the book "Collision Detection in 3D Environments". */ public class EPAAlgorithm { private static final int MAX_SUPPORT_POINTS = 100; private static final int MAX_FACETS = 200; /** * Computes the penetration depth with the EPA algorithm. This method computes the penetration depth and contact points between two enlarged objects (with margin) where the original objects * (without margin) intersect. An initial simplex that contains the origin has been computed with GJK algorithm. The EPA Algorithm will extend this simplex polytope to find the correct penetration * depth. Returns true if the computation was successful, false if not. * * @param simplex The initial simplex * @param collisionShape1 The first collision shape * @param transform1 The transform of the first collision shape * @param collisionShape2 The second collision shape * @param transform2 The transform of the second collision shape * @param v The vector in which to store the closest point * @param contactInfo The contact info in which to store the contact info of the collision * @return Whether or not the computation was successful */ public boolean computePenetrationDepthAndContactPoints(Simplex simplex, CollisionShape collisionShape1, Transform transform1, CollisionShape collisionShape2, Transform transform2, Vector3 v, ContactPointInfo contactInfo) { final Vector3[] suppPointsA = new Vector3[MAX_SUPPORT_POINTS]; final Vector3[] suppPointsB = new Vector3[MAX_SUPPORT_POINTS]; final Vector3[] points = new Vector3[MAX_SUPPORT_POINTS]; final TrianglesStore triangleStore = new TrianglesStore(); final Queue<TriangleEPA> triangleHeap = new PriorityQueue<>(MAX_FACETS, new TriangleComparison()); final Transform body2Tobody1 = Transform.multiply(transform1.getInverse(), transform2); final Matrix3x3 rotateToBody2 = Matrix3x3.multiply(transform2.getOrientation().getMatrix().getTranspose(), transform1.getOrientation().getMatrix()); int nbVertices = simplex.getSimplex(suppPointsA, suppPointsB, points); final float tolerance = ReactDefaults.MACHINE_EPSILON * simplex.getMaxLengthSquareOfAPoint(); int nbTriangles = 0; triangleStore.clear(); switch (nbVertices) { case 1: return false; case 2: { final Vector3 d = Vector3.subtract(points[1], points[0]).getUnit(); final int minAxis = d.getAbsoluteVector().getMinAxis(); final float sin60 = (float) Math.sqrt(3) * 0.5f; final Quaternion rotationQuat = new Quaternion(d.getX() * sin60, d.getY() * sin60, d.getZ() * sin60, 0.5f); final Matrix3x3 rotationMat = rotationQuat.getMatrix(); final Vector3 v1 = d.cross(new Vector3(minAxis == 0 ? 1 : 0, minAxis == 1 ? 1 : 0, minAxis == 2 ? 1 : 0)); final Vector3 v2 = Matrix3x3.multiply(rotationMat, v1); final Vector3 v3 = Matrix3x3.multiply(rotationMat, v2); suppPointsA[2] = collisionShape1.getLocalSupportPointWithMargin(v1); suppPointsB[2] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v1)))); points[2] = Vector3.subtract(suppPointsA[2], suppPointsB[2]); suppPointsA[3] = collisionShape1.getLocalSupportPointWithMargin(v2); suppPointsB[3] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v2)))); points[3] = Vector3.subtract(suppPointsA[3], suppPointsB[3]); suppPointsA[4] = collisionShape1.getLocalSupportPointWithMargin(v3); suppPointsB[4] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v3)))); points[4] = Vector3.subtract(suppPointsA[4], suppPointsB[4]); if (isOriginInTetrahedron(points[0], points[2], points[3], points[4]) == 0) { suppPointsA[1].set(suppPointsA[4]); suppPointsB[1].set(suppPointsB[4]); points[1].set(points[4]); } else if (isOriginInTetrahedron(points[1], points[2], points[3], points[4]) == 0) { suppPointsA[0].set(suppPointsA[4]); suppPointsB[0].set(suppPointsB[4]); points[0].set(points[4]); } else { return false; } nbVertices = 4; } case 4: { final int badVertex = isOriginInTetrahedron(points[0], points[1], points[2], points[3]); if (badVertex == 0) { final TriangleEPA face0 = triangleStore.newTriangle(points, 0, 1, 2); final TriangleEPA face1 = triangleStore.newTriangle(points, 0, 3, 1); final TriangleEPA face2 = triangleStore.newTriangle(points, 0, 2, 3); final TriangleEPA face3 = triangleStore.newTriangle(points, 1, 3, 2); if (!(face0 != null && face1 != null && face2 != null && face3 != null && face0.getDistSquare() > 0 && face1.getDistSquare() > 0 && face2.getDistSquare() > 0 && face3.getDistSquare() > 0)) { return false; } TriangleEPA.link(new EdgeEPA(face0, 0), new EdgeEPA(face1, 2)); TriangleEPA.link(new EdgeEPA(face0, 1), new EdgeEPA(face3, 2)); TriangleEPA.link(new EdgeEPA(face0, 2), new EdgeEPA(face2, 0)); TriangleEPA.link(new EdgeEPA(face1, 0), new EdgeEPA(face2, 2)); TriangleEPA.link(new EdgeEPA(face1, 1), new EdgeEPA(face3, 0)); TriangleEPA.link(new EdgeEPA(face2, 1), new EdgeEPA(face3, 1)); nbTriangles = addFaceCandidate(face0, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face1, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face2, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face3, triangleHeap, nbTriangles, Float.MAX_VALUE); break; } if (badVertex < 4) { suppPointsA[badVertex - 1].set(suppPointsA[4]); suppPointsB[badVertex - 1].set(suppPointsB[4]); points[badVertex - 1].set(points[4]); } nbVertices = 3; } case 3: { final Vector3 v1 = Vector3.subtract(points[1], points[0]); final Vector3 v2 = Vector3.subtract(points[2], points[0]); final Vector3 n = v1.cross(v2); suppPointsA[3] = collisionShape1.getLocalSupportPointWithMargin(n); suppPointsB[3] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(n)))); points[3] = Vector3.subtract(suppPointsA[3], suppPointsB[3]); suppPointsA[4] = collisionShape1.getLocalSupportPointWithMargin(Vector3.negate(n)); suppPointsB[4] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, n))); points[4] = Vector3.subtract(suppPointsA[4], suppPointsB[4]); final TriangleEPA face0 = triangleStore.newTriangle(points, 0, 1, 3); final TriangleEPA face1 = triangleStore.newTriangle(points, 1, 2, 3); final TriangleEPA face2 = triangleStore.newTriangle(points, 2, 0, 3); final TriangleEPA face3 = triangleStore.newTriangle(points, 0, 2, 4); final TriangleEPA face4 = triangleStore.newTriangle(points, 2, 1, 4); final TriangleEPA face5 = triangleStore.newTriangle(points, 1, 0, 4); if (!(face0 != null && face1 != null && face2 != null && face3 != null && face4 != null && face5 != null && face0.getDistSquare() > 0 && face1.getDistSquare() > 0 && face2.getDistSquare() > 0 && face3.getDistSquare() > 0 && face4.getDistSquare() > 0 && face5.getDistSquare() > 0)) { return false; } TriangleEPA.link(new EdgeEPA(face0, 1), new EdgeEPA(face1, 2)); TriangleEPA.link(new EdgeEPA(face1, 1), new EdgeEPA(face2, 2)); TriangleEPA.link(new EdgeEPA(face2, 1), new EdgeEPA(face0, 2)); TriangleEPA.link(new EdgeEPA(face0, 0), new EdgeEPA(face5, 0)); TriangleEPA.link(new EdgeEPA(face1, 0), new EdgeEPA(face4, 0)); TriangleEPA.link(new EdgeEPA(face2, 0), new EdgeEPA(face3, 0)); TriangleEPA.link(new EdgeEPA(face3, 1), new EdgeEPA(face4, 2)); TriangleEPA.link(new EdgeEPA(face4, 1), new EdgeEPA(face5, 2)); TriangleEPA.link(new EdgeEPA(face5, 1), new EdgeEPA(face3, 2)); nbTriangles = addFaceCandidate(face0, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face1, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face2, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face3, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face4, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face5, triangleHeap, nbTriangles, Float.MAX_VALUE); nbVertices = 5; } break; } if (nbTriangles == 0) { return false; } TriangleEPA triangle; float upperBoundSquarePenDepth = Float.MAX_VALUE; do { triangle = triangleHeap.remove(); nbTriangles--; if (!triangle.isObsolete()) { if (nbVertices == MAX_SUPPORT_POINTS) { break; } suppPointsA[nbVertices] = collisionShape1.getLocalSupportPointWithMargin(triangle.getClosestPoint()); suppPointsB[nbVertices] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(triangle.getClosestPoint())))); points[nbVertices] = Vector3.subtract(suppPointsA[nbVertices], suppPointsB[nbVertices]); final int indexNewVertex = nbVertices; nbVertices++; final float wDotv = points[indexNewVertex].dot(triangle.getClosestPoint()); if (wDotv <= 0) { throw new IllegalStateException("wDotv must be greater than zero"); } final float wDotVSquare = wDotv * wDotv / triangle.getDistSquare(); if (wDotVSquare < upperBoundSquarePenDepth) { upperBoundSquarePenDepth = wDotVSquare; } final float error = wDotv - triangle.getDistSquare(); if (error <= Math.max(tolerance, GJKAlgorithm.REL_ERROR_SQUARE * wDotv) || points[indexNewVertex].equals(points[triangle.get(0)]) || points[indexNewVertex].equals(points[triangle.get(1)]) || points[indexNewVertex].equals(points[triangle.get(2)])) { break; } int i = triangleStore.getNbTriangles(); if (!triangle.computeSilhouette(points, indexNewVertex, triangleStore)) { break; } while (i != triangleStore.getNbTriangles()) { final TriangleEPA newTriangle = triangleStore.get(i); nbTriangles = addFaceCandidate(newTriangle, triangleHeap, nbTriangles, upperBoundSquarePenDepth); i++; } } } while (nbTriangles > 0 && triangleHeap.element().getDistSquare() <= upperBoundSquarePenDepth); v.set(Matrix3x3.multiply(transform1.getOrientation().getMatrix(), triangle.getClosestPoint())); final Vector3 pALocal = triangle.computeClosestPointOfObject(suppPointsA); final Vector3 pBLocal = Transform.multiply(body2Tobody1.getInverse(), triangle.computeClosestPointOfObject(suppPointsB)); final Vector3 normal = v.getUnit(); final float penetrationDepth = v.length(); if (penetrationDepth <= 0) { throw new IllegalStateException("penetration depth must be greater that zero"); } contactInfo.set(normal, penetrationDepth, pALocal, pBLocal); return true; } // Decides if the origin is in the tetrahedron. // Returns 0 if the origin is in the tetrahedron or returns the index (1,2,3 or 4) of the bad // vertex if the origin is not in the tetrahedron. private static int isOriginInTetrahedron(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) { final Vector3 normal1 = Vector3.subtract(p2, p1).cross(Vector3.subtract(p3, p1)); if (normal1.dot(p1) > 0 == normal1.dot(p4) > 0) { return 4; } final Vector3 normal2 = Vector3.subtract(p4, p2).cross(Vector3.subtract(p3, p2)); if (normal2.dot(p2) > 0 == normal2.dot(p1) > 0) { return 1; } final Vector3 normal3 = Vector3.subtract(p4, p3).cross(Vector3.subtract(p1, p3)); if (normal3.dot(p3) > 0 == normal3.dot(p2) > 0) { return 2; } final Vector3 normal4 = Vector3.subtract(p2, p4).cross(Vector3.subtract(p1, p4)); if (normal4.dot(p4) > 0 == normal4.dot(p3) > 0) { return 3; } return 0; } // Adds a triangle face in the candidate triangle heap in the EPA algorithm. private static int addFaceCandidate(TriangleEPA triangle, Queue<TriangleEPA> heap, int nbTriangles, float upperBoundSquarePenDepth) { if (triangle.isClosestPointInternalToTriangle() && triangle.getDistSquare() <= upperBoundSquarePenDepth) { heap.add(triangle); nbTriangles++; } return nbTriangles; } // Compares the EPA triangles in the queue. private static class TriangleComparison implements Comparator<TriangleEPA> { @Override public int compare(TriangleEPA face1, TriangleEPA face2) { final float dist1 = face1.getDistSquare(); final float dist2 = face2.getDistSquare(); if (dist1 == dist2) { return 0; } return dist1 > dist2 ? 1 : -1; } } }
mit
iontorrent/Torrent-Variant-Caller-stable
public/java/src/org/broadinstitute/sting/utils/codecs/table/TableCodec.java
4090
package org.broadinstitute.sting.utils.codecs.table; import org.broad.tribble.Feature; import org.broad.tribble.readers.LineReader; import org.broadinstitute.sting.gatk.refdata.ReferenceDependentFeatureCodec; import org.broadinstitute.sting.utils.GenomeLocParser; import org.broadinstitute.sting.utils.exceptions.UserException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Reads tab deliminated tabular text files * * <p> * <ul> * <li>Header: must begin with line HEADER or track (for IGV), followed by any number of column names, * separated by whitespace.</li> * <li>Comment lines starting with # are ignored</li> * <li>Each non-header and non-comment line is split into parts by whitespace, * and these parts are assigned as a map to their corresponding column name in the header. * Note that the first element (corresponding to the HEADER column) must be a valid genome loc * such as 1, 1:1 or 1:1-10, which is the position of the Table element on the genome. TableCodec * requires that there be one value for each column in the header, and no more, on all lines.</li> * </ul> * </p> * * </p> * * <h2>File format example</h2> * <pre> * HEADER a b c * 1:1 1 2 3 * 1:2 4 5 6 * 1:3 7 8 9 * </pre> * * @author Mark DePristo * @since 2009 */ public class TableCodec implements ReferenceDependentFeatureCodec { final static protected String delimiterRegex = "\\s+"; final static protected String headerDelimiter = "HEADER"; final static protected String igvHeaderDelimiter = "track"; final static protected String commentDelimiter = "#"; protected ArrayList<String> header = new ArrayList<String>(); /** * The parser to use when resolving genome-wide locations. */ protected GenomeLocParser genomeLocParser; /** * Set the parser to use when resolving genetic data. * @param genomeLocParser The supplied parser. */ @Override public void setGenomeLocParser(GenomeLocParser genomeLocParser) { this.genomeLocParser = genomeLocParser; } @Override public Feature decodeLoc(String line) { return decode(line); } @Override public Feature decode(String line) { if (line.startsWith(headerDelimiter) || line.startsWith(commentDelimiter) || line.startsWith(igvHeaderDelimiter)) return null; String[] split = line.split(delimiterRegex); if (split.length < 1) throw new IllegalArgumentException("TableCodec line = " + line + " doesn't appear to be a valid table format"); return new TableFeature(genomeLocParser.parseGenomeLoc(split[0]),Arrays.asList(split),header); } @Override public Class<TableFeature> getFeatureType() { return TableFeature.class; } @Override public Object readHeader(LineReader reader) { String line = ""; try { boolean isFirst = true; while ((line = reader.readLine()) != null) { if ( isFirst && ! line.startsWith(headerDelimiter) && ! line.startsWith(commentDelimiter)) { throw new UserException.MalformedFile("TableCodec file does not have a header"); } isFirst &= line.startsWith(commentDelimiter); if (line.startsWith(headerDelimiter)) { if (header.size() > 0) throw new IllegalStateException("Input table file seems to have two header lines. The second is = " + line); String spl[] = line.split(delimiterRegex); for (String s : spl) header.add(s); return header; } else if (!line.startsWith(commentDelimiter)) { break; } } } catch (IOException e) { throw new UserException.MalformedFile("unable to parse header from TableCodec file",e); } return header; } public boolean canDecode(final String potentialInput) { return false; } }
mit
some1epic123/Mr.-Dungeon-Aase-LD34-
LD34/src/com/exilegl/ld34/entity/enemy/EntityBullet.java
6144
package com.exilegl.ld34.entity.enemy; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.box2d.World; import com.exilegl.ld34.ai.AiFollowLocation; import com.exilegl.ld34.entity.Entity; import com.exilegl.ld34.entity.EntityCoin; import com.exilegl.ld34.entity.EntityDirection; import com.exilegl.ld34.entity.EntityPlayer; import com.exilegl.ld34.map.Map; import com.exilegl.ld34.sound.Sound; import com.exilegl.ld34.tile.Tile; import box2dLight.ChainLight; import box2dLight.ConeLight; import box2dLight.PointLight; public class EntityBullet extends EntityEnemy{ //The bullet's light color private Color color; private float distance; private Vector2 offset; private float age; private boolean textured; private Texture texture; //Whether or not the bullet kills enemies. If not, it kills non enemies. private boolean killsEnemies; private float duration; private boolean ranged; public EntityBullet(Vector2 location, Color color, EntityDirection direction, float distance, boolean killsEnemies, float duration, boolean textured, boolean ranged, boolean moveY) { super(null, location, 10, 10, true); this.setColor(color); this.setDistance(distance); this.offset = new Vector2(0, 0); float y = (this.getLocation().y); if(ranged){ Random r = new Random(); if(r.nextBoolean()){ y = (y + 64); }else{ y = (y - 64); } } if(!moveY){ if(direction == EntityDirection.LEFT){ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x - this.getDistance() * 5, y), this.getSpeed(), false, false)); }else{ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x + this.getDistance() * 5, y), this.getSpeed(), false, false)); } }else{ if(direction == EntityDirection.LEFT){ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x * 5, y + distance * 3), this.getSpeed(), false, false)); }else{ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x, y - distance * 3), this.getSpeed(), false, false)); } } setAge(0); if(this.isTextured()){ this.setTexture(new Texture(Gdx.files.internal("assets/texture/entity/redbullet.png"))); } this.setKillsEnemies(killsEnemies); this.setDuration(duration); if(textured){ this.setTexture(new Texture(Gdx.files.internal("assets/texture/misc/bullet.png"))); } this.setTextured(textured); if(!killsEnemies){ Sound.play(Sound.Enemy_Shoot, 0.5f); } this.ranged = ranged; if(ranged){ this.setDistance(distance * 1.5f); } } @Override public void update() { setAge((getAge() + 1 * Gdx.graphics.getDeltaTime())); if(this.getLight() == null){ this.setLight(new PointLight(this.getMap().getRay(), Map.RAYS, this.getColor(), this.getDistance() / 5, this.getLocation().x, this.getLocation().y)); } this.flickerLight(20, (int) ((int) getDistance() * 1.5f), (int) getDistance()); this.getLight().setPosition(this.getLocation().x + offset.x, this.getLocation().y + offset.y); this.setRectangle(new Rectangle(this.getLocation().x, this.getLocation().y, this.getLight().getDistance(), this.getLight().getDistance())); this.performAi(); if(this.getAge() > this.getDuration()){ this.kill(); } for(Entity e : this.getMap().getEntities()){ if(this.isKillsEnemies()){ if(e instanceof EntityEnemy && !(e instanceof EntityPlayer) && !(e instanceof EntityBullet) && this.getRectangle().overlaps(e.getRectangle()) && !(e instanceof EntityDeathTile)){ e.kill(); this.kill(); Sound.play(Sound.Kill_Enemy); } }else{ try{ if(!(e instanceof EntityEnemy) && !(e instanceof EntityCoin) && this.getRectangle().overlaps(e.getRectangle())){ e.kill(); this.kill(); } }catch(NullPointerException n){ } } if(e instanceof EntityPlayer && this.getRectangle().overlaps(e.getRectangle()) && !this.isKillsEnemies()){ e.kill(); this.kill(); } } for(Tile t : this.getMap().getTiles()){ if(t.getType().SOLID){ Rectangle tileRect = new Rectangle(t.getLocation().x, t.getLocation().y, t.getSingleAnimation().getWidth(), t.getSingleAnimation().getHeight()); Rectangle bulletRect = new Rectangle(this.getLocation().x, this.getLocation().y, this.getLight().getDistance(), this.getLight().getDistance()); if(bulletRect.overlaps(tileRect)){ this.kill(); } } } } @Override public void draw(SpriteBatch batch){ if(this.isTextured()){ batch.draw(this.getTexture(), this.getLocation().x, this.getLocation().y); } } @Override public void create(Map map) { this.setMap(map); if(isKillsEnemies()){ Vector3 m = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0); this.getMap().getCamera().unproject(m); ((AiFollowLocation) this.getActions().get(0)).getDestination().set(m.x, m.y); } } public boolean isTextured() { return textured; } public void setTextured(boolean textured) { this.textured = textured; } public Texture getTexture() { return texture; } public void setTexture(Texture texture) { this.texture = texture; } public float getAge() { return age; } public void setAge(float age) { this.age = age; } public float getDistance() { return distance; } public void setDistance(float distance) { this.distance = distance; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public boolean isKillsEnemies() { return killsEnemies; } public void setKillsEnemies(boolean killsEnemies) { this.killsEnemies = killsEnemies; } public Vector2 getOffset(){ return this.offset; } }
mit
zekedroid/ABC-Music-Player
src/adts/Music.java
1812
package adts; /** * Interface that represents any music item. MusicSymbol and MusicPart extend * this. Thus, a Music could be a MusicPiece, a Voice, a Chord, a Lyric, a * Pitch, or a Rest. a The objects are immutable. The equals, toString, and * hashCode methods work recursively and individually different from each class * extending Music. Read their documentation for full specs. * **/ /* * Representation Music = MusicPiece(signature: Signature, voices: List<Voice>) * + Measure(notes: List<MusicSymbol>, lyrics: Lyric) + Voice(name: String, * measures: List<Measure>) + Chord(notes: List<Pitch>)+ + Lyric(syllables: * List<String>) + Pitch(value: string, octave: int, length: int) + Rest(length: * int) */ public interface Music { /** * Calculates the required number of ticks per beat, so that each note can * be represented as an integer number of ticks. * * @return integer representing number of ticks per beat. */ public int calculateTicksPerBeat(); /** * Tests the equality of one music to to another, such that two expressions * with equal attributes (observationally indistinguishable) are considered * equal * * @param _that * music to compare to * @return whether or not the two musics are equal */ @Override public boolean equals(Object _that); /** * Returns the string representation of the music * * @returns the music as a string */ @Override public String toString(); /** * Calculates the hashcode for this music. HashCode for two equal musics * will be identical. * * @return the hashcode for the music */ @Override public int hashCode(); }
mit
CubeEngine/Modularity
core/src/main/java/de/cubeisland/engine/modularity/core/LifeCycle.java
11912
/* * The MIT License * Copyright © 2014 Cube Island * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.cubeisland.engine.modularity.core; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.TreeMap; import javax.inject.Provider; import de.cubeisland.engine.modularity.core.graph.Dependency; import de.cubeisland.engine.modularity.core.graph.DependencyInformation; import de.cubeisland.engine.modularity.core.graph.meta.ModuleMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceDefinitionMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceImplementationMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceProviderMetadata; import de.cubeisland.engine.modularity.core.marker.Disable; import de.cubeisland.engine.modularity.core.marker.Enable; import de.cubeisland.engine.modularity.core.marker.Setup; import de.cubeisland.engine.modularity.core.service.ServiceProvider; import static de.cubeisland.engine.modularity.core.LifeCycle.State.*; public class LifeCycle { private static final Field MODULE_META_FIELD; private static final Field MODULE_MODULARITY_FIELD; private static final Field MODULE_LIFECYCLE; static { try { MODULE_META_FIELD = Module.class.getDeclaredField("metadata"); MODULE_META_FIELD.setAccessible(true); MODULE_MODULARITY_FIELD = Module.class.getDeclaredField("modularity"); MODULE_MODULARITY_FIELD.setAccessible(true); MODULE_LIFECYCLE = Module.class.getDeclaredField("lifeCycle"); MODULE_LIFECYCLE.setAccessible(true); } catch (NoSuchFieldException e) { throw new IllegalStateException(); } } private Modularity modularity; private DependencyInformation info; private State current = NONE; private Object instance; private Method enable; private Method disable; private Map<Integer, Method> setup = new TreeMap<Integer, Method>(); private Map<Dependency, SettableMaybe> maybes = new HashMap<Dependency, SettableMaybe>(); private Queue<LifeCycle> impls = new LinkedList<LifeCycle>(); public LifeCycle(Modularity modularity) { this.modularity = modularity; } public LifeCycle load(DependencyInformation info) { this.info = info; this.current = LOADED; return this; } public LifeCycle provide(ValueProvider provider) { this.instance = provider; this.current = PROVIDED; return this; } public LifeCycle initProvided(Object object) { this.instance = object; this.current = PROVIDED; return this; } public boolean isIn(State state) { return current == state; } public LifeCycle instantiate() { if (isIn(NONE)) { throw new IllegalStateException("Cannot instantiate when not loaded"); } if (isIn(LOADED)) { try { if (info instanceof ServiceDefinitionMetadata) { ClassLoader classLoader = info.getClassLoader(); if (classLoader == null) // may happen when loading from classpath { classLoader = modularity.getClass().getClassLoader(); // get parent classloader then } Class<?> instanceClass = Class.forName(info.getClassName(), true, classLoader); instance = new ServiceProvider(instanceClass, impls); // TODO find impls in modularity and link them to this // TODO transition all impls to INSTANTIATED? } else { this.instance = info.injectionPoints().get(INSTANTIATED.name(0)).inject(modularity, this); if (instance instanceof Module) { MODULE_META_FIELD.set(instance, info); MODULE_MODULARITY_FIELD.set(instance, modularity); MODULE_LIFECYCLE.set(instance, this); } info.injectionPoints().get(INSTANTIATED.name(1)).inject(modularity, this); findMethods(); } } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } current = INSTANTIATED; } // else State already reached or provided return this; } public LifeCycle setup() { if (isIn(NONE)) { throw new IllegalStateException("Cannot instantiate when not loaded"); } if (isIn(LOADED)) { this.instantiate(); } if (isIn(INSTANTIATED)) { // TODO abstract those methods away for (Method method : setup.values()) { invoke(method); } for (LifeCycle impl : impls) { impl.setup(); } current = SETUP; } // else reached or provided return this; } public LifeCycle enable() { if (isIn(NONE)) { throw new IllegalStateException("Cannot instantiate when not loaded"); } if (isIn(LOADED)) { this.instantiate(); } if (isIn(INSTANTIATED)) { this.setup(); } if (isIn(SETUP)) { this.modularity.log("Enable " + info.getIdentifier().name()); modularity.runEnableHandlers(getInstance()); invoke(enable); for (SettableMaybe maybe : maybes.values()) { maybe.provide(getProvided(this)); } for (LifeCycle impl : impls) { impl.enable(); } current = ENABLED; } return this; } public LifeCycle disable() { if (isIn(ENABLED)) { modularity.runDisableHandlers(getInstance()); invoke(disable); for (SettableMaybe maybe : maybes.values()) { maybe.remove(); } // TODO if active impl replace in service with inactive OR disable service too // TODO if service disable all impls too modularity.getGraph().getNode(info.getIdentifier()).getPredecessors(); // TODO somehow implement reload too // TODO disable predecessors for (LifeCycle impl : impls) { impl.disable(); } current = DISABLED; } return this; } private void invoke(Method method) { if (method != null) { if (method.isAnnotationPresent(Setup.class)) { info.injectionPoints().get(SETUP.name(method.getAnnotation(Setup.class).value())) .inject(modularity, this); } else if (method.isAnnotationPresent(Enable.class)) { info.injectionPoints().get(ENABLED.name()).inject(modularity, this); } else { try { method.invoke(instance); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (IllegalArgumentException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } } } } public boolean isInstantiated() { return instance != null; } private void findMethods() { // find enable and disable methods Class<?> clazz = instance.getClass(); for (Method method : clazz.getMethods()) { if (method.isAnnotationPresent(Enable.class)) { enable = method; } if (method.isAnnotationPresent(Disable.class)) { disable = method; } if (method.isAnnotationPresent(Setup.class)) { int value = method.getAnnotation(Setup.class).value(); setup.put(value, method); } } } public Object getInstance() { return instance; } @SuppressWarnings("unchecked") public Maybe getMaybe(LifeCycle other) { Dependency identifier = other == null ? null : other.getInformation().getIdentifier(); SettableMaybe maybe = maybes.get(identifier); if (maybe == null) { maybe = new SettableMaybe(getProvided(other)); maybes.put(identifier, maybe); } return maybe; } public Object getProvided(LifeCycle lifeCycle) { boolean enable = true; if (info instanceof ModuleMetadata) { enable = false; } if (instance == null) { this.instantiate(); } if (enable) { this.enable(); // Instantiate Setup and enable dependency before providing it to someone else } Object toSet = instance; if (toSet instanceof Provider) { toSet = ((Provider)toSet).get(); } if (toSet instanceof ValueProvider) { toSet = ((ValueProvider)toSet).get(lifeCycle, modularity); } return toSet; } public void addImpl(LifeCycle impl) { this.impls.add(impl); } public DependencyInformation getInformation() { return info; } public enum State { NONE, LOADED, INSTANTIATED, SETUP, ENABLED, DISABLED, SHUTDOWN, PROVIDED // TODO prevent changing / except shutdown? ; public String name(Integer value) { return value == null ? name() : name() + ":" + value; } } @Override public String toString() { return info.getIdentifier().name() + " " + super.toString(); } }
mit
bugsnag/bugsnag-java
bugsnag-spring/src/main/java/com/bugsnag/MvcConfiguration.java
1039
package com.bugsnag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; /** * If spring-webmvc is loaded, add configuration for reporting unhandled exceptions. */ @Configuration @Conditional(SpringWebMvcLoadedCondition.class) class MvcConfiguration { @Autowired private Bugsnag bugsnag; /** * Register an exception resolver to send unhandled reports to Bugsnag * for uncaught exceptions thrown from request handlers. */ @Bean BugsnagMvcExceptionHandler bugsnagHandlerExceptionResolver() { return new BugsnagMvcExceptionHandler(bugsnag); } /** * Add a callback to assign specified severities for some Spring exceptions. */ @PostConstruct void addExceptionClassCallback() { bugsnag.addCallback(new ExceptionClassCallback()); } }
mit
huangbop/seadroid-build
seadroid/src/main/java/com/seafile/seadroid2/transfer/DownloadStateListener.java
249
package com.seafile.seadroid2.transfer; /** * Download state listener * */ public interface DownloadStateListener { void onFileDownloadProgress(int taskID); void onFileDownloaded(int taskID); void onFileDownloadFailed(int taskID); }
mit
javay/zheng-lite
zheng-common/src/main/java/cn/javay/zheng/common/validator/LengthValidator.java
1107
package cn.javay.zheng.common.validator; import com.baidu.unbiz.fluentvalidator.ValidationError; import com.baidu.unbiz.fluentvalidator.Validator; import com.baidu.unbiz.fluentvalidator.ValidatorContext; import com.baidu.unbiz.fluentvalidator.ValidatorHandler; /** * 长度校验 * Created by shuzheng on 2017/2/18. */ public class LengthValidator extends ValidatorHandler<String> implements Validator<String> { private int min; private int max; private String fieldName; public LengthValidator(int min, int max, String fieldName) { this.min = min; this.max = max; this.fieldName = fieldName; } @Override public boolean validate(ValidatorContext context, String s) { if (null == s || s.length() > max || s.length() < min) { context.addError(ValidationError.create(String.format("%s长度必须介于%s~%s之间!", fieldName, min, max)) .setErrorCode(-1) .setField(fieldName) .setInvalidValue(s)); return false; } return true; } }
mit
cscfa/bartleby
library/logBack/logback-1.1.3/logback-access/src/main/java/ch/qos/logback/access/spi/AccessEvent.java
14592
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.access.spi; import ch.qos.logback.access.AccessConstants; import ch.qos.logback.access.pattern.AccessConverter; import ch.qos.logback.access.servlet.Util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Vector; // Contributors: Joern Huxhorn (see also bug #110) /** * The Access module's internal representation of logging events. When the * logging component instance is called in the container to log then a * <code>AccessEvent</code> instance is created. This instance is passed * around to the different logback components. * * @author Ceki G&uuml;lc&uuml; * @author S&eacute;bastien Pennec */ public class AccessEvent implements Serializable, IAccessEvent { private static final long serialVersionUID = 866718993618836343L; private static final String EMPTY = ""; private transient final HttpServletRequest httpRequest; private transient final HttpServletResponse httpResponse; String requestURI; String requestURL; String remoteHost; String remoteUser; String remoteAddr; String protocol; String method; String serverName; String requestContent; String responseContent; long elapsedTime; Map<String, String> requestHeaderMap; Map<String, String[]> requestParameterMap; Map<String, String> responseHeaderMap; Map<String, Object> attributeMap; long contentLength = SENTINEL; int statusCode = SENTINEL; int localPort = SENTINEL; transient ServerAdapter serverAdapter; /** * The number of milliseconds elapsed from 1/1/1970 until logging event was * created. */ private long timeStamp = 0; public AccessEvent(HttpServletRequest httpRequest, HttpServletResponse httpResponse, ServerAdapter adapter) { this.httpRequest = httpRequest; this.httpResponse = httpResponse; this.timeStamp = System.currentTimeMillis(); this.serverAdapter = adapter; this.elapsedTime = calculateElapsedTime(); } /** * Returns the underlying HttpServletRequest. After serialization the returned * value will be null. * * @return */ @Override public HttpServletRequest getRequest() { return httpRequest; } /** * Returns the underlying HttpServletResponse. After serialization the returned * value will be null. * * @return */ @Override public HttpServletResponse getResponse() { return httpResponse; } @Override public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { if (this.timeStamp != 0) { throw new IllegalStateException( "timeStamp has been already set for this event."); } else { this.timeStamp = timeStamp; } } @Override public String getRequestURI() { if (requestURI == null) { if (httpRequest != null) { requestURI = httpRequest.getRequestURI(); } else { requestURI = NA; } } return requestURI; } /** * The first line of the request. */ @Override public String getRequestURL() { if (requestURL == null) { if (httpRequest != null) { StringBuilder buf = new StringBuilder(); buf.append(httpRequest.getMethod()); buf.append(AccessConverter.SPACE_CHAR); buf.append(httpRequest.getRequestURI()); final String qStr = httpRequest.getQueryString(); if (qStr != null) { buf.append(AccessConverter.QUESTION_CHAR); buf.append(qStr); } buf.append(AccessConverter.SPACE_CHAR); buf.append(httpRequest.getProtocol()); requestURL = buf.toString(); } else { requestURL = NA; } } return requestURL; } @Override public String getRemoteHost() { if (remoteHost == null) { if (httpRequest != null) { // the underlying implementation of HttpServletRequest will // determine if remote lookup will be performed remoteHost = httpRequest.getRemoteHost(); } else { remoteHost = NA; } } return remoteHost; } @Override public String getRemoteUser() { if (remoteUser == null) { if (httpRequest != null) { remoteUser = httpRequest.getRemoteUser(); } else { remoteUser = NA; } } return remoteUser; } @Override public String getProtocol() { if (protocol == null) { if (httpRequest != null) { protocol = httpRequest.getProtocol(); } else { protocol = NA; } } return protocol; } @Override public String getMethod() { if (method == null) { if (httpRequest != null) { method = httpRequest.getMethod(); } else { method = NA; } } return method; } @Override public String getServerName() { if (serverName == null) { if (httpRequest != null) { serverName = httpRequest.getServerName(); } else { serverName = NA; } } return serverName; } @Override public String getRemoteAddr() { if (remoteAddr == null) { if (httpRequest != null) { remoteAddr = httpRequest.getRemoteAddr(); } else { remoteAddr = NA; } } return remoteAddr; } @Override public String getRequestHeader(String key) { String result = null; key = key.toLowerCase(); if (requestHeaderMap == null) { if (httpRequest != null) { buildRequestHeaderMap(); result = requestHeaderMap.get(key); } } else { result = requestHeaderMap.get(key); } if (result != null) { return result; } else { return NA; } } @Override public Enumeration getRequestHeaderNames() { // post-serialization if (httpRequest == null) { Vector<String> list = new Vector<String>(getRequestHeaderMap().keySet()); return list.elements(); } return httpRequest.getHeaderNames(); } @Override public Map<String, String> getRequestHeaderMap() { if (requestHeaderMap == null) { buildRequestHeaderMap(); } return requestHeaderMap; } public void buildRequestHeaderMap() { // according to RFC 2616 header names are case insensitive // latest versions of Tomcat return header names in lower-case requestHeaderMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); Enumeration e = httpRequest.getHeaderNames(); if (e == null) { return; } while (e.hasMoreElements()) { String key = (String) e.nextElement(); requestHeaderMap.put(key, httpRequest.getHeader(key)); } } public void buildRequestParameterMap() { requestParameterMap = new HashMap<String, String[]>(); Enumeration e = httpRequest.getParameterNames(); if (e == null) { return; } while (e.hasMoreElements()) { String key = (String) e.nextElement(); requestParameterMap.put(key, httpRequest.getParameterValues(key)); } } @Override public Map<String, String[]> getRequestParameterMap() { if (requestParameterMap == null) { buildRequestParameterMap(); } return requestParameterMap; } @Override public String getAttribute(String key) { Object value = null; if (attributeMap != null) { // Event was prepared for deferred processing so we have a copy of attribute map and must use that copy value = attributeMap.get(key); } else if (httpRequest != null) { // We have original request so take attribute from it value = httpRequest.getAttribute(key); } return value != null ? value.toString() : NA; } private void copyAttributeMap() { if (httpRequest == null) { return; } attributeMap = new HashMap<String, Object>(); Enumeration<String> names = httpRequest.getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Object value = httpRequest.getAttribute(name); if (shouldCopyAttribute(name, value)) { attributeMap.put(name, value); } } } private boolean shouldCopyAttribute(String name, Object value) { if (AccessConstants.LB_INPUT_BUFFER.equals(name) || AccessConstants.LB_OUTPUT_BUFFER.equals(name)) { // Do not copy attributes used by logback internally - these are available via other getters anyway return false; } else if (value == null) { // No reasons to copy nulls - Map.get() will return null for missing keys and the list of attribute // names is not available through IAccessEvent return false; } else { // Only copy what is serializable return value instanceof Serializable; } } @Override public String[] getRequestParameter(String key) { if (httpRequest != null) { String[] value = httpRequest.getParameterValues(key); if (value == null) { return new String[]{ NA }; } else { return value; } } else { return new String[]{ NA }; } } @Override public String getCookie(String key) { if (httpRequest != null) { Cookie[] cookieArray = httpRequest.getCookies(); if (cookieArray == null) { return NA; } for (Cookie cookie : cookieArray) { if (key.equals(cookie.getName())) { return cookie.getValue(); } } } return NA; } @Override public long getContentLength() { if (contentLength == SENTINEL) { if (httpResponse != null) { contentLength = serverAdapter.getContentLength(); return contentLength; } } return contentLength; } public int getStatusCode() { if (statusCode == SENTINEL) { if (httpResponse != null) { statusCode = serverAdapter.getStatusCode(); } } return statusCode; } public long getElapsedTime() { return elapsedTime; } private long calculateElapsedTime() { if (serverAdapter.getRequestTimestamp() < 0) { return -1; } return getTimeStamp() - serverAdapter.getRequestTimestamp(); } public String getRequestContent() { if (requestContent != null) { return requestContent; } if (Util.isFormUrlEncoded(httpRequest)) { StringBuilder buf = new StringBuilder(); Enumeration pramEnumeration = httpRequest.getParameterNames(); // example: id=1234&user=cgu // number=1233&x=1 int count = 0; try { while (pramEnumeration.hasMoreElements()) { String key = (String) pramEnumeration.nextElement(); if (count++ != 0) { buf.append("&"); } buf.append(key); buf.append("="); String val = httpRequest.getParameter(key); if (val != null) { buf.append(val); } else { buf.append(""); } } } catch (Exception e) { // FIXME Why is try/catch required? e.printStackTrace(); } requestContent = buf.toString(); } else { // retrieve the byte array placed by TeeFilter byte[] inputBuffer = (byte[]) httpRequest .getAttribute(AccessConstants.LB_INPUT_BUFFER); if (inputBuffer != null) { requestContent = new String(inputBuffer); } if (requestContent == null || requestContent.length() == 0) { requestContent = EMPTY; } } return requestContent; } public String getResponseContent() { if (responseContent != null) { return responseContent; } if (Util.isImageResponse(httpResponse)) { responseContent = "[IMAGE CONTENTS SUPPRESSED]"; } else { // retreive the byte array previously placed by TeeFilter byte[] outputBuffer = (byte[]) httpRequest .getAttribute(AccessConstants.LB_OUTPUT_BUFFER); if (outputBuffer != null) { responseContent = new String(outputBuffer); } if (responseContent == null || responseContent.length() == 0) { responseContent = EMPTY; } } return responseContent; } public int getLocalPort() { if (localPort == SENTINEL) { if (httpRequest != null) { localPort = httpRequest.getLocalPort(); } } return localPort; } public ServerAdapter getServerAdapter() { return serverAdapter; } public String getResponseHeader(String key) { buildResponseHeaderMap(); return responseHeaderMap.get(key); } void buildResponseHeaderMap() { if (responseHeaderMap == null) { responseHeaderMap = serverAdapter.buildResponseHeaderMap(); } } public Map<String, String> getResponseHeaderMap() { buildResponseHeaderMap(); return responseHeaderMap; } public List<String> getResponseHeaderNameList() { buildResponseHeaderMap(); return new ArrayList<String>(responseHeaderMap.keySet()); } public void prepareForDeferredProcessing() { getRequestHeaderMap(); getRequestParameterMap(); getResponseHeaderMap(); getLocalPort(); getMethod(); getProtocol(); getRemoteAddr(); getRemoteHost(); getRemoteUser(); getRequestURI(); getRequestURL(); getServerName(); getTimeStamp(); getElapsedTime(); getStatusCode(); getContentLength(); getRequestContent(); getResponseContent(); copyAttributeMap(); } }
mit
vontell/EasyAPI
build/resources/main/appalounge/APPAAnnounce.java
2768
package appalounge; import org.json.JSONArray; import org.json.JSONObject; import resources.Constructors; import resources.exceptions.ApiException; import resources.exceptions.AuthRequiredException; import resources.exceptions.BadRequestException; import resources.exceptions.DataNotSetException; import resources.infrastructure.EasyApiComponent; /** * Returns an array of the announcements made on APPA Lounge * @author Aaron Vontell * @date 10/16/2015 * @version 0.1 */ public class APPAAnnounce implements EasyApiComponent{ private String url = ""; private JSONArray result; private String[] message; private String[] creator; private String[] created; /** * Create an announcement object */ protected APPAAnnounce() { url = AppaLounge.BASE_URL + "announcements/2/"; } /** * Downloads and parses all data from the given information */ @Override public void downloadData() throws ApiException, BadRequestException, DataNotSetException, AuthRequiredException { try { result = Constructors.constructJSONArray(url); message = new String[result.length()]; creator = new String[result.length()]; created = new String[result.length()]; for(int i = 0; i < result.length(); i++){ String mes = result.getJSONObject(i).getString("message"); String user = result.getJSONObject(i).getString("creator"); String date = result.getJSONObject(i).getString("created"); message[i] = mes; creator[i] = user; created[i] = date; } } catch (Exception e) { throw new ApiException("API Error: " + result.toString()); } } /** * Get the number of announcements * @return announcement amount */ public int getNumAnnouncements(){ return message.length; } /** * Get the message at a certain index * @param i The num message to get * @return The message at that position */ public String getMessageAt(int i){ return message[i]; } /** * Get the user at a certain index * @param i The num user to get * @return The user at that position */ public String getCreatorAt(int i){ return creator[i]; } /** * Get the date at a certain index * @param i The num date to get * @return The date at that position */ public String getCreatedAt(int i){ return created[i]; } @Override public String getRawData() { if(result != null){ return result.toString(); } else { return "No data"; } } }
mit
CarlisleChan/Incubators
app/src/main/java/com/carlisle/incubators/PopupWindow/PopupWindowActivity.java
728
package com.carlisle.incubators.PopupWindow; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.carlisle.incubators.R; /** * Created by chengxin on 11/24/16. */ public class PopupWindowActivity extends AppCompatActivity { private PopupView popupView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_popup_window); popupView = new PopupView(this); } public void onButtonClick(View view) { //popupView.showAsDropDown(view); popupView.showAsDropUp(view); } }
mit
plast-lab/DelphJ
examples/berkeleydb/com/sleepycat/persist/evolve/EntityConverter.java
2735
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: EntityConverter.java,v 1.11 2008/01/07 14:28:58 cwl Exp $ */ package com.sleepycat.persist.evolve; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * A subclass of Converter that allows specifying keys to be deleted. * * <p>When a Converter is used with an entity class, secondary keys cannot be * automatically deleted based on field deletion, because field Deleter objects * are not used in conjunction with a Converter mutation. The EntityConverter * can be used instead of a plain Converter to specify the key names to be * deleted.</p> * * <p>It is not currently possible to rename or insert secondary keys when * using a Converter mutation with an entity class.</p> * * @see Converter * @see com.sleepycat.persist.evolve Class Evolution * @author Mark Hayes */ public class EntityConverter extends Converter { private static final long serialVersionUID = -988428985370593743L; private Set<String> deletedKeys; /** * Creates a mutation for converting all instances of the given entity * class version to the current version of the class. */ public EntityConverter(String entityClassName, int classVersion, Conversion conversion, Set<String> deletedKeys) { super(entityClassName, classVersion, null, conversion); /* Eclipse objects to assigning with a ternary operator. */ if (deletedKeys != null) { this.deletedKeys = new HashSet(deletedKeys); } else { this.deletedKeys = Collections.emptySet(); } } /** * Returns the set of key names that are to be deleted. */ public Set<String> getDeletedKeys() { return Collections.unmodifiableSet(deletedKeys); } /** * Returns true if the deleted and renamed keys are equal in this object * and given object, and if the {@link Converter#equals} superclass method * returns true. */ @Override public boolean equals(Object other) { if (other instanceof EntityConverter) { EntityConverter o = (EntityConverter) other; return deletedKeys.equals(o.deletedKeys) && super.equals(other); } else { return false; } } @Override public int hashCode() { return deletedKeys.hashCode() + super.hashCode(); } @Override public String toString() { return "[EntityConverter " + super.toString() + " DeletedKeys: " + deletedKeys + ']'; } }
mit
wolfposd/jadexphoto
photoeffect/src/photoeffect/effect/otherblur/IEffectOtherBlur.java
198
package photoeffect.effect.otherblur; import java.awt.image.BufferedImage; import measure.generic.IGenericWorkload; public interface IEffectOtherBlur extends IGenericWorkload<BufferedImage> { }
mit
JShadowMan/package
java/concurrency-arts/src/main/java/com/wjiec/learn/reordering/SynchronizedThreading.java
357
package com.wjiec.learn.reordering; public class SynchronizedThreading { private int number = 0; private boolean flag = false; public synchronized void write() { number = 1; flag = true; } public synchronized int read() { if (flag) { return number * number; } return -1; } }
mit
Blaubot/Blaubot
blaubot-android/src/main/java/eu/hgross/blaubot/android/views/KingdomView.java
6132
package eu.hgross.blaubot.android.views; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import eu.hgross.blaubot.admin.AbstractAdminMessage; import eu.hgross.blaubot.admin.CensusMessage; import eu.hgross.blaubot.android.R; import eu.hgross.blaubot.core.Blaubot; import eu.hgross.blaubot.core.IBlaubotConnection; import eu.hgross.blaubot.core.State; import eu.hgross.blaubot.core.acceptor.IBlaubotConnectionManagerListener; import eu.hgross.blaubot.core.statemachine.IBlaubotConnectionStateMachineListener; import eu.hgross.blaubot.core.statemachine.states.IBlaubotState; import eu.hgross.blaubot.messaging.IBlaubotAdminMessageListener; import eu.hgross.blaubot.ui.IBlaubotDebugView; /** * Android view to display informations about the StateMachine's state. * * Add this view to a blaubot instance like this: stateView.registerBlaubotInstance(blaubot); * * @author Henning Gross {@literal (mail.to@henning-gross.de)} * */ public class KingdomView extends LinearLayout implements IBlaubotDebugView { private Handler mUiHandler; private Blaubot mBlaubot; private Context mContext; public KingdomView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public KingdomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); } private void initView(Context context) { this.mContext = context; mUiHandler = new Handler(Looper.getMainLooper()); } private final static String NO_CENSUS_MESSAGE_SO_FAR_TEXT = "Got no census message so far"; private void updateUI(final CensusMessage censusMessage) { mUiHandler.post(new Runnable() { @Override public void run() { final List<View> stateItems = new ArrayList<>(); if(censusMessage != null) { final Set<Entry<String, State>> entries = censusMessage.getDeviceStates().entrySet(); for(Entry<String, State> entry : entries) { final String uniqueDeviceId = entry.getKey(); final State state = entry.getValue(); View item = createKingdomViewListItem(mContext, state, uniqueDeviceId); stateItems.add(item); } } // Never got a message if(stateItems.isEmpty()) { TextView tv = new TextView(mContext); tv.setText(NO_CENSUS_MESSAGE_SO_FAR_TEXT); stateItems.add(tv); } removeAllViews(); for(View v : stateItems) { addView(v); } } }); } /** * Creates a kingdom view list item * * @param context the context * @param state the state of the device to visualize * @param uniqueDeviceId the unique device id * @return the constructed view */ public static View createKingdomViewListItem(Context context, State state, String uniqueDeviceId) { final Drawable icon = ViewUtils.getDrawableForBlaubotState(context, state); View item = inflate(context, R.layout.blaubot_kingdom_view_list_item, null); TextView uniqueDeviceIdTextView = (TextView) item.findViewById(R.id.uniqueDeviceIdLabel); TextView stateTextView = (TextView) item.findViewById(R.id.stateLabel); ImageView iconImageView = (ImageView) item.findViewById(R.id.stateIcon); iconImageView.setImageDrawable(icon); uniqueDeviceIdTextView.setText(uniqueDeviceId); stateTextView.setText(state.toString()); return item; } private IBlaubotConnectionManagerListener mConnectionManagerListener = new IBlaubotConnectionManagerListener() { @Override public void onConnectionClosed(IBlaubotConnection connection) { } @Override public void onConnectionEstablished(IBlaubotConnection connection) { } }; private IBlaubotConnectionStateMachineListener mBlaubotConnectionStateMachineListener = new IBlaubotConnectionStateMachineListener() { @Override public void onStateChanged(IBlaubotState oldState, final IBlaubotState state) { if(State.getStateByStatemachineClass(state.getClass()) == State.Free) { updateUI(null); } } @Override public void onStateMachineStopped() { updateUI(null); } @Override public void onStateMachineStarted() { } }; private IBlaubotAdminMessageListener connectionLayerAdminMessageListener = new IBlaubotAdminMessageListener() { @Override public void onAdminMessage(AbstractAdminMessage adminMessage) { if(adminMessage instanceof CensusMessage) { updateUI((CensusMessage) adminMessage); } } }; /** * Register this view with the given blaubot instance * * @param blaubot * the blaubot instance to connect with */ @Override public void registerBlaubotInstance(Blaubot blaubot) { if (mBlaubot != null) { unregisterBlaubotInstance(); } this.mBlaubot = blaubot; this.mBlaubot.getConnectionStateMachine().addConnectionStateMachineListener(mBlaubotConnectionStateMachineListener); this.mBlaubot.getChannelManager().addAdminMessageListener(connectionLayerAdminMessageListener); this.mBlaubot.getConnectionManager().addConnectionListener(mConnectionManagerListener); // update updateUI(null); } @Override public void unregisterBlaubotInstance() { if(mBlaubot != null) { this.mBlaubot.getConnectionStateMachine().removeConnectionStateMachineListener(mBlaubotConnectionStateMachineListener); this.mBlaubot.getChannelManager().removeAdminMessageListener(connectionLayerAdminMessageListener); this.mBlaubot.getConnectionManager().removeConnectionListener(mConnectionManagerListener); } // force some updates updateUI(null); } }
mit
gabrielnobregal/mjcide
src/MicroJava/TestParserSemantic.java
13139
/* MicroJava Parser Semantic Tester * * Test only semantics. The grammar in all tests are correct. */ package MicroJava; import java.io.*; public class TestParserSemantic { public static void main(String args[]) { if (args.length == 0) { executeTests(); } else { for (int i = 0; i < args.length; ++i) { reportFile(args[i]); } } } private static void reportFile(String filename) { try { report("File: " + filename, new InputStreamReader(new FileInputStream(filename))); } catch (IOException e) { System.out.println("-- cannot open file " + filename); } } private static void report(String header, Reader reader) { System.out.println(header); Parser parser = new Parser(reader); parser.parse(); System.out.println(parser.errors + " errors detected\n"); } private static Parser createParser(String input) { Parser parser = new Parser(new StringReader(input)); parser.showSemanticError = true; parser.code.showError = false; parser.scan(); // get first token return parser; } private static void executeTests() { testClassDecl(); testCondition(); testConstDecl(); testDesignator(); testExpr(); testFactor(); testFormPars(); testMethodDecl(); testProgram(); testStatement(); testTerm(); testType(); testVarDecl(); } private static void testClassDecl() { System.out.println("Test: ClassDecl"); createParser("class A {}").ClassDecl(); createParser("class B { int b; }").ClassDecl(); createParser("class C { int c1; char[] c2; }").ClassDecl(); createParser("class D {} class E { D d; }").ClassDecl().ClassDecl(); System.out.println("Test: ClassDecl errors"); createParser("class int {}").ClassDecl(); createParser("class char {}").ClassDecl(); createParser("class F { F[] f; }").ClassDecl(); createParser("class H { int H; }").ClassDecl(); createParser("class J { int j; char j; }").ClassDecl(); // invalid type (X not declared) createParser("class K { X k; }").ClassDecl(); // atribute name is the same of the type of variable createParser("class L {} class M { L L; }").ClassDecl().ClassDecl(); createParser("class N { N N; }").ClassDecl(); System.out.println(); } private static void testCondition() { System.out.println("Test: Condition"); createParser("2 == 3").Condition(); createParser("int[] a, b; a == b").VarDecl().Condition(); createParser("char[] c, d; c != d").VarDecl().Condition(); createParser("class E{} E e, f; e == f e != f") .ClassDecl().VarDecl().Condition().Condition(); System.out.println("Test: Condition errors"); createParser("2 + 3 == 'a'").Condition(); createParser("int[] ia, ib; ia > ib").VarDecl().Condition(); createParser("class X{} X x, y; x <= y").ClassDecl().VarDecl().Condition(); createParser("class W{ int[] a; } W w; int[] b; w.a <= b") .ClassDecl().VarDecl().VarDecl().Condition(); createParser("class Z{} Z z; int[] r; r == z") .ClassDecl().VarDecl().VarDecl().Condition(); System.out.println(); } private static void testConstDecl() { System.out.println("Test: ConstDecl"); createParser("final int b = 2;").ConstDecl(); createParser("final char c = 'c';").ConstDecl(); System.out.println("Test: ConstDecl errors"); createParser("final int d = 'd';").ConstDecl(); createParser("final char e = 1;").ConstDecl(); // array is not accept createParser("final int[] f = 1;").ConstDecl(); createParser("final char[] g = 'g';").ConstDecl(); System.out.println(); } private static void testDesignator() { System.out.println("Test: Designator"); createParser("class A {} A a; a = new A; a") .ClassDecl().VarDecl().Statement().Designator(); createParser("class B { int bb; } B b; b = new B; b.bb") .ClassDecl().VarDecl().Statement().Designator(); createParser("class C { char c1; int c2; } C c; c = new C; c.c1 c.c2") .ClassDecl().VarDecl().Statement().Designator().Designator(); createParser("int[] d; d[2]").VarDecl().Designator(); System.out.println("Test: Designator errors"); createParser("int x; x.y").VarDecl().Designator(); createParser("class M { int m; } M.m").ClassDecl().Designator(); System.out.println(); } private static void testExpr() { System.out.println("Test: Expr"); createParser("2 + 3").Expr(); createParser("-4").Expr(); createParser("-5 * 6").Expr(); createParser("int a; a * 6").VarDecl().Expr(); createParser("int b, c, d; b * 6 + c * d").VarDecl().Expr(); System.out.println("Test: Expr errors"); createParser("-'a'").Expr(); createParser("-2 * 'b'").Expr(); createParser("-3 * 'c' * 4").Expr(); createParser("-5 * 'd' * 6 + 7").Expr(); createParser("char e; e - 'f' % 'g'").VarDecl().Expr(); createParser("void m(){} m + 8").MethodDecl().Expr(); System.out.println(); } private static void testFactor() { System.out.println("Test: Factor"); // new createParser("new int[2]").Factor(); createParser("int size; new char[size]").VarDecl().Factor(); createParser("class A {} new A").ClassDecl().Factor(); createParser("class B {} new B[2]").ClassDecl().Factor(); // designator: variable createParser("int i; i").VarDecl().Factor(); // designator: method */ createParser("int m1(int i, int j) {} m1(2, 3)").MethodDecl().Factor(); System.out.println("Test: Factor errors"); // new createParser("new int").Factor(); createParser("new char").Factor(); createParser("new X").Factor(); createParser("new Y[2]").Factor(); createParser("class G {} new G['b']").ClassDecl().Factor(); // designator: variable createParser("int w; w()").VarDecl().Factor(); // designator: method createParser("int me1() {} me1(1)").MethodDecl().Factor(); createParser("int me2(int i, int j) {} me2(2)").MethodDecl().Factor(); createParser("char me3(char c) {} me3(3)").MethodDecl().Factor(); createParser("char me4(int i, int j, char k) {} me4(4, 'c', 6)").MethodDecl().Factor(); // void methods (procedures) cannot be used in a expression context. // Factor is always called in an expression context (Expr -> Term -> Factor) createParser("void m5() {} m5()").MethodDecl().Factor(); createParser("void m6(char c) {} m6('c')").MethodDecl().Factor(); System.out.println(); } private static void testFormPars() { System.out.println("Test: FormPars"); createParser("int i, char c, int[] ia, char[] ca").FormPars(); createParser("class A {} A a, A[] aa").ClassDecl().FormPars(); System.out.println("Test: FormPars errors"); createParser("int char, int char").FormPars(); createParser("B b, C[] c").FormPars(); System.out.println(); } private static void testMethodDecl() { System.out.println("Test: MethodDecl"); createParser("int[] a(int[] ia, char[] ca) int i; char c; {}").MethodDecl(); createParser("void b() int i; char c; {}").MethodDecl(); createParser("class C {} \n C c() {}").ClassDecl().MethodDecl(); createParser("class D {} \n D[] d(D dp) D dv; {}").ClassDecl().MethodDecl(); System.out.println("Test: MethodDecl errors"); createParser("int char() {}").MethodDecl(); createParser("void m(G g) {}").MethodDecl(); System.out.println(); } private static void testProgram() { System.out.println("Test: Program"); createParser("program P { void main() {} }").Program(); createParser("program ABC {" + " void f() {}" + " void main() { return ; }" + " int g(int x) { return x*2; }" + " }").Program(); System.out.println("Test: Program errors"); createParser("program E1 { }").Program(); createParser("program E2 { int main() { } }").Program(); createParser("program E3 { void main(int i) { } }").Program(); System.out.println(); } private static void testStatement() { System.out.println("Test: Statement"); // Designator "=" Expr ";" createParser("int b; b = 2;").VarDecl().Statement(); createParser("char c, d; c = d;").VarDecl().Statement(); createParser("int[] e; e[3] = 3;").VarDecl().Statement(); createParser("class A { int i; } A a; a.i = 4;").ClassDecl().VarDecl().Statement(); createParser("int[] ia; ia = new int[5];").VarDecl().Statement(); createParser("char[] ca; ca = new char[6];").VarDecl().Statement(); // Designator ActPars ";" createParser("void f() {} f();").MethodDecl().Statement(); // "print" "(" Expr ["," number] ")" ";" createParser("print(2); print('c');").Statement().Statement(); createParser("print(3, 4);").Statement(); // "read" "(" Designator ")" ";" createParser("int i; read(i);").VarDecl().Statement(); createParser("char c; read(c);").VarDecl().Statement(); createParser("char[] ca; read(ca[2]);").VarDecl().Statement(); createParser("class C {int i;} C o; read(o.i);").ClassDecl().VarDecl().Statement(); // "return" [Expr] ";" createParser("void f() { return ;}").MethodDecl(); createParser("int g() { return 2;}").MethodDecl(); createParser("char h() { return 'c';}").MethodDecl(); System.out.println("Test: Statement errors"); // Designator "=" Expr createParser("int b; b = 'c';").VarDecl().Statement(); createParser("char[] c; c[4] = 4;").VarDecl().Statement(); createParser("class A { int i; } A a; a.i = '4';").ClassDecl().VarDecl().Statement(); createParser("int[] ia; ia = new char[5];").VarDecl().Statement(); createParser("char[] ca; ca = new int[6];").VarDecl().Statement(); // Designator ActPars createParser("int g; g();").VarDecl().Statement(); // "print" "(" Expr ["," number] ")" ";" createParser("class C {} C c; print(c);").ClassDecl().VarDecl().Statement(); createParser("print(5, 'd');").Statement(); // "read" "(" Designator ")" ";" createParser("class C {} C c; read(c);").ClassDecl().VarDecl().Statement(); // "return" [Expr] ";" createParser("void p() { return 1; }").MethodDecl(); createParser("int q() { return 'c';}").MethodDecl(); createParser("char r() { return 2;}").MethodDecl(); createParser("int s() { return ;}").MethodDecl(); System.out.println(); } private static void testTerm() { System.out.println("Test: Term"); createParser("2 * 3").Term(); createParser("4").Term(); createParser("5 * (-6)").Term(); createParser("'a'").Term(); createParser("int a, b; a * (-7) * b").VarDecl().Term(); createParser("char a; a").VarDecl().Term(); System.out.println("Test: Term errors"); createParser("2 * 'b'").Term(); createParser("'c' * 3").Term(); createParser("char d; d * 'e'").VarDecl().Term(); System.out.println(); } private static void testType() { System.out.println("Test: Type"); createParser("int").Type(); createParser("int[]").Type(); createParser("char").Type(); createParser("char[]").Type(); createParser("class A {} A").ClassDecl().Type(); System.out.println("Test: Type errors"); createParser("class").Type(); createParser("MyClass").Type(); System.out.println(); } private static void testVarDecl() { System.out.println("Test: VarDecl"); createParser("int x;").VarDecl(); createParser("int x, y;").VarDecl(); createParser("int x, X;").VarDecl(); // case-sensitive variables createParser("int x, y, z, X, Y, Z;").VarDecl(); System.out.println("Test: VarDecl errors"); createParser("int int;").VarDecl(); createParser("int char;").VarDecl(); createParser("char int;").VarDecl(); createParser("char char;").VarDecl(); createParser("int s, s;").VarDecl(); createParser("int t, char, t, int;").VarDecl(); createParser("int x, w, p, q, r, w;").VarDecl(); System.out.println(); } }
mit