repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
shitalm/jsignpdf2
src/main/java/com/lowagie/text/Cell.java
21862
/* * $Id: Cell.java,v 1.1 2010/04/14 17:50:35 kwart Exp $ * * Copyright 1999, 2000, 2001, 2002 by Bruno Lowagie. * * The contents of this file are subject to the Mozilla Public License Version 1.1 * (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the License. * * The Original Code is 'iText, a free JAVA-PDF library'. * * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. * All Rights Reserved. * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. * * Contributor(s): all the names of the contributors are added in the source code * where applicable. * * Alternatively, the contents of this file may be used under the terms of the * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * provisions of LGPL are applicable instead of those above. If you wish to * allow use of your version of this file only under the terms of the LGPL * License and not to allow others to use your version of this file under * the MPL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the LGPL. * If you do not delete the provisions above, a recipient may use your version * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. * * This library is free software; you can redistribute it and/or modify it * under the terms of the MPL as stated above or under the terms of the GNU * Library General Public License as published by the Free Software Foundation; * either version 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more * details. * * If you didn't download this code from the following link, you should check if * you aren't using an obsolete version: * http://www.lowagie.com/iText/ */ package com.lowagie.text; import java.util.ArrayList; import java.util.Iterator; import com.lowagie.text.pdf.PdfPCell; /** * A <CODE>Cell</CODE> is a <CODE>Rectangle</CODE> containing other * <CODE>Element</CODE>s. * <P> * A <CODE>Cell</CODE> must be added to a <CODE>Table</CODE>. * The <CODE>Table</CODE> will place the <CODE>Cell</CODE> in * a <CODE>Row</CODE>. * <P> * Example: * <BLOCKQUOTE><PRE> * Table table = new Table(3); * table.setBorderWidth(1); * table.setBorderColor(new Color(0, 0, 255)); * table.setCellpadding(5); * table.setCellspacing(5); * <STRONG>Cell cell = new Cell("header");</STRONG> * <STRONG>cell.setHeader(true);</STRONG> * <STRONG>cell.setColspan(3);</STRONG> * table.addCell(cell); * <STRONG>cell = new Cell("example cell with colspan 1 and rowspan 2");</STRONG> * <STRONG>cell.setRowspan(2);</STRONG> * <STRONG>cell.setBorderColor(new Color(255, 0, 0));</STRONG> * table.addCell(cell); * table.addCell("1.1"); * table.addCell("2.1"); * table.addCell("1.2"); * table.addCell("2.2"); * </PRE></BLOCKQUOTE> * * @see Rectangle * @see Element * @see Table * @see Row */ public class Cell extends Rectangle implements TextElementArray { // membervariables /** * The <CODE>ArrayList</CODE> of <CODE>Element</CODE>s * that are part of the content of the Cell. */ protected ArrayList arrayList = null; /** The horizontal alignment of the cell content. */ protected int horizontalAlignment = Element.ALIGN_UNDEFINED; /** The vertical alignment of the cell content. */ protected int verticalAlignment = Element.ALIGN_UNDEFINED; /** * The width of the cell as a String. * It can be an absolute value "100" or a percentage "20%". */ protected float width; protected boolean percentage = false; /** The colspan of the cell. */ protected int colspan = 1; /** The rowspan of the cell. */ protected int rowspan = 1; /** The leading of the content inside the cell. */ float leading = Float.NaN; /** Is this <CODE>Cell</CODE> a header? */ protected boolean header; /** * Maximum number of lines allowed in the cell. * The default value of this property is not to limit the maximum number of lines * (contributed by dperezcar@fcc.es) */ protected int maxLines = Integer.MAX_VALUE; /** * If a truncation happens due to the maxLines property, then this text will * be added to indicate a truncation has happened. * Default value is null, and means avoiding marking the truncation. * A useful value of this property could be e.g. "..." * (contributed by dperezcar@fcc.es) */ String showTruncation; /** * Indicates that the largest ascender height should be used to determine the * height of the first line. Note that this only has an effect when rendered * to PDF. Setting this to true can help with vertical alignment problems. */ protected boolean useAscender = false; /** * Indicates that the largest descender height should be added to the height of * the last line (so characters like y don't dip into the border). Note that * this only has an effect when rendered to PDF. */ protected boolean useDescender = false; /** * Adjusts the cell contents to compensate for border widths. Note that * this only has an effect when rendered to PDF. */ protected boolean useBorderPadding; /** Does this <CODE>Cell</CODE> force a group change? */ protected boolean groupChange = true; // constructors /** Constructs an empty <CODE>Cell</CODE>. */ public Cell() { // creates a Rectangle with BY DEFAULT a border of 0.5 super(0, 0, 0, 0); setBorder(UNDEFINED); setBorderWidth(0.5f); // initializes the arraylist arrayList = new ArrayList(); } /** * Constructs an empty <CODE>Cell</CODE> (for internal use only). * * @param dummy a dummy value */ public Cell(boolean dummy) { this(); arrayList.add(new Paragraph(0)); } /** * Constructs a <CODE>Cell</CODE> with a certain content.<p> * The <CODE>String</CODE> will be converted into a <CODE>Paragraph</CODE>. * @param content a <CODE>String</CODE> */ public Cell(String content) { this(); try { addElement(new Paragraph(content)); } catch(BadElementException bee) { } } /** * Constructs a <CODE>Cell</CODE> with a certain <CODE>Element</CODE>.<p> * if the element is a <CODE>ListItem</CODE>, <CODE>Row</CODE> or * <CODE>Cell</CODE>, an exception will be thrown. * * @param element the element * @throws BadElementException when the creator was called with a <CODE>ListItem</CODE>, <CODE>Row</CODE> or <CODE>Cell</CODE> */ public Cell(Element element) throws BadElementException { this(); if(element instanceof Phrase) { setLeading(((Phrase)element).getLeading()); } addElement(element); } // implementation of the Element-methods /** * Processes the element by adding it (or the different parts) to an * <CODE>ElementListener</CODE>. * * @param listener an <CODE>ElementListener</CODE> * @return <CODE>true</CODE> if the element was processed successfully */ public boolean process(ElementListener listener) { try { return listener.add(this); } catch(DocumentException de) { return false; } } /** * Gets the type of the text element. * * @return a type */ public int type() { return Element.CELL; } /** * Gets all the chunks in this element. * * @return an <CODE>ArrayList</CODE> */ public ArrayList getChunks() { ArrayList tmp = new ArrayList(); for (Iterator i = arrayList.iterator(); i.hasNext(); ) { tmp.addAll(((Element) i.next()).getChunks()); } return tmp; } // Getters and setters /** * Gets the horizontal alignment. * * @return a value */ public int getHorizontalAlignment() { return horizontalAlignment; } /** * Sets the horizontal alignment. * @param value the new value */ public void setHorizontalAlignment(int value) { horizontalAlignment = value; } /** * Sets the alignment of this cell. * This methods allows you to set the alignment as a String. * @param alignment the new alignment as a <CODE>String</CODE> */ public void setHorizontalAlignment(String alignment) { setHorizontalAlignment(ElementTags.alignmentValue(alignment)); } /** * Gets the vertical alignment. * @return a value */ public int getVerticalAlignment() { return verticalAlignment; } /** * Sets the vertical alignment. * @param value the new value */ public void setVerticalAlignment(int value) { verticalAlignment = value; } /** * Sets the alignment of this paragraph. * * @param alignment the new alignment as a <CODE>String</CODE> */ public void setVerticalAlignment(String alignment) { setVerticalAlignment(ElementTags.alignmentValue(alignment)); } /** * Sets the width. * * @param value the new value */ public void setWidth(float value) { this.width = value; } /** * Sets the width. * It can be an absolute value "100" or a percentage "20%" * * @param value the new value */ public void setWidth(String value) { if (value.endsWith("%")) { value = value.substring(0, value.length() - 1); percentage = true; } width = Integer.parseInt(value); } /** * Gets the width. */ public float getWidth() { return width; } /** * Gets the width as a String. * * @return a value */ public String getWidthAsString() { String w = String.valueOf(width); if (w.endsWith(".0")) w = w.substring(0, w.length() - 2); if (percentage) w += "%"; return w; } /** * Sets the colspan. * * @param value the new value */ public void setColspan(int value) { colspan = value; } /** * Gets the colspan. * @return a value */ public int getColspan() { return colspan; } /** * Sets the rowspan. * * @param value the new value */ public void setRowspan(int value) { rowspan = value; } /** * Gets the rowspan. * @return a value */ public int getRowspan() { return rowspan; } /** * Sets the leading. * * @param value the new value */ public void setLeading(float value) { leading = value; } /** * Gets the leading. * * @return a value */ public float getLeading() { if (Float.isNaN(leading)) { return 16; } return leading; } /** * Sets header. * * @param value the new value */ public void setHeader(boolean value) { header = value; } /** * Is this <CODE>Cell</CODE> a header? * * @return a value */ public boolean isHeader() { return header; } /** * Setter for maxLines * @param value the maximum number of lines */ public void setMaxLines(int value) { maxLines = value; } /** * Getter for maxLines * @return the maxLines value */ public int getMaxLines() { return maxLines; } /** * Setter for showTruncation * @param value Can be null for avoiding marking the truncation. */ public void setShowTruncation(String value) { showTruncation = value; } /** * Getter for showTruncation * @return the showTruncation value */ public String getShowTruncation() { return showTruncation; } /** * Sets the value of useAscender. * @param use use ascender height if true */ public void setUseAscender(boolean use) { useAscender = use; } /** * Gets the value of useAscender * @return useAscender */ public boolean isUseAscender() { return useAscender; } /** * Sets the value of useDescender. * @param use use descender height if true */ public void setUseDescender(boolean use) { useDescender = use; } /** * gets the value of useDescender * @return useDescender */ public boolean isUseDescender() { return useDescender; } /** * Sets the value of useBorderPadding. * @param use adjust layout for borders if true */ public void setUseBorderPadding(boolean use) { useBorderPadding = use; } /** * Gets the value of useBorderPadding. * @return useBorderPadding */ public boolean isUseBorderPadding() { return useBorderPadding; } /** * Does this <CODE>Cell</CODE> force a group change? * * @return a value */ public boolean getGroupChange() { return groupChange; } /** * Sets group change. * * @param value the new value */ public void setGroupChange(boolean value) { groupChange = value; } // arraylist stuff /** * Gets the number of <CODE>Element</CODE>s in the Cell. * * @return a <CODE>size</CODE>. */ public int size() { return arrayList.size(); } /** * Gets an iterator of <CODE>Element</CODE>s. * * @return an <CODE>Iterator</CODE>. */ public Iterator getElements() { return arrayList.iterator(); } /** * Clears all the <CODE>Element</CODE>s of this <CODE>Cell</CODE>. */ public void clear() { arrayList.clear(); } /** * Checks if the <CODE>Cell</CODE> is empty. * * @return <CODE>false</CODE> if there are non-empty <CODE>Element</CODE>s in the <CODE>Cell</CODE>. */ public boolean isEmpty() { switch(size()) { case 0: return true; case 1: Element element = (Element) arrayList.get(0); switch (element.type()) { case Element.CHUNK: return ((Chunk) element).isEmpty(); case Element.ANCHOR: case Element.PHRASE: case Element.PARAGRAPH: return ((Phrase) element).isEmpty(); case Element.LIST: return ((List) element).isEmpty(); } return false; default: return false; } } /** * Makes sure there is at least 1 object in the Cell. * * Otherwise it might not be shown in the table. */ void fill() { if (size() == 0) arrayList.add(new Paragraph(0)); } /** * Checks if this <CODE>Cell</CODE> is a placeholder for a (nested) table. * * @return true if the only element in this cell is a table */ public boolean isTable() { return (size() == 1) && (((Element)arrayList.get(0)).type() == Element.TABLE); } /** * Adds an element to this <CODE>Cell</CODE>. * <P> * Remark: you can't add <CODE>ListItem</CODE>s, <CODE>Row</CODE>s, <CODE>Cell</CODE>s, * <CODE>JPEG</CODE>s, <CODE>GIF</CODE>s or <CODE>PNG</CODE>s to a <CODE>Cell</CODE>. * * @param element The <CODE>Element</CODE> to add * @throws BadElementException if the method was called with a <CODE>ListItem</CODE>, <CODE>Row</CODE> or <CODE>Cell</CODE> */ public void addElement(Element element) throws BadElementException { if (isTable()) { Table table = (Table) arrayList.get(0); Cell tmp = new Cell(element); tmp.setBorder(NO_BORDER); tmp.setColspan(table.getColumns()); table.addCell(tmp); return; } switch(element.type()) { case Element.LISTITEM: case Element.ROW: case Element.CELL: throw new BadElementException("You can't add listitems, rows or cells to a cell."); case Element.LIST: List list = (List)element; if (Float.isNaN(leading)) { setLeading(list.getTotalLeading()); } if (list.isEmpty()) return; arrayList.add(element); return; case Element.ANCHOR: case Element.PARAGRAPH: case Element.PHRASE: Phrase p = (Phrase)element; if (Float.isNaN(leading)) { setLeading(p.getLeading()); } if (p.isEmpty()) return; arrayList.add(element); return; case Element.CHUNK: if (((Chunk) element).isEmpty()) return; arrayList.add(element); return; case Element.TABLE: Table table = new Table(3); float[] widths = new float[3]; widths[1] = ((Table)element).getWidth(); switch(((Table)element).getAlignment()) { case Element.ALIGN_LEFT: widths[0] = 0f; widths[2] = 100f - widths[1]; break; case Element.ALIGN_CENTER: widths[0] = (100f - widths[1]) / 2f; widths[2] = widths[0]; break; case Element.ALIGN_RIGHT: widths[0] = 100f - widths[1]; widths[2] = 0f; } table.setWidths(widths); Cell tmp; if (arrayList.isEmpty()) { table.addCell(getDummyCell()); } else { tmp = new Cell(); tmp.setBorder(NO_BORDER); tmp.setColspan(3); for (Iterator i = arrayList.iterator(); i.hasNext(); ) { tmp.add(i.next()); } table.addCell(tmp); } tmp = new Cell(); tmp.setBorder(NO_BORDER); table.addCell(tmp); table.insertTable((Table)element); tmp = new Cell(); tmp.setBorder(NO_BORDER); table.addCell(tmp); table.addCell(getDummyCell()); clear(); arrayList.add(table); return; default: arrayList.add(element); } } /** * Add an <CODE>Object</CODE> to this cell. * * @param o the object to add * @return always <CODE>true</CODE> */ public boolean add(Object o) { try { this.addElement((Element) o); return true; } catch(ClassCastException cce) { throw new ClassCastException("You can only add objects that implement the Element interface."); } catch(BadElementException bee) { throw new ClassCastException(bee.getMessage()); } } // helper methods /** * Get dummy cell used when merging inner tables. * @return a cell with colspan 3 and no border */ private static Cell getDummyCell() { Cell cell = new Cell(true); cell.setColspan(3); cell.setBorder(NO_BORDER); return cell; } /** * Creates a PdfPCell based on this Cell object. * @return a PdfPCell * @throws BadElementException */ public PdfPCell createPdfPCell() throws BadElementException { if (rowspan > 1) throw new BadElementException("PdfPCells can't have a rowspan > 1"); if (isTable()) return new PdfPCell(((Table)arrayList.get(0)).createPdfPTable()); PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(verticalAlignment); cell.setHorizontalAlignment(horizontalAlignment); cell.setColspan(colspan); cell.setUseBorderPadding(useBorderPadding); cell.setUseDescender(useDescender); cell.setLeading(getLeading(), 0); cell.cloneNonPositionParameters(this); cell.setNoWrap(getMaxLines() == 1); for (Iterator i = getElements(); i.hasNext(); ) { Element e = (Element)i.next(); if (e.type() == Element.PHRASE || e.type() == Element.PARAGRAPH) { Paragraph p = new Paragraph((Phrase)e); p.setAlignment(horizontalAlignment); e = p; } cell.addElement(e); } return cell; } // unsupported Rectangle methods /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @return NA */ public float getTop() { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @return NA */ public float getBottom() { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @return NA */ public float getLeft() { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @return NA */ public float getRight() { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param margin * @return NA */ public float top(int margin) { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param margin * @return NA */ public float bottom(int margin) { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param margin * @return NA */ public float left(int margin) { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param margin NA * @return NA */ public float right(int margin) { throw new UnsupportedOperationException("Dimensions of a Cell can't be calculated. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param value NA */ public void setTop(int value) { throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param value NA */ public void setBottom(int value) { throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param value NA */ public void setLeft(int value) { throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ."); } /** * This method throws an <CODE>UnsupportedOperationException</CODE>. * @param value NA */ public void setRight(int value) { throw new UnsupportedOperationException("Dimensions of a Cell are attributed automagically. See the FAQ."); } }
gpl-2.0
LeNiglo/TinyTank
ClientTinyTank/src/main/java/com/lefrantguillaume/components/taskComponent/TaskFactory.java
737
package com.lefrantguillaume.components.taskComponent; import com.lefrantguillaume.utils.stockage.Tuple; /** * Created by andres_k on 30/05/2015. */ public class TaskFactory { public static Tuple<EnumTargetTask, EnumTargetTask, Object> createTask(EnumTargetTask sender, Tuple<EnumTargetTask, EnumTargetTask, Object> task){ Tuple<EnumTargetTask, EnumTargetTask, Object> result = new Tuple<>(sender, task.getV2(), task.getV3()); return result; } public static Tuple<EnumTargetTask, EnumTargetTask, Object> createTask(EnumTargetTask sender, EnumTargetTask target, Object task){ Tuple<EnumTargetTask, EnumTargetTask, Object> result = new Tuple<>(sender, target, task); return result; } }
gpl-2.0
AlejusMaximus/androidProjects
Survey/src/apps101/aleix/survey/MainActivity.java
9325
package apps101.aleix.survey; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements TextWatcher { private static final String TAG = "MainActivity"; private EditText mName; private EditText mPhone; private EditText mEmail; private EditText mComments; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Look for these views after we've created them ! mName = (EditText) findViewById(R.id.name); mPhone = (EditText) findViewById(R.id.phone); mEmail = (EditText) findViewById(R.id.email); mComments = (EditText) findViewById(R.id.comments); // Create a pointer Text Watcher // Note: watcher object has a link to our activity // final MainActivity appContext = this; // mComments.addTextChangedListener(watcher); // After put the TextWatcher methods inside our Activity... mComments.addTextChangedListener(this); } // Now TextWatcher methods are declared inside the activity @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub String comments = s.toString(); String duck = getString(R.string.duck); boolean valid = comments.length() > 0 && (comments.toLowerCase().indexOf(duck) == -1); // If duck is written, then indexOf("duck") != -1. Then valid = false. View view = findViewById(R.id.imageButton1); //What could happened if... // View view = findViewById(R.drawable.duck); -> this is not the ID for something on the screen! // Then when the method view.getVisitibily runs on no object, so -> view = null -> Null Pointer Exception // We can find out if the duck is visible or not: boolean isVisible = view.getVisibility() == View.VISIBLE; if (isVisible == valid) { return; } Animation anim; if (valid) { view.setVisibility(View.VISIBLE); anim = AnimationUtils.makeInAnimation(this, true); } else { // if any object is created here, will only exist // between else{} brackets view.setVisibility(View.INVISIBLE); anim = AnimationUtils.makeOutAnimation(this, true); } view.startAnimation(anim); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void processForm(View duck) { // Uncomment - remove the // - from one of these methods! // And comment out - add // to the other two simpleExample(); // sendSMS(); // sendEmail(); } public void simpleExample() { // The simplest code to share a message.... Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, "What a wonderful app!"); startActivity(i); // But on real devices you will see many many matching options // including Bluetooth, Google drive... // And to be more robust you should catch ActivityNotFoundException... } public void sendSMS() { String comments = mComments.getText().toString(); String phone = mPhone.getText().toString(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.fromParts("sms", phone, null)); intent.putExtra("sms_body", comments); try { startActivity(intent); // startActivity can throw ActivityNotFoundException // So to be robust our app will catch the exception .. } catch (Exception ex) { // We could tell the user it didn't work e.g. with a Toast // Also we can print the exception message and stack trace in the // log... Log.e(TAG, "Could not send message", ex); } } public void sendEmail() { String comments = mComments.getText().toString(); String email = mEmail.getText().toString(); String phone = mPhone.getText().toString(); String name = mName.getText().toString(); String message = name + " says.. \n" + comments; if (phone.length() > 0) { message = message + "\nPhone:" + phone; } if (email.length() > 0) { message = message + "\nAlternative Email:" + email; } // FYI There's lots of discussion about email intents on StackOverflow // eg SEND vs SENDTO and setting the mimetype to message/rfc822 // Experimentally the following works on many devices // - Tested on Android 1.6 and 4.x phones, and tablets and 2.x,4.x // emulator. // You will need to configure the emulator's email client with a // real email address. // To test unsupported schemes change "mailto" to "horseback" Intent emailIntent = new Intent(Intent.ACTION_SENDTO); emailIntent.setData(Uri.fromParts("mailto", "feedback@myapp.somewhere...", null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "important news"); emailIntent.putExtra(Intent.EXTRA_TEXT, message); // Better .... use resolveActivity // We can check to see if there is a configured email client // BEFORE trying to start an activity // Using this test we could have prevented the user from ever opening // the survey... if (emailIntent.resolveActivity(getPackageManager()) == null) { Toast.makeText(getApplicationContext(), "Please configure your email client!", Toast.LENGTH_LONG) .show(); } else { // Secondly, use a chooser will gracefully handle 0,1,2+ matching // activities startActivity(Intent.createChooser(emailIntent, "Please choose your email app!")); } } public void processFormOriginal(View duck) { // Not used in this video // Validate and Animate String comments = mComments.getText().toString(); String email = mEmail.getText().toString(); String phone = mPhone.getText().toString(); String name = mName.getText().toString(); // Notice '=' means assign to the variable on the left // to the value of the right hand side int position = email.indexOf("@"); // Notice '==' means see if these integers are the same if (position == -1) { // Alternatively... if( ! email.contains("@") ) Toast.makeText(this.getApplicationContext(), "Invalid email address!", Toast.LENGTH_LONG).show(); mEmail.requestFocus(); return; } // You can ask a string for its length (number of characters) int len = comments.length(); // To see if two integer values are equal use == // But don't use == for Strings (see below)! if (len == 0) { Toast.makeText(this.getApplicationContext(), "Give me comments!", Toast.LENGTH_LONG).show(); mComments.requestFocus(); return; } // To see if two String objects are equal use the "equals" method // For String pointers, '==' compares two memory pointers to see if they // point to the same object // // if (name == "Fred") Not OK! (because name can point to a different // String object, that might also contain F-r-e-d) // // if( name == null) is OK for this special case of comparing with null // if (name.equals("Fred")) { Toast.makeText(this.getApplicationContext(), "Hi Fred!", Toast.LENGTH_LONG).show(); } // We might run into some surprises when we try to convert // a string to an integer value // Convert a string (a sequence of characters) "123123123" into an // integer value // Notice we declare these variables OUTSIDE the try-catch block // So we can use them after the catch block ends int value = -1; // we will change this boolean valueOK = false; // will become true if everything works out OK try { // The next line will throw an exception if it does not like our // string! // e.g. if phone is an empty string "3000000000" or "askdgahksdg" value = Integer.parseInt(phone); // We will skip this code if parseInt throws its // NumberFormatException // If everything goes to plan though we will just continue here... valueOK = true; // Change AFTER parseInt has returned Log.d(TAG, "Phone number:" + value); } catch (Exception e) { // Uh oh... We caught that nasty exception!! // (FYI More experienced programmers might choose to catch // NumberFormatException) Log.d(TAG, "Invalid Phone Number!? Could not be turned into an Java integer value" + phone); } if (valueOK) { Log.d(TAG, "Phone number as an integer value:" + value); } String username = email.substring(0, position); String thankyou = "Thankyou " + username + "!"; Toast.makeText(this.getApplicationContext(), thankyou, Toast.LENGTH_LONG).show(); // Move the duck to the right and fade it out Animation anim = AnimationUtils.makeOutAnimation(this, true); duck.startAnimation(anim); // // duck.setVisibility(View.INVISIBLE); // Toast.makeText(this.getApplicationContext(), R.string.app_name, // Toast.LENGTH_LONG).show(); } }
gpl-2.0
quchenhao/spot-auto-scaling
spot-auto-scaling-core/src/main/java/auto_scaling/configuration/ILimitsLoader.java
614
package auto_scaling.configuration; import java.io.InputStream; /** * @ClassName: ILimitsLoader * @Description: loader to load limits * @author Chenhao Qu * @date 04/06/2015 5:07:24 pm * */ public interface ILimitsLoader { static final String MINIMUM_ON_DEMAND_CAPACITY = "minimum_on_demand_limit"; static final String MAXIMUM_CHOSEN_SPOT_TYPES_LIMIT = "maximum_chosen_spot_types_limit"; /** * @Title: load * @Description: load from input stream * @param inputStream * @throws Exception * @throws */ public void load(InputStream inputStream) throws Exception; }
gpl-2.0
adamfisk/littleshoot-client
common/ice/src/main/java/org/lastbamboo/common/ice/candidate/IceCandidatePairState.java
492
package org.lastbamboo.common.ice.candidate; /** * States for ICE candidate pairs. */ public enum IceCandidatePairState { /** * The pair is waiting for execution. */ WAITING, /** * The pair resolution is in progress. */ IN_PROGRESS, /** * The pair succeeded. */ SUCCEEDED, /** * The pair has permanently failed. */ FAILED, /** * The pair is inactive. */ FROZEN; }
gpl-2.0
lclsdu/CS
GrabParking/src/com/grabparking/utils/Modules.java
3572
package com.grabparking.utils; /** * 内置第三方应用的对应模块名 * 其实就是9宫格要显示的内容的模块代码 * @author Administrator * */ public class Modules { /** * 一级模块:充值(需要弹出二级选项框) */ public static final String TOP_Recharge = "TOP_Recharge"; /** * 充值二级模块:话费充值(应用内打开) */ public static final String Bill_Recharge = "Bill_Recharge"; /** * 充值二级模块:快捷充值(应用内打开) */ public static final String Quick_Recharge = "Quick_Recharge"; /** * 一级模块:限时抢购(应用内打开) */ public static final String limitSale = "limitSale"; /** * 一级模块:转账(应用内打开) */ public static final String Zhuanzhang = "Zhuanzhang"; /** * 一级模块:信用支付(应用内打开) */ public static final String Credit = "Credit"; /** * 一级模块:提现(应用内打开) */ public static final String Withdrawals = "Withdrawals"; /** * 一级模块:代理商充值(第三方网站) */ public static final String agentsRecharge = "agentsRecharge"; /** * 一级模块:理财(第三方网站) */ public static final String Fund = "Fund"; /** * 一级模块:彩票(需要弹出二级选项框) */ public static final String TOPlottery = "TOPlottery"; /** * 彩票二级模块:我中啦(第三方网站) */ public static final String lottery = "lottery"; /** * 彩票二级模块:中彩手彩票(第三方网站) */ public static final String TXWlottery = "TXWlottery"; /** * 一级模块:游戏点卡(第三方网站) */ public static final String handpayGame = "handpayGame"; /** * 一级模块:商城(第三方网站) */ public static final String handpayMarket = "handpayMarket"; /** * 一级模块:电影票(第三方网站) */ public static final String DYP = "DYP"; /** * 一级模块:团购(第三方网站) */ public static final String Tuangou = "Tuangou"; /** * 一级模块:水电煤(第三方网站) */ public static final String payWater = "payWater"; /** * 一级模块: 保险(第三方网站) */ public static final String TBURL = "TBURL"; /** * 一级模块:Q币(第三方网站) */ public static final String qBi = "qBi"; /** * 旺铺 */ public static final String WANGSHOP = "WANGSHOP"; public static final String REMENHUDONG = "REMENHUODONG"; /** * 判断是否为一级模块 * @param moduleName * @return */ public static boolean isAppTopModule(String moduleName){ if(TOP_Recharge.equals(moduleName) ||agentsRecharge.equals(moduleName) ||TOPlottery.equals(moduleName) ||qBi.equals(moduleName) ||handpayGame.equals(moduleName) ||handpayMarket.equals(moduleName) ||DYP.equals(moduleName) ||Tuangou.equals(moduleName) ||payWater.equals(moduleName) ||TBURL.equals(moduleName) ||limitSale.equals(moduleName) ||Zhuanzhang.equals(moduleName) ||Fund.equals(moduleName) ||Credit.equals(moduleName) ||"WANGSHOP".equals(moduleName) ||Withdrawals.equals(moduleName) ){ return true; } return false; } /** * 判断是否为二级模块 * @param moduleName * @return */ public static boolean isAppTwoModule(String moduleName){ if(lottery.equals(moduleName) ||TXWlottery.equals(moduleName) ||Bill_Recharge.equals(moduleName) ||Quick_Recharge.equals(moduleName) ){ return true; } return false; } }
gpl-2.0
KungFuLucky7/NetBeansProjects
SimpleServer/src/simpleserver/method/Head.java
429
package simpleserver.method; import java.io.PrintWriter; import simpleserver.Response; /** * HEAD,identical to GET, except the server does not return the body in the * response * * @author Terry Wong */ public class Head extends Method { @Override public void execute(Response response, PrintWriter writer) { writer.println(""); System.out.println("Cached: Finished generating response"); } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/packages/apps/RCSe/core/src/com/orangelabs/rcs/core/ims/service/presence/pidf/OverridingWillingness.java
1365
/******************************************************************************* * Software Name : RCS IMS Stack * * Copyright (C) 2010 France Telecom S.A. * * 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.orangelabs.rcs.core.ims.service.presence.pidf; import com.orangelabs.rcs.utils.DateUtils; public class OverridingWillingness { private Basic basic = null; private long until = -1; public OverridingWillingness(Basic basic) { this.basic = basic; } public OverridingWillingness() { } public Basic getBasic() { return basic; } public void setBasic(Basic basic) { this.basic = basic; } public long getUntilTimestamp() { return until; } public void setUntilTimestamp(String ts) { this.until = DateUtils.decodeDate(ts); } }
gpl-2.0
dlitz/resin
modules/kernel/src/com/caucho/config/inject/BeanStartupEvent.java
1618
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.config.inject; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; /** * An event at webbeans startup */ public class BeanStartupEvent { private final BeanManager _manager; private final Bean _bean; public BeanStartupEvent(BeanManager manager, Bean bean) { _manager = manager; _bean = bean; } public BeanManager getManager() { return _manager; } public Bean getBean() { return _bean; } public String toString() { return getClass().getSimpleName() + "[" + _bean + "]"; } }
gpl-2.0
elefantbilen/UniCalc
src/se/bearden/unicalc/converter/NumberConverter.java
4376
package se.bearden.unicalc.converter; import java.util.ArrayList; import se.bearden.unicalc.R; import android.content.Context; /** * This class will calculate the character representation of numbers and vice * versa * */ public class NumberConverter { private ArrayList<ValuesToConvert> fin; private Context mContext; public NumberConverter(Context c) { this.mContext = c; } /** * Will instantiate a new list each time to clear out old results, starts * the conversion and returns result * * @param rawString * @return */ public ArrayList<ValuesToConvert> startConversion(String rawString) { fin = new ArrayList<ValuesToConvert>(); ArrayList<String> tokenizedString = splitStringForNumbers(rawString); convertAndAdd(tokenizedString); return fin; } /** * Splits a string into a string array First splits the string for every * character. Will then append values if they were integers i.e. 1,4,3 > 143 * * @param string * the string to split * @return A new string array containing all the values */ private ArrayList<String> splitStringForNumbers(String string) { String[] splitString; splitString = string.split("(?!^)"); ArrayList<String> unitString = new ArrayList<String>(); StringBuilder sBuild = new StringBuilder(); int i = 0; while (i < splitString.length) { if (isANumber(splitString[i])) { // This order is important. Length check first to avoid index // out of bounds while (i < splitString.length && isANumber(splitString[i])) { sBuild.append(splitString[i]); i++; } unitString.add(sBuild.toString()); sBuild = new StringBuilder(); } else { unitString.add(splitString[i]); i++; } } return unitString; } /** * Iterates through the string array and converts its' value through two * different methods depending on if the value is an integer or a character * * @param tokString */ private void convertAndAdd(ArrayList<String> tokString) { for (int i = 0; i < tokString.size(); i++) { if (isANumber(tokString.get(i))) fromNumberToChar(tokString.get(i)); else fromCharToNumber(tokString.get(i)); } } /** * Creates an instance of ValuesToConvert which will hold the different * values from this string. * * @param string */ private void fromNumberToChar(String string) { ValuesToConvert val = new ValuesToConvert(); try { int number = Integer.parseInt(string); if (number < 33) val.setAsciiValue(SpecialCharsEnum.values()[number].name()); else if (number < 127) val.setAsciiValue(Character.toString((char) Integer .parseInt(string))); else if (number == 127) val.setAsciiValue("Delete"); else if (number <= 255) val.setAsciiValue(Character.toString((char) Integer .parseInt(string)) + " (Extended ASCII)"); else val.setAsciiValue("Not a valid ASCII number"); val.setOriginalValue(string); val.setHexValue(Integer.toHexString(Integer.parseInt(string))); val.setDecValue(string); } catch (Exception e) { val.setOriginalValue(string + " (Too big to process)"); val.setAsciiValue("-"); val.setHexValue("-"); val.setDecValue("-"); } fin.add(val); } /** * Creates an instance of ValuesToConvert which will hold the different * values from this string. * * @param string */ private void fromCharToNumber(String string) { ValuesToConvert val = new ValuesToConvert(); int numberRepresentation = (int) string.charAt(0); if (numberRepresentation == 32) val.setOriginalValue("Space"); else val.setOriginalValue(string); if (numberRepresentation < 128) val.setAsciiValue(Integer.toString(numberRepresentation)); else val.setAsciiValue(mContext.getResources().getString( R.string.not_applicable)); val.setHexValue(Integer.toHexString(numberRepresentation)); val.setDecValue(Integer.toString(numberRepresentation)); val.setUTF8Value("Placeholder"); fin.add(val); } /** * Tests if a string is a number * * @param string * @return */ private boolean isANumber(String string) { return string.matches("\\d+"); } /** * Getter method of the prepared ArrayList of ValuesToConvert objects * containing all the values * * @return */ public ArrayList<ValuesToConvert> getFinalizedArray() { return fin; } }
gpl-2.0
rezam90/fg
TMessagesProj/src/main/java/org/telegram/messenger/time/PersianFastDateFormat.java
11153
package org.telegram.messenger.time; import org.telegram.felegram.utils.calendar.PersianCalendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class PersianFastDateFormat extends FastDateFormat { public static String[] DayNames; public static String[] MonthNames; private static final FormatCache<PersianFastDateFormat> cache = new FormatCache() { protected PersianFastDateFormat createInstance(String paramAnonymousString, TimeZone paramAnonymousTimeZone, Locale paramAnonymousLocale) { return new PersianFastDateFormat(paramAnonymousString, paramAnonymousTimeZone, paramAnonymousLocale); } }; static int localizedZeroCharCode = 1776; static int zeroCharCode; static { String[] arrayOfString1 = new String[7]; arrayOfString1[0] = "یکشنبه"; arrayOfString1[1] = "دوشنبه"; arrayOfString1[2] = "ﺳﻪشنبه"; arrayOfString1[3] = "چهارشنبه"; arrayOfString1[4] = "پنجشنبه"; arrayOfString1[5] = "جمعه"; arrayOfString1[6] = "شنبه"; DayNames = arrayOfString1; String[] arrayOfString2 = new String[12]; arrayOfString2[0] = "فروردین"; arrayOfString2[1] = "ارديبهشت"; arrayOfString2[2] = "خرداد"; arrayOfString2[3] = "تير"; arrayOfString2[4] = "مرداد"; arrayOfString2[5] = "شهریور"; arrayOfString2[6] = "مهر"; arrayOfString2[7] = "آبان"; arrayOfString2[8] = "آذر"; arrayOfString2[9] = "دی"; arrayOfString2[10] = "بهمن"; arrayOfString2[11] = "اسفند"; MonthNames = arrayOfString2; zeroCharCode = 48; } protected PersianFastDateFormat(String paramString, TimeZone paramTimeZone, Locale paramLocale) { super(paramString, paramTimeZone, paramLocale, null); } private static String GetFormat(char c) { switch (c) { case 'G': { return "yyyy/MM/dd,hh:mm:ss"; } case 'a': { return "hh:mm yy/MM/dd"; } case 'l': { return "d MMMM yyyy"; } case 'd': { return "yyyy/MM/dd"; } case 'w': { return "dd/MM/yyyy"; } case 's': { return "dddd d MMMM yyyy"; } case 'k': { return "dddd d MMMM yyyy , hh:mm:ss "; } case 'c': { return "yyyy MMMM d , hh:mm:ss"; } case 't': { return "hh:mm:ss"; } } return c + ""; } private static int GetRepeatCount(String paramString, char paramChar, int paramInt) { int i = 0; for (i = paramInt; (i < paramString.length()) && (paramString.charAt(i) == paramChar); i++) { i++; } return (i - paramInt); } public static String LocalizeNumbers(String paramString) { if (paramString == null) { char[] arrayOfChar = paramString.toCharArray(); for (int i = 0; i < arrayOfChar.length; i++) { int j = arrayOfChar[i] - zeroCharCode; if ((j >= 0) && (j < 10)) { arrayOfChar[i] = ((char) (j + localizedZeroCharCode)); } } paramString = new String(arrayOfChar); } return paramString; } private static String To2Digit(int paramInt) { int i = (byte) paramInt; char[] arrayOfChar = new char[2]; if (i < 10) { arrayOfChar[0] = '0'; arrayOfChar[1] = (char) (i + 48); } else { arrayOfChar[0] = (char) ((i / 10) + 48); arrayOfChar[1] = (char) ((i % 10) + 48); } return new String(arrayOfChar); } private String toPersianDigit(String str){ char[] arabicChars = {'۰','١','۲','۳','۴','۵','۶','۷','۸','۹'}; StringBuilder builder = new StringBuilder(); for(int i =0;i<str.length();i++) { if(Character.isDigit(str.charAt(i))) { builder.append(arabicChars[(int)(str.charAt(i))-48]); } else { builder.append(str.charAt(i)); } } return builder.toString(); } private String toPersianDigit(Integer str){ return toPersianDigit(String.valueOf(str)); } private StringBuilder ToStringBuilder(Date date, String format) { if ((format == null) || (format.length() == 0)) { format = "G"; } if (format.length() == 1) { format = GetFormat(format.charAt(0)); } PersianCalendar persianCal = new PersianCalendar(date); int Year = persianCal.getYear(); int Month = persianCal.getMonth(); int Day = persianCal.getDay(); int DayOfWeek = persianCal.getWeekDay(); int Hour = date.getHours(); int Minute = date.getMinutes(); int Second = date.getSeconds(); int length = 0; StringBuilder builder = new StringBuilder(50); while (length < format.length()) { char c = format.charAt(length); length = length + 1; int count = 0; switch (c) { case 'y': { count = GetRepeatCount(format, c, length); if (count == 4) { builder.append(toPersianDigit(Year)); break; } else if (count == 2) { builder.append(toPersianDigit(Year)); break; } else { count = 0; break; } } case 'M': { count = GetRepeatCount(format, c, length) + 1; if (count >= 3) { builder.append(MonthNames[(Month - 1)]); break; } else if (count == 2) { builder.append(toPersianDigit(To2Digit(Month))); break; } else if (count == 1) { builder.append(toPersianDigit(Month)); break; } else { count = 0; break; } } case 'd': { count = GetRepeatCount(format, c, length) + 1; if (count == 4) { builder.append(persianCal.getStrWeekDay()); break; } else if (count == 2) { builder.append(toPersianDigit(To2Digit(Day))); break; } else if (count == 1) { builder.append(toPersianDigit(Day)); break; } else { count = 0; break; } } case 'h': { count = GetRepeatCount(format, c, length) + 1; if (count == 0x2) { builder.append(toPersianDigit(To2Digit((((Hour + 0x17) % 0xc) + 1)))); break; } else if (count == 0x1) { builder.append(toPersianDigit((((Hour + 0x17) % 0xc) + 1))); break; } else { count = 0x0; break; } } case 'H': { count = GetRepeatCount(format, c, length) + 1; if (count == 0x2) { builder.append(toPersianDigit(To2Digit(Hour))); break; } else if (count == 0x1) { builder.append(toPersianDigit(Hour)); break; } else { count = 0x0; break; } } case 'm': { count = GetRepeatCount(format, c, length); if (count == 2) { builder.append(toPersianDigit(To2Digit(Minute))); break; } else if (count == 1) { builder.append(toPersianDigit(Minute)); break; } else { count = 0x0; break; } } case 's': { count = GetRepeatCount(format, c, length) + 1; if (count == 0x2) { builder.append(toPersianDigit(To2Digit(Second))); break; } else if (count == 0x1) { builder.append(toPersianDigit(Second)); break; } else { count = 0x0; break; } } case 'a': { if ((Hour < 0xc) || (Hour == 0x18)) { builder.append("صبح"); } else { builder.append("عصر"); } count = 0x1; break; } case 'E': { count = GetRepeatCount(format, c, length) + 1; if (count == 3) { builder.append(persianCal.getStrWeekDay()); break; } else { count = 0; break; } } case '.': { builder.append(" "); break; } case ':': { builder.append(":"); break; } case ' ': { builder.append(" "); break; } } if (count == 0) { //builder.append(c); continue; } length = (length + count) - 1; //break; } return builder; } public static PersianFastDateFormat getInstance(String paramString, Locale paramLocale) { return (PersianFastDateFormat) cache.getInstance(paramString, null, paramLocale); } public String format(long millis) { return format(new Date(millis)); } public String format(Date date) { if (getLocale().getLanguage().toLowerCase().contains("fa")) { return LocalizeNumbers(ToStringBuilder(date, getPattern()).toString()); } return super.format(date); } }
gpl-2.0
mzorz/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/actions/ReaderCommentActions.java
7994
package org.wordpress.android.ui.reader.actions; import android.text.TextUtils; import com.android.volley.VolleyError; import com.wordpress.rest.RestRequest; import org.json.JSONObject; import org.wordpress.android.WordPress; import org.wordpress.android.datasets.ReaderCommentTable; import org.wordpress.android.datasets.ReaderLikeTable; import org.wordpress.android.datasets.ReaderUserTable; import org.wordpress.android.models.ReaderComment; import org.wordpress.android.models.ReaderPost; import org.wordpress.android.models.ReaderUser; import org.wordpress.android.util.AppLog; import org.wordpress.android.util.AppLog.T; import org.wordpress.android.util.DateTimeUtils; import org.wordpress.android.util.JSONUtils; import org.wordpress.android.util.VolleyUtils; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ReaderCommentActions { /* * used by post detail to generate a temporary "fake" comment id (see below) */ public static long generateFakeCommentId() { return System.currentTimeMillis(); } /* * add the passed comment text to the passed post - caller must pass a unique "fake" comment id * to give the comment that's generated locally */ public static ReaderComment submitPostComment(final ReaderPost post, final long fakeCommentId, final String commentText, final long replyToCommentId, final ReaderActions.CommentActionListener actionListener, final long wpComUserId) { if (post == null || TextUtils.isEmpty(commentText)) { return null; } // determine which page this new comment should be assigned to final int pageNumber; if (replyToCommentId != 0) { pageNumber = ReaderCommentTable.getPageNumberForComment(post.blogId, post.postId, replyToCommentId); } else { pageNumber = ReaderCommentTable.getLastPageNumberForPost(post.blogId, post.postId); } // create a "fake" comment that's added to the db so it can be shown right away - will be // replaced with actual comment if it succeeds to be posted, or deleted if comment fails // to be posted ReaderComment newComment = new ReaderComment(); newComment.commentId = fakeCommentId; newComment.postId = post.postId; newComment.blogId = post.blogId; newComment.parentId = replyToCommentId; newComment.pageNumber = pageNumber; newComment.setText(commentText); Date dtPublished = DateTimeUtils.nowUTC(); newComment.setPublished(DateTimeUtils.iso8601FromDate(dtPublished)); newComment.timestamp = dtPublished.getTime(); ReaderUser currentUser = ReaderUserTable.getCurrentUser(wpComUserId); if (currentUser != null) { newComment.setAuthorAvatar(currentUser.getAvatarUrl()); newComment.setAuthorName(currentUser.getDisplayName()); } ReaderCommentTable.addOrUpdateComment(newComment); // different endpoint depending on whether the new comment is a reply to another comment final String path; if (replyToCommentId == 0) { path = "sites/" + post.blogId + "/posts/" + post.postId + "/replies/new"; } else { path = "sites/" + post.blogId + "/comments/" + Long.toString(replyToCommentId) + "/replies/new"; } Map<String, String> params = new HashMap<>(); params.put("content", commentText); RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { ReaderCommentTable.deleteComment(post, fakeCommentId); AppLog.i(T.READER, "comment succeeded"); ReaderComment newComment = ReaderComment.fromJson(jsonObject, post.blogId); newComment.pageNumber = pageNumber; ReaderCommentTable.addOrUpdateComment(newComment); if (actionListener != null) { actionListener.onActionResult(true, newComment); } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { ReaderCommentTable.deleteComment(post, fakeCommentId); AppLog.w(T.READER, "comment failed"); AppLog.e(T.READER, volleyError); if (actionListener != null) { actionListener.onActionResult(false, null); } } }; AppLog.i(T.READER, "submitting comment"); WordPress.getRestClientUtilsV1_1().post(path, params, null, listener, errorListener); return newComment; } /* * like or unlike the passed comment */ public static boolean performLikeAction(final ReaderComment comment, boolean isAskingToLike, final long wpComUserId) { if (comment == null) { return false; } // make sure like status is changing boolean isCurrentlyLiked = ReaderCommentTable.isCommentLikedByCurrentUser(comment); if (isCurrentlyLiked == isAskingToLike) { AppLog.w(T.READER, "comment like unchanged"); return false; } // update like status and like count in local db int newNumLikes = (isAskingToLike ? comment.numLikes + 1 : comment.numLikes - 1); ReaderCommentTable.setLikesForComment(comment, newNumLikes, isAskingToLike); ReaderLikeTable.setCurrentUserLikesComment(comment, isAskingToLike, wpComUserId); // sites/$site/comments/$comment_ID/likes/new final String actionName = isAskingToLike ? "like" : "unlike"; String path = "sites/" + comment.blogId + "/comments/" + comment.commentId + "/likes/"; if (isAskingToLike) { path += "new"; } else { path += "mine/delete"; } RestRequest.Listener listener = new RestRequest.Listener() { @Override public void onResponse(JSONObject jsonObject) { boolean success = (jsonObject != null && JSONUtils.getBool(jsonObject, "success")); if (success) { AppLog.d(T.READER, String.format("comment %s succeeded", actionName)); } else { AppLog.w(T.READER, String.format("comment %s failed", actionName)); ReaderCommentTable.setLikesForComment(comment, comment.numLikes, comment.isLikedByCurrentUser); ReaderLikeTable.setCurrentUserLikesComment(comment, comment.isLikedByCurrentUser, wpComUserId); } } }; RestRequest.ErrorListener errorListener = new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { String error = VolleyUtils.errStringFromVolleyError(volleyError); if (TextUtils.isEmpty(error)) { AppLog.w(T.READER, String.format("comment %s failed", actionName)); } else { AppLog.w(T.READER, String.format("comment %s failed (%s)", actionName, error)); } AppLog.e(T.READER, volleyError); ReaderCommentTable.setLikesForComment(comment, comment.numLikes, comment.isLikedByCurrentUser); ReaderLikeTable.setCurrentUserLikesComment(comment, comment.isLikedByCurrentUser, wpComUserId); } }; WordPress.getRestClientUtilsV1_1().post(path, listener, errorListener); return true; } }
gpl-2.0
dain/graal
graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/PushThroughIfTest.java
2791
/* * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.test; import org.junit.*; import com.oracle.graal.api.code.*; import com.oracle.graal.debug.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.util.*; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.tiers.*; public class PushThroughIfTest extends GraalCompilerTest { public int field1; public int field2; public int testSnippet(boolean b) { int i; if (b) { i = field1; } else { i = field1; } return i + field2; } @SuppressWarnings("unused") public int referenceSnippet(boolean b) { return field1 + field2; } @Test public void test1() { test("testSnippet", "referenceSnippet"); } private void test(String snippet, String reference) { StructuredGraph graph = parse(snippet); Debug.dump(graph, "Graph"); for (FrameState fs : graph.getNodes(FrameState.class).snapshot()) { fs.replaceAtUsages(null); GraphUtil.killWithUnusedFloatingInputs(fs); } new CanonicalizerPhase(true).apply(graph, new PhaseContext(getProviders(), new Assumptions(false))); new CanonicalizerPhase(true).apply(graph, new PhaseContext(getProviders(), new Assumptions(false))); StructuredGraph referenceGraph = parse(reference); for (FrameState fs : referenceGraph.getNodes(FrameState.class).snapshot()) { fs.replaceAtUsages(null); GraphUtil.killWithUnusedFloatingInputs(fs); } new CanonicalizerPhase(true).apply(referenceGraph, new PhaseContext(getProviders(), new Assumptions(false))); assertEquals(referenceGraph, graph); } }
gpl-2.0
mdaniel/svn-caucho-com-resin
modules/quercus/src/com/caucho/quercus/lib/simplexml/SimpleXMLNode.java
10797
package com.caucho.quercus.lib.simplexml; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import com.caucho.quercus.QuercusException; import com.caucho.quercus.annotation.JsonEncode; import com.caucho.quercus.annotation.Name; import com.caucho.quercus.annotation.Optional; import com.caucho.quercus.annotation.ReturnNullAsFalse; import com.caucho.quercus.env.ArrayValue; import com.caucho.quercus.env.ArrayValueImpl; import com.caucho.quercus.env.BooleanValue; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.JavaValue; import com.caucho.quercus.env.JsonEncodeContext; import com.caucho.quercus.env.NullValue; import com.caucho.quercus.env.ObjectExtJavaValue; import com.caucho.quercus.env.QuercusClass; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.Value; import com.caucho.util.IoUtil; import com.caucho.util.L10N; import com.caucho.vfs.Path; public abstract class SimpleXMLNode { private static final Logger log = Logger.getLogger(SimpleXMLNode.class.getName()); private static final L10N L = new L10N(SimpleXMLNode.class); protected final QuercusClass _cls; protected final SimpleView _view; private SimpleNamespaceContext _xpathNamespaceContext; public SimpleXMLNode(QuercusClass cls, SimpleView view) { _cls = cls; _view = view; } /** * public string getName() */ @Name("getName") public String simplexml_getName() { return _view.getNodeName(); } /** * public string __toString() */ public StringValue __toString(Env env) { String str = _view.toString(env); StringValue sb = env.createStringBuilder(); if (sb.isUnicode()) { sb.append(str); } else { String encoding = _view.getEncoding(); byte[] bytes; try { bytes = str.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new QuercusException(e); } sb.appendBytes(bytes, 0, bytes.length); } return sb; } /** * Implementation for getting the fields of this class. * i.e. <code>$a->foo</code> */ public Value __getField(Env env, StringValue name) { SimpleView view = _view.getField(env, name); if (view == null) { return NullValue.NULL; } SimpleXMLElement e = new SimpleXMLElement(_cls, view); return e.wrapJava(env); } /** * Implementation for setting the fields of this class. * i.e. <code>$a->foo = "hello"</code> */ public void __setField(Env env, StringValue name, Value value) { SimpleView view = _view.setField(env, name, value); } /** * Implementation for getting the indices of this class. * i.e. <code>$a->foo[0]</code> */ public Value __get(Env env, Value indexV) { SimpleView view = _view.getIndex(env, indexV); if (view == null) { return NullValue.NULL; } SimpleXMLElement e = new SimpleXMLElement(_cls, view); return e.wrapJava(env); } /** * Implementation for setting the indices of this class. * i.e. <code>$a->foo[0] = "hello"</code> */ public void __set(Env env, StringValue nameV, StringValue value) { _view.setIndex(env, nameV, value); } public int __count(Env env) { return _view.getCount(); } /** * public SimpleXMLElement addChild( string $name [, string $value [, string $namespace ]] ) */ public SimpleXMLElement addChild(Env env, StringValue nameV, @Optional StringValue valueV, @Optional String namespace) { String name; String value; String encoding = _view.getEncoding(); try { name = nameV.toString(encoding); value = valueV.toString(encoding); } catch (UnsupportedEncodingException e) { env.warning(e); return null; } SimpleView view = _view.addChild(env, name, value, namespace); SimpleXMLElement e = new SimpleXMLElement(_cls, view); return e; } /** * public void SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] ) */ public void addAttribute(Env env, StringValue nameV, @Optional StringValue valueV, @Optional String namespace) { String name; String value; String encoding = _view.getEncoding(); try { name = nameV.toString(encoding); value = valueV.toString(encoding); } catch (UnsupportedEncodingException e) { env.warning(e); return; } if (namespace != null) { if (namespace.length() == 0) { namespace = null; } else if (name.indexOf(':') <= 0) { env.warning(L.l("Adding attributes with namespaces requires attribute name with a prefix")); return; } } _view.addAttribute(env, name, value, namespace); } /** * public mixed SimpleXMLElement::asXML([ string $filename ]) */ public final Value asXML(Env env, @Optional Value filename) { StringBuilder sb = new StringBuilder(); if (! _view.toXml(env, sb)) { return BooleanValue.FALSE; } String encoding = _view.getEncoding(); if (filename.isDefault()) { StringValue value = env.createStringBuilder(); if (env.isUnicodeSemantics()) { value.append(sb.toString()); } else { byte []bytes; try { bytes = sb.toString().getBytes(encoding); } catch (UnsupportedEncodingException e) { log.log(Level.FINE, e.getMessage(), e); env.warning(e); return BooleanValue.FALSE; } value.append(bytes); } return value; } else { Path path = env.lookupPwd(filename); OutputStream os = null; try { os = path.openWrite(); byte []bytes = sb.toString().getBytes(encoding); os.write(bytes); return BooleanValue.TRUE; } catch (IOException e) { log.log(Level.FINE, e.getMessage(), e); env.warning(e); return BooleanValue.FALSE; } finally { if (os != null) { IoUtil.close(os); } } } } /** * public SimpleXMLElement SimpleXMLElement::attributes([ string $ns = NULL [, bool $is_prefix = false ]]) */ public Value attributes(Env env, @Optional Value namespaceV, @Optional boolean isPrefix) { String namespace = null; if (! namespaceV.isNull()) { namespace = namespaceV.toString(); if (namespace != null && namespace.length() == 0) { namespace = null; } } AttributeListView view = _view.getAttributes(namespace); SimpleXMLElement e = new SimpleXMLElement(getQuercusClass(), view); return e.wrapJava(env); } /** * public SimpleXMLElement SimpleXMLElement::children([ string $ns [, bool $is_prefix = false ]]) */ public Value children(Env env, @Optional Value namespaceV, @Optional boolean isPrefix) { String namespace = null; String prefix = null; if (! namespaceV.isNull()) { if (isPrefix) { prefix = namespaceV.toString(); if (prefix != null && prefix.length() == 0) { prefix = null; } } else { namespace = namespaceV.toString(); if (namespace != null && namespace.length() == 0) { namespace = null; } } } ChildrenView view = _view.getChildren(namespace, prefix); SimpleXMLElement e = new SimpleXMLElement(_cls, view); return e.wrapJava(env); } /** * public array SimpleXMLElement::getNamespaces ([ bool $recursive = false ] ) */ public ArrayValue getNamespaces(Env env, @Optional boolean isRecursive) { ArrayValue array = new ArrayValueImpl(); HashMap<String,String> usedMap = _view.getNamespaces(isRecursive, false, true); for (Map.Entry<String,String> entry : usedMap.entrySet()) { StringValue key = env.createString(entry.getKey()); StringValue value = env.createString(entry.getValue()); array.append(key, value); } return array; } /** * public array SimpleXMLElement::getDocNamespaces ([ bool $recursive = false [, bool $from_root = true ]] ) */ public ArrayValue getDocNamespaces(Env env, @Optional boolean isRecursive, @Optional boolean isFromRoot) { ArrayValue array = new ArrayValueImpl(); HashMap<String,String> usedMap = _view.getNamespaces(isRecursive, isFromRoot, false); for (Map.Entry<String,String> entry : usedMap.entrySet()) { StringValue key = env.createString(entry.getKey()); StringValue value = env.createString(entry.getValue()); array.append(key, value); } return array; } /** * public bool SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) */ public boolean registerXPathNamespace(Env env, String prefix, String ns) { if (_xpathNamespaceContext == null) { _xpathNamespaceContext = new SimpleNamespaceContext(); } _xpathNamespaceContext.addPrefix(prefix, ns); return true; } /** * public array SimpleXMLElement::xpath( string $path ) */ public Value xpath(Env env, String expression) { if (_xpathNamespaceContext == null) { _xpathNamespaceContext = new SimpleNamespaceContext(); } List<SimpleView> viewList = _view.xpath(env, _xpathNamespaceContext, expression); if (viewList == null) { return NullValue.NULL; } ArrayValue array = new ArrayValueImpl(); for (SimpleView view : viewList) { SimpleXMLElement e = new SimpleXMLElement(_cls, view); Value value = e.wrapJava(env); array.append(value); } return array; } @JsonEncode public void jsonEncode(Env env, JsonEncodeContext context, StringValue sb) { _view.jsonEncode(env, context, sb, _cls); } protected QuercusClass getQuercusClass() { return _cls; } protected Value wrapJava(Env env) { if (! "SimpleXMLElement".equals(_cls.getName())) { return new ObjectExtJavaValue(env, _cls, this, _cls.getJavaClassDef()); } else { return new JavaValue(env, this, _cls.getJavaClassDef()); } } }
gpl-2.0
dbenn/cgp
lib/antlr-2.7.0/antlr/CppCharFormatter.java
2446
package antlr; /* ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/RIGHTS.html * * $Id: //depot/code/org.antlr/release/antlr-2.7.0/antlr/CppCharFormatter.java#1 $ */ // C++ code generator by Pete Wells: pete@yamuna.demon.co.uk class CppCharFormatter implements CharFormatter { /** Given a character value, return a string representing the character * that can be embedded inside a string literal or character literal * This works for Java/C/C++ code-generation and languages with compatible * special-character-escapment. * Code-generators for languages should override this method. * @param c The character of interest. * @param forCharLiteral true to escape for char literal, false for string literal */ public String escapeChar(int c, boolean forCharLiteral) { switch (c) { case '\n' : return "\\n"; case '\t' : return "\\t"; case '\r' : return "\\r"; case '\\' : return "\\\\"; case '\'' : return forCharLiteral ? "\\'" : "'"; case '"' : return forCharLiteral ? "\"" : "\\\""; default : if ( c<' '||c>126 ) { if (c > 255) { return "\\u" + Integer.toString(c,16); } else { return "\\" + Integer.toString(c,8); } } else { return String.valueOf((char)c); } } } /** Converts a String into a representation that can be use as a literal * when surrounded by double-quotes. * @param s The String to be changed into a literal */ public String escapeString(String s) { String retval = new String(); for (int i = 0; i < s.length(); i++) { retval += escapeChar(s.charAt(i), false); } return retval; } /** Given a character value, return a string representing the character * literal that can be recognized by the target language compiler. * This works for languages that use single-quotes for character literals. * Code-generators for languages should override this method. * @param c The character of interest. */ public String literalChar(int c) { return "static_cast<unsigned char>('" + escapeChar(c, true) + "')"; } /** Converts a String into a string literal * This works for languages that use double-quotes for string literals. * Code-generators for languages should override this method. * @param s The String to be changed into a literal */ public String literalString(String s) { return "\"" + escapeString(s) + "\""; } }
gpl-2.0
abousselmi/suncomplus
src/suncom/peerclient/PeerClient.java
1648
/* * Copyright 2015 Ayoub. * * 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 suncom.peerclient; import java.util.ArrayList; import java.util.StringTokenizer; import suncom.ui.MainUI; import suncom.ui.LogUI; public class PeerClient { public static String CURRENT_DIR; public PeerClient() { String currentDirectory = this.getClass().getResource("").getFile(); currentDirectory = currentDirectory.replaceAll("file:", ""); StringTokenizer st = new StringTokenizer(currentDirectory, "/"); ArrayList<String> tokensList = new ArrayList<>(); while(st.hasMoreTokens()){ tokensList.add(st.nextToken()); } String newDir = ""; for(int i = 0; i < tokensList.size()-3; i++) { newDir += tokensList.get(i) + "/"; } CURRENT_DIR = newDir; java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainUI(new LogUI()).setVisible(true); } }); } public static void main(String[] args){ new PeerClient(); } }
gpl-2.0
srotya/marauder
ids-source/src/main/java/org/ambud/marauder/source/ids/pcap/layer3/IPv4.java
4012
/* * Copyright 2013 Ambud Sharma * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>.2 */ package org.ambud.marauder.source.ids.pcap.layer3; import java.io.DataInput; import java.io.IOException; import org.ambud.marauder.source.ids.pcap.layer2.EtherFrame; public class IPv4 extends NetworkLayer{ public static final int IP_HDR_LENGTH = 20; public static final int IP_ADDR_LENGTH = 4; private byte version, hdrLength; private byte typeOfService; private short totalLength, ident; private byte flgs; private short fragOffset; private byte ttl, proto; private short chkSum; private int srcIP, dstIP; private EtherFrame parent; public IPv4() { } @Override public void decode(DataInput di, EtherFrame parent) throws IOException { this.parent = parent; byte temp = di.readByte(); this.version = (byte)((temp >> 4) & 0xff); //all below for IPv4 this.hdrLength = (byte)(((temp << 4) & 0xff) >> 4); this.typeOfService = di.readByte(); this.totalLength = EtherFrame.readShort(di); this.ident = EtherFrame.readShort(di); short tempFlgOff = EtherFrame.readShort(di); this.flgs = (byte) ((tempFlgOff >> 13) & 0xff); this.fragOffset = (short) (((tempFlgOff << 3) >> 3) & 0xff); this.ttl = di.readByte(); this.proto = di.readByte(); this.chkSum = EtherFrame.readShort(di); this.srcIP = di.readInt(); this.dstIP = di.readInt(); if(hdrLength > 5){ // options are present, skip options for now // options = hdrLength*4 - 5*4 = hdrLength*4 - 20 di.skipBytes((hdrLength-5)); } decodeNextLayer(di); } /** * @return the version */ public byte getVersion() { return version; } /** * @return the hdrLength */ public byte getHdrLength() { return hdrLength; } /** * @return the typeOfService */ public byte getTypeOfService() { return typeOfService; } /** * @return the totalLength */ public short getTotalLength() { return totalLength; } /** * @return the ident */ public short getIdent() { return ident; } /** * @return the flgs */ public byte getFlgs() { return flgs; } /** * @return the fragOffset */ public short getFragOffset() { return fragOffset; } /** * @return the ttl */ public byte getTtl() { return ttl; } public byte getNxtProto() { return proto; } /** * @return the chkSum */ public short getChkSum() { return chkSum; } /** * @return the srcIP */ public int getSrcIP() { return srcIP; } /** * @return the dstIP */ public int getDstIP() { return dstIP; } @Override public String toString() { return "Version:"+version+" Hdr:"+hdrLength+" Src:"+intToStringIP(srcIP)+" Dst:"+intToStringIP(dstIP)+" Proto:"+proto; } public static String intToStringIP(int ip){ return ((ip >> 24) & 0xff) + "."+ ((ip >> 16) & 0xff) + "."+ ((ip >> 8) & 0xff) + "."+ ((ip >> 0) & 0xff); } @Override public NETWORK_LAYER_TYPE getType() { return NETWORK_LAYER_TYPE.IPv4; } @Override public Integer getSourceAddr() { return srcIP; } @Override public Integer getDestinationAddr() { return dstIP; } @Override public byte getNextProto() { return proto; } @Override public EtherFrame getParent() { return parent; } }
gpl-2.0
goacg/mobi_android
GoACG/src/mobi/hubtech/goacg/request/BaseResponse.java
813
package mobi.hubtech.goacg.request; public class BaseResponse implements IResponse { public static final int ERROR_CODE_SUCCESS = 0; public static final int FLAG_CACHEED = 0x00000001; private int flag; private int error_code; private String msg; public int getFlag() { return flag; } public void setFlag(int flag) { this.flag = flag; } public void addFlag(int flag) { this.flag |= flag; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public int getErrorCode() { return error_code; } }
gpl-2.0
asalber/ecollections-api
src/main/java/org/ceu/alf/ecollections/CollectionOntologyManager.java
8797
package org.ceu.alf.ecollections; import java.net.URI; /** * Interface for managing an ontology that uses the E-Collections ontology. * * This is the main interface and every class that want to access an ontology build with the E-Collections ontology must * to implement it. * * @author Alfredo Sánchez Alberca (asalber@ceu.es) * */ public interface CollectionOntologyManager { /** * is the URI for the Collection class in the E-Collections ontology. */ URI COLLECTION_URI = URI.create("http://purl.org/ceu/eco#Collection"); /** * is the URI for the Item class in the E-Collections ontology. */ URI ITEM_URI = URI.create("http://purl.org/ceu/eco#Item"); /** * is the URI for the hasElement object property in the E-Collections ontology. */ URI HASELEMENT_URI = URI.create("http://purl.org/ceu/eco#hasElement"); /** * is the URI for the hasItem object property in the E-Collections ontology. */ URI HASITEM_URI = URI.create("http://purl.org/ceu/eco#hasItem"); /** * is the URI for the hasContent object property in the E-Collections ontology. */ URI HASCONTENT_URI = URI.create("http://purl.org/ceu/eco#hasContent"); /** * is the URI for the hasCardinality data property in the E-Collections ontology. */ URI HASCARDINALITY_URI = URI.create("http://purl.org/ceu/eco#hasCardinality"); /** * is the URI for the Multiheteroset class in the E-Collections ontology. */ URI MULTIHETEROSET_URI = URI.create("http://purl.org/ceu/eco#Multiheteroset"); /** * is the URI for the Multiset class in the E-Collections ontology. */ URI MULTISET_URI = URI.create("http://purl.org/ceu/eco#Multiset"); /** * is the URI for the Heteroset class in the E-Collections ontology. */ URI HETEROSET_URI = URI.create("http://purl.org/ceu/eco#Heteroset"); /** * is the URI for the List class in the E-Collections ontology. */ URI LIST_URI = URI.create("http://purl.org/ceu/eco#List"); /** * is the URI for the Box class in the E-Collections ontology. */ URI BOX_URI = URI.create("http://purl.org/ceu/eco#Box"); /** * is the URI for the Set class in the E-Collections ontology. */ URI SET_URI = URI.create("http://purl.org/ceu/eco#Set"); /** * is the URI for the Sequence class in the E-Collections ontology. */ URI SEQUENCE_URI = URI.create("http://purl.org/ceu/eco#Sequence"); /** * is the URI for the Multicombination class in the E-Collections ontology. */ URI MULTICOMBINATION_URI = URI.create("http://purl.org/ceu/eco#Multicombination"); /** * is the URI for the Heteroranking class in the E-Collections ontology. */ URI HETERORANKING_URI = URI.create("http://purl.org/ceu/eco#Heteroranking"); /** * is the URI for the Heterocombination class in the E-Collections ontology. */ URI HETEROCOMBINATION_URI = URI.create("http://purl.org/ceu/eco#Heterocombination"); /** * is the URI for the Tuple class in the E-Collections ontology. */ URI TUPLE_URI = URI.create("http://purl.org/ceu/eco#Tuple"); /** * is the URI for the Ranking class in the E-Collections ontology. */ URI RANKING_URI = URI.create("http://purl.org/ceu/eco#Ranking"); /** * is the URI for the Combination class in the E-Collections ontology. */ URI COMBINATION_URI = URI.create("http://purl.org/ceu/eco#Combination"); /** * is the URI for the Vector class in the E-Collections ontology. */ URI VECTOR_URI = URI.create("http://purl.org/ceu/eco#Vector"); /** * is the URI for the Heterovariation class in the E-Collections ontology. */ URI HETEROVARIATION_URI = URI.create("http://purl.org/ceu/eco#Heterovariation"); /** * is the URI for the Variation class in the E-Collections ontology. */ URI VARIATION_URI = URI.create("http://purl.org/ceu/eco#Variation"); /** * is the URI for the hasElementsOfType property in the E-Collections ontology. */ URI HASELEMENTSOFTYPE_URI = URI.create("http://purl.org/ceu/eco#hasElementsOfType"); /** * Method that returns the ontology model that stores the ontology. * * @return the ontology model that stores the ontology. */ Object getOntologyModel(); /** * Method that extract a multiheteroset with a given uri from the ontology. * * @param uri * is the URI of the multiheteroset. * @return a multiheteroset with its elements contained in the ontology. */ OntologyMultiheteroset getMultiheteroset(String uri); /** * Method that extract a multiset with a given uri from the ontology. * * @param uri * is the URI of the multiset. * @return a multiset with its elements contained in the ontology. * @throws ElementOfWrongTypeException * Exception thrown when trying to add an element to an homogeneous collection and the * element not belongs to the ontology class of the elements of the collection. */ OntologyMultiset getMultiset(String uri) throws ElementOfWrongTypeException; /** * Method that extract a heteroset with a given uri from the ontology. * * @param uri * is the URI of the heteroset. * @return a heteroset with its elements contained in the ontology. */ OntologyHeteroset getHeteroset(String uri); /** * Method that extract a list with a given uri from the ontology. * * @param uri * is the URI of the list. * @return a list with its elements contained in the ontology. */ OntologyList getList(String uri); /** * Method that extract a box with a given uri from the ontology. * * @param uri * is the URI of the box. * @return a box with its elements contained in the ontology. */ OntologyBox getBox(String uri); /** * Method that extract a set with a given uri from the ontology. * * @param uri * is the URI of the set. * @return a set with its elements contained in the ontology. */ OntologySet getSet(String uri); /** * Method that extract a sequence with a given uri from the ontology. * * @param uri * is the URI of the sequence. * @return a sequence with its elements contained in the ontology. */ OntologySequence getSequence(String uri); /** * Method that extract a multicombination with a given uri from the ontology. * * @param uri * is the URI of the multicombination. * @return a multicombination with its elements contained in the ontology. */ OntologyMulticombination getMulticombination(String uri); /** * Method that extract a heteroranking with a given uri from the ontology. * * @param uri * is the URI of the heteroranking. * @return a heteroranking with its elements contained in the ontology. */ OntologyHeteroranking getHeteroranking(String uri); /** * Method that extract a heterocombination with a given uri from the ontology. * * @param uri * is the URI of the heterocombination. * @return a heterocombination with its elements contained in the ontology. */ OntologyHeterocombination getHeterocombination(String uri); /** * Method that extract a tuple with a given uri from the ontology. * * @param uri * is the URI of the tuple. * @return a tuple with its elements contained in the ontology. */ OntologyTuple getTuple(String uri); /** * Method that extract a ranking with a given uri from the ontology. * * @param uri * is the URI of the ranking. * @return a ranking with its elements contained in the ontology. */ OntologyRanking getRanking(String uri); /** * Method that extract a combination with a given uri from the ontology. * * @param uri * is the URI of the combination. * @return a combination with its elements contained in the ontology. */ OntologyCombination getCombination(String uri); /** * Method that extract a vector with a given uri from the ontology. * * @param uri * is the URI of the vector. * @return a vector with its elements contained in the ontology. */ OntologyVector getVector(String uri); /** * Method that extract a heterovariation with a given uri from the ontology. * * @param uri * is the URI of the heterovariation. * @return a heterovariation with its elements contained in the ontology. */ OntologyHeterovariation getHeterovariation(String uri); /** * Method that extract a variation with a given uri from the ontology. * * @param uri * is the URI of the variation. * @return a variation with its elements contained in the ontology. */ OntologyVariation getVariation(String uri); }
gpl-2.0
jiangchanghong/Mycat2
src/main/java/io/mycat/backend/mysql/nio/MySQLConnection.java
19999
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.backend.mysql.nio; import io.mycat.MycatServer; import io.mycat.backend.mysql.CharsetUtil; import io.mycat.backend.mysql.SecurityUtil; import io.mycat.backend.mysql.nio.handler.ResponseHandler; import io.mycat.backend.mysql.xa.TxState; import io.mycat.config.Capabilities; import io.mycat.config.Isolations; import io.mycat.net.BackendAIOConnection; import io.mycat.net.NIOProcessor; import io.mycat.net.mysql.*; import io.mycat.route.RouteResultsetNode; import io.mycat.server.ServerConnection; import io.mycat.server.parser.ServerParse; import io.mycat.serverproxy.Mysession; import io.mycat.util.TimeUtil; import io.mycat.util.exception.UnknownTxIsolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; import java.nio.channels.NetworkChannel; import java.security.NoSuchAlgorithmException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * @author mycat */ public class MySQLConnection extends BackendAIOConnection { private static final Logger LOGGER = LoggerFactory .getLogger(MySQLConnection.class); private static final long CLIENT_FLAGS = initClientFlags(); private volatile long lastTime; private volatile String schema = null; private volatile String oldSchema; private volatile boolean borrowed = false; private volatile boolean modifiedSQLExecuted = false; private volatile int batchCmdCount = 0; private static long initClientFlags() { int flag = 0; flag |= Capabilities.CLIENT_LONG_PASSWORD; flag |= Capabilities.CLIENT_FOUND_ROWS; flag |= Capabilities.CLIENT_LONG_FLAG; flag |= Capabilities.CLIENT_CONNECT_WITH_DB; // flag |= Capabilities.CLIENT_NO_SCHEMA; boolean usingCompress=MycatServer.config.getSystem().getUseCompression()==1 ; if(usingCompress) { flag |= Capabilities.CLIENT_COMPRESS; } flag |= Capabilities.CLIENT_ODBC; flag |= Capabilities.CLIENT_LOCAL_FILES; flag |= Capabilities.CLIENT_IGNORE_SPACE; flag |= Capabilities.CLIENT_PROTOCOL_41; flag |= Capabilities.CLIENT_INTERACTIVE; // flag |= Capabilities.CLIENT_SSL; flag |= Capabilities.CLIENT_IGNORE_SIGPIPE; flag |= Capabilities.CLIENT_TRANSACTIONS; // flag |= Capabilities.CLIENT_RESERVED; flag |= Capabilities.CLIENT_SECURE_CONNECTION; // client extension flag |= Capabilities.CLIENT_MULTI_STATEMENTS; flag |= Capabilities.CLIENT_MULTI_RESULTS; return flag; } private static final CommandPacket _READ_UNCOMMITTED = new CommandPacket(); private static final CommandPacket _READ_COMMITTED = new CommandPacket(); private static final CommandPacket _REPEATED_READ = new CommandPacket(); private static final CommandPacket _SERIALIZABLE = new CommandPacket(); private static final CommandPacket _AUTOCOMMIT_ON = new CommandPacket(); private static final CommandPacket _AUTOCOMMIT_OFF = new CommandPacket(); private static final CommandPacket _COMMIT = new CommandPacket(); private static final CommandPacket _ROLLBACK = new CommandPacket(); static { _READ_UNCOMMITTED.packetId = 0; _READ_UNCOMMITTED.command = MySQLPacket.COM_QUERY; _READ_UNCOMMITTED.arg = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED" .getBytes(); _READ_COMMITTED.packetId = 0; _READ_COMMITTED.command = MySQLPacket.COM_QUERY; _READ_COMMITTED.arg = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED" .getBytes(); _REPEATED_READ.packetId = 0; _REPEATED_READ.command = MySQLPacket.COM_QUERY; _REPEATED_READ.arg = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ" .getBytes(); _SERIALIZABLE.packetId = 0; _SERIALIZABLE.command = MySQLPacket.COM_QUERY; _SERIALIZABLE.arg = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE" .getBytes(); _AUTOCOMMIT_ON.packetId = 0; _AUTOCOMMIT_ON.command = MySQLPacket.COM_QUERY; _AUTOCOMMIT_ON.arg = "SET autocommit=1".getBytes(); _AUTOCOMMIT_OFF.packetId = 0; _AUTOCOMMIT_OFF.command = MySQLPacket.COM_QUERY; _AUTOCOMMIT_OFF.arg = "SET autocommit=0".getBytes(); _COMMIT.packetId = 0; _COMMIT.command = MySQLPacket.COM_QUERY; _COMMIT.arg = "commit".getBytes(); _ROLLBACK.packetId = 0; _ROLLBACK.command = MySQLPacket.COM_QUERY; _ROLLBACK.arg = "rollback".getBytes(); } private MySQLDataSource pool; private boolean fromSlaveDB; private long threadId; private HandshakePacket handshake; private volatile int txIsolation; private volatile boolean autocommit; private long clientFlags; private boolean isAuthenticated; private String user; private String password; private Object attachment; private ResponseHandler respHandler; private final AtomicBoolean isQuit; private volatile StatusSync statusSync; private volatile boolean metaDataSyned = true; private volatile int xaStatus = 0; public MySQLConnection(NetworkChannel channel, boolean fromSlaveDB) { super(channel); this.clientFlags = CLIENT_FLAGS; this.lastTime = TimeUtil.currentTimeMillis(); this.isQuit = new AtomicBoolean(false); this.autocommit = true; this.fromSlaveDB = fromSlaveDB; // 设为默认值,免得每个初始化好的连接都要去同步一下 this.txIsolation = MycatServer.config.getSystem().getTxIsolation(); } public int getXaStatus() { return xaStatus; } public void setXaStatus(int xaStatus) { this.xaStatus = xaStatus; } public void onConnectFailed(Throwable t) { if (handler instanceof MySQLConnectionHandler) { MySQLConnectionHandler theHandler = (MySQLConnectionHandler) handler; theHandler.connectionError(t); } else { ((MySQLConnectionAuthenticator) handler).connectionError(this, t); } } public String getSchema() { return this.schema; } public void setSchema(String newSchema) { String curSchema = schema; if (curSchema == null) { this.schema = newSchema; this.oldSchema = newSchema; } else { this.oldSchema = curSchema; this.schema = newSchema; } } public MySQLDataSource getPool() { return pool; } public void setPool(MySQLDataSource pool) { this.pool = pool; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public void setPassword(String password) { this.password = password; } public HandshakePacket getHandshake() { return handshake; } public void setHandshake(HandshakePacket handshake) { this.handshake = handshake; } public long getThreadId() { return threadId; } public void setThreadId(long threadId) { this.threadId = threadId; } public boolean isAuthenticated() { return isAuthenticated; } public void setAuthenticated(boolean isAuthenticated) { this.isAuthenticated = isAuthenticated; } public String getPassword() { return password; } public void authenticate() { AuthPacket packet = new AuthPacket(); packet.packetId = 1; packet.clientFlags = clientFlags; packet.maxPacketSize = maxPacketSize; packet.charsetIndex = this.charsetIndex; packet.user = user; try { packet.password = passwd(password, handshake); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } packet.database = schema; packet.write(this); } public boolean isAutocommit() { return autocommit; } public Object getAttachment() { return attachment; } public void setAttachment(Object attachment) { this.attachment = attachment; } public boolean isClosedOrQuit() { return isClosed() || isQuit.get(); } protected void sendQueryCmd(String query) { CommandPacket packet = new CommandPacket(); packet.packetId = 0; packet.command = MySQLPacket.COM_QUERY; try { packet.arg = query.getBytes(charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } lastTime = TimeUtil.currentTimeMillis(); packet.write(this); } private static void getCharsetCommand(StringBuilder sb, int clientCharIndex) { sb.append("SET names ").append(CharsetUtil.getCharset(clientCharIndex)) .append(";"); } private static void getTxIsolationCommand(StringBuilder sb, int txIsolation) { switch (txIsolation) { case Isolations.READ_UNCOMMITTED: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); return; case Isolations.READ_COMMITTED: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;"); return; case Isolations.REPEATED_READ: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); return; case Isolations.SERIALIZABLE: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); return; default: throw new UnknownTxIsolationException("txIsolation:" + txIsolation); } } private void getAutocommitCommand(StringBuilder sb, boolean autoCommit) { if (autoCommit) { sb.append("SET autocommit=1;"); } else { sb.append("SET autocommit=0;"); } } private static class StatusSync { private final String schema; private final Integer charsetIndex; private final Integer txtIsolation; private final Boolean autocommit; private final AtomicInteger synCmdCount; private final boolean xaStarted; public StatusSync(boolean xaStarted, String schema, Integer charsetIndex, Integer txtIsolation, Boolean autocommit, int synCount) { super(); this.xaStarted = xaStarted; this.schema = schema; this.charsetIndex = charsetIndex; this.txtIsolation = txtIsolation; this.autocommit = autocommit; this.synCmdCount = new AtomicInteger(synCount); } public boolean synAndExecuted(MySQLConnection conn) { int remains = synCmdCount.decrementAndGet(); if (remains == 0) {// syn command finished this.updateConnectionInfo(conn); conn.metaDataSyned = true; return false; } else if (remains < 0) { return true; } return false; } private void updateConnectionInfo(MySQLConnection conn) { if (schema != null) { conn.schema = schema; conn.oldSchema = conn.schema; } if (charsetIndex != null) { conn.setCharset(CharsetUtil.getCharset(charsetIndex)); } if (txtIsolation != null) { conn.txIsolation = txtIsolation; } if (autocommit != null) { conn.autocommit = autocommit; } } } /** * @return if synchronization finished and execute-sql has already been sent * before */ public boolean syncAndExcute() { StatusSync sync = this.statusSync; if (sync == null) { return true; } else { boolean executed = sync.synAndExecuted(this); if (executed) { statusSync = null; } return executed; } } public void execute(RouteResultsetNode rrn, ServerConnection sc, boolean autocommit) throws UnsupportedEncodingException { if (!modifiedSQLExecuted && rrn.isModifySQL()) { modifiedSQLExecuted = true; } String xaTXID = sc.getSession2().getXaTXID(); synAndDoExecute(xaTXID, rrn, sc.getCharsetIndex(), sc.getTxIsolation(), autocommit); } private void synAndDoExecute(String xaTxID, RouteResultsetNode rrn, int clientCharSetIndex, int clientTxIsoLation, boolean clientAutoCommit) { String xaCmd = null; boolean conAutoComit = this.autocommit; String conSchema = this.schema; // never executed modify sql,so auto commit boolean expectAutocommit = !modifiedSQLExecuted || isFromSlaveDB() || clientAutoCommit; if (expectAutocommit == false && xaTxID != null && xaStatus == TxState.TX_INITIALIZE_STATE) { //clientTxIsoLation = Isolations.SERIALIZABLE; xaCmd = "XA START " + xaTxID + ';'; this.xaStatus = TxState.TX_STARTED_STATE; } int schemaSyn = conSchema.equals(oldSchema) ? 0 : 1; int charsetSyn = 0; if (this.charsetIndex != clientCharSetIndex) { //need to syn the charset of connection. //set current connection charset to client charset. //otherwise while sending commend to server the charset will not coincidence. setCharset(CharsetUtil.getCharset(clientCharSetIndex)); charsetSyn = 1; } int txIsoLationSyn = (txIsolation == clientTxIsoLation) ? 0 : 1; int autoCommitSyn = (conAutoComit == expectAutocommit) ? 0 : 1; int synCount = schemaSyn + charsetSyn + txIsoLationSyn + autoCommitSyn; if (synCount == 0 && this.xaStatus != TxState.TX_STARTED_STATE) { // not need syn connection sendQueryCmd(rrn.getStatement()); return; } CommandPacket schemaCmd = null; StringBuilder sb = new StringBuilder(); if (schemaSyn == 1) { schemaCmd = getChangeSchemaCommand(conSchema); // getChangeSchemaCommand(sb, conSchema); } if (charsetSyn == 1) { getCharsetCommand(sb, clientCharSetIndex); } if (txIsoLationSyn == 1) { getTxIsolationCommand(sb, clientTxIsoLation); } if (autoCommitSyn == 1) { getAutocommitCommand(sb, expectAutocommit); } if (xaCmd != null) { sb.append(xaCmd); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("con need syn ,total syn cmd " + synCount + " commands " + sb.toString() + "schema change:" + (schemaCmd != null) + " con:" + this); } metaDataSyned = false; statusSync = new StatusSync(xaCmd != null, conSchema, clientCharSetIndex, clientTxIsoLation, expectAutocommit, synCount); // syn schema if (schemaCmd != null) { schemaCmd.write(this); } // and our query sql to multi command at last sb.append(rrn.getStatement()+";"); // syn and execute others this.sendQueryCmd(sb.toString()); // waiting syn result... } private static CommandPacket getChangeSchemaCommand(String schema) { CommandPacket cmd = new CommandPacket(); cmd.packetId = 0; cmd.command = MySQLPacket.COM_INIT_DB; cmd.arg = schema.getBytes(); return cmd; } /** * by wuzh ,execute a query and ignore transaction settings for performance * * @param sql * @throws UnsupportedEncodingException */ public void query(String query) throws UnsupportedEncodingException { RouteResultsetNode rrn = new RouteResultsetNode("default", ServerParse.SELECT, query); synAndDoExecute(null, rrn, this.charsetIndex, this.txIsolation, true); } public long getLastTime() { return lastTime; } public void setLastTime(long lastTime) { this.lastTime = lastTime; } public void quit() { if (isQuit.compareAndSet(false, true) && !isClosed()) { if (isAuthenticated) { write(writeToBuffer(QuitPacket.QUIT, allocate())); write(allocate()); } else { close("normal"); } } } @Override public void close(String reason) { if (!isClosed.get()) { isQuit.set(true); super.close(reason); pool.connectionClosed(this); if (this.respHandler != null) { this.respHandler.connectionClose(this, reason); respHandler = null; } } } public void commit() { _COMMIT.write(this); } public boolean batchCmdFinished() { batchCmdCount--; return (batchCmdCount == 0); } public void execCmd(String cmd) { this.sendQueryCmd(cmd); } public void execBatchCmd(String[] batchCmds) { // "XA END "+xaID+";"+"XA PREPARE "+xaID this.batchCmdCount = batchCmds.length; StringBuilder sb = new StringBuilder(); for (String sql : batchCmds) { sb.append(sql).append(';'); } this.sendQueryCmd(sb.toString()); } public void rollback() { _ROLLBACK.write(this); } public void release() { if (metaDataSyned == false) {// indicate connection not normalfinished // ,and // we can't know it's syn status ,so // close // it LOGGER.warn("can't sure connection syn result,so close it " + this); this.respHandler = null; this.close("syn status unkown "); return; } metaDataSyned = true; attachment = null; statusSync = null; modifiedSQLExecuted = false; setResponseHandler(null); pool.releaseChannel(this); } public boolean setResponseHandler(ResponseHandler queryHandler) { if (handler instanceof MySQLConnectionHandler) { ((MySQLConnectionHandler) handler).setResponseHandler(queryHandler); respHandler = queryHandler; return true; } else if (queryHandler != null) { LOGGER.warn("set not MySQLConnectionHandler " + queryHandler.getClass().getCanonicalName()); } return false; } /** * 写队列为空,可以继续写数据 */ public void writeQueueAvailable() { if (respHandler != null) { respHandler.writeQueueAvailable(); } } /** * 记录sql执行信息 */ public void recordSql(String host, String schema, String stmt) { // final long now = TimeUtil.currentTimeMillis(); // if (now > this.lastTime) { // // long time = now - this.lastTime; // // SQLRecorder sqlRecorder = this.pool.getSqlRecorder(); // // if (sqlRecorder.check(time)) { // // SQLRecord recorder = new SQLRecord(); // // recorder.host = host; // // recorder.schema = schema; // // recorder.statement = stmt; // // recorder.startTime = lastTime; // // recorder.executeTime = time; // // recorder.dataNode = pool.getName(); // // recorder.dataNodeIndex = pool.getIndex(); // // sqlRecorder.add(recorder); // // } // } // this.lastTime = now; } private static byte[] passwd(String pass, HandshakePacket hs) throws NoSuchAlgorithmException { if (pass == null || pass.length() == 0) { return null; } byte[] passwd = pass.getBytes(); int sl1 = hs.seed.length; int sl2 = hs.restOfScrambleBuff.length; byte[] seed = new byte[sl1 + sl2]; System.arraycopy(hs.seed, 0, seed, 0, sl1); System.arraycopy(hs.restOfScrambleBuff, 0, seed, sl1, sl2); return SecurityUtil.scramble411(passwd, seed); } @Override public boolean isFromSlaveDB() { return fromSlaveDB; } @Override public boolean isBorrowed() { return borrowed; } @Override public void setBorrowed(boolean borrowed) { this.lastTime = TimeUtil.currentTimeMillis(); this.borrowed = borrowed; } @Override public String toString() { return "MySQLConnection [id=" + id + ", lastTime=" + lastTime + ", user=" + user + ", schema=" + schema + ", old shema=" + oldSchema + ", borrowed=" + borrowed + ", fromSlaveDB=" + fromSlaveDB + ", threadId=" + threadId + ", charset=" + charset + ", txIsolation=" + txIsolation + ", autocommit=" + autocommit + ", attachment=" + attachment + ", respHandler=" + respHandler + ", host=" + host + ", port=" + port + ", statusSync=" + statusSync + ", writeQueue=" + this.getWriteQueue().size() + ", modifiedSQLExecuted=" + modifiedSQLExecuted + "]"; } @Override public boolean isModifiedSQLExecuted() { return modifiedSQLExecuted; } @Override public int getTxIsolation() { return txIsolation; } @Override public void handle(byte[] data) { try { if (MycatServer.config.pureproxy) { Mysession mysession = NIOProcessor.mySessionList.findbycon(this); if (mysession != null && mysession.frontendConnection.isAuthenticated() && MycatServer.config.pureproxy) { mysession.sendtoclient(data); return; } } } catch (Exception e) { e.printStackTrace(); super.handle(data); return; } super.handle(data); } }
gpl-2.0
draknyte1/MiscUtils
src/Java/binnie/craftgui/minecraft/control/ControlTabIcon.java
1295
package binnie.craftgui.minecraft.control; import binnie.core.genetics.IItemStackRepresentitive; import binnie.craftgui.controls.tab.ControlTab; import binnie.craftgui.controls.tab.ControlTabBar; import binnie.craftgui.core.geometry.IPoint; import binnie.craftgui.core.geometry.Position; import net.minecraft.item.ItemStack; public class ControlTabIcon<T> extends ControlTab<T> { private ControlItemDisplay item; public ControlTabIcon(ControlTabBar<T> parent, float x, float y, float w, float h, T value) { super(parent, x, y, w, h, value); this.item = new ControlItemDisplay(this, -8.0F + w / 2.0F, -8.0F + h / 2.0F); this.item.hastooltip = false; } public ItemStack getItemStack() { if ((this.value instanceof IItemStackRepresentitive)) { return ((IItemStackRepresentitive)this.value).getItemStackRepresentitive(); } return null; } public void onUpdateClient() { super.onUpdateClient(); this.item.setItemStack(getItemStack()); float x = ((ControlTabBar)getParent()).getDirection().x(); this.item.setOffset(new IPoint((isCurrentSelection()) || (isMouseOver()) ? 0.0F : -4.0F * x, 0.0F)); } public boolean hasOutline() { return false; } public int getOutlineColour() { return 16777215; } }
gpl-2.0
wangguodong577/qqj-backend
admin/src/main/java/com/qqj/download/controller/DownloadController.java
802
package com.qqj.download.controller; import com.qqj.download.DownloadUtils; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * User: guodong */ @Controller public class DownloadController { @RequestMapping(value = "/api/download", method = RequestMethod.GET) @ResponseBody public HttpEntity<byte[]> downloadApk(HttpServletRequest request, HttpServletResponse response) throws Exception { return DownloadUtils.downloadApk(request, response); } }
gpl-2.0
PrincetonUniversity/NVJVM
build/linux-amd64/jaxp/drop/jaxp_src/src/com/sun/org/apache/xalan/internal/xsltc/runtime/ErrorMessages_sv.java
12081
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ /* * $Id: ErrorMessages_sv.java 3023 2011-03-01 00:53:34Z joehw $ */ package com.sun.org.apache.xalan.internal.xsltc.runtime; import java.util.ListResourceBundle; /** * @author Morten Jorgensen */ public class ErrorMessages_sv extends ListResourceBundle { /* * XSLTC run-time error messages. * * General notes to translators and definitions: * * 1) XSLTC is the name of the product. It is an acronym for XML Stylesheet: * Transformations Compiler * * 2) A stylesheet is a description of how to transform an input XML document * into a resultant output XML document (or HTML document or text) * * 3) An axis is a particular "dimension" in a tree representation of an XML * document; the nodes in the tree are divided along different axes. * Traversing the "child" axis, for instance, means that the program * would visit each child of a particular node; traversing the "descendant" * axis means that the program would visit the child nodes of a particular * node, their children, and so on until the leaf nodes of the tree are * reached. * * 4) An iterator is an object that traverses nodes in a tree along a * particular axis, one at a time. * * 5) An element is a mark-up tag in an XML document; an attribute is a * modifier on the tag. For example, in <elem attr='val' attr2='val2'> * "elem" is an element name, "attr" and "attr2" are attribute names with * the values "val" and "val2", respectively. * * 6) A namespace declaration is a special attribute that is used to associate * a prefix with a URI (the namespace). The meanings of element names and * attribute names that use that prefix are defined with respect to that * namespace. * * 7) DOM is an acronym for Document Object Model. It is a tree * representation of an XML document. * * SAX is an acronym for the Simple API for XML processing. It is an API * used inform an XML processor (in this case XSLTC) of the structure and * content of an XML document. * * Input to the stylesheet processor can come from an XML parser in the * form of a DOM tree or through the SAX API. * * 8) DTD is a document type declaration. It is a way of specifying the * grammar for an XML file, the names and types of elements, attributes, * etc. * * 9) Translet is an invented term that refers to the class file that contains * the compiled form of a stylesheet. */ // These message should be read from a locale-specific resource bundle private static final Object[][] _contents = new Object[][] { /* * Note to translators: the substitution text in the following message * is a class name. Used for internal errors in the processor. */ {BasisLibrary.RUN_TIME_INTERNAL_ERR, "Internt k\u00F6rningsfel i ''{0}''"}, /* * Note to translators: <xsl:copy> is a keyword that should not be * translated. */ {BasisLibrary.RUN_TIME_COPY_ERR, "K\u00F6rningsfel vid k\u00F6rning av <xsl:copy>."}, /* * Note to translators: The substitution text refers to data types. * The message is displayed if a value in a particular context needs to * be converted to type {1}, but that's not possible for a value of type * {0}. */ {BasisLibrary.DATA_CONVERSION_ERR, "Ogiltig konvertering fr\u00E5n ''{0}'' till ''{1}''."}, /* * Note to translators: This message is displayed if the function named * by the substitution text is not a function that is supported. XSLTC * is the acronym naming the product. */ {BasisLibrary.EXTERNAL_FUNC_ERR, "Den externa funktionen ''{0}'' underst\u00F6ds inte i XSLTC."}, /* * Note to translators: This message is displayed if two values are * compared for equality, but the data type of one of the values is * unknown. */ {BasisLibrary.EQUALITY_EXPR_ERR, "Ok\u00E4nd argumenttyp i likhetsuttryck."}, /* * Note to translators: The substitution text for {0} will be a data * type; the substitution text for {1} will be the name of a function. * This is displayed if an argument of the particular data type is not * permitted for a call to this function. */ {BasisLibrary.INVALID_ARGUMENT_ERR, "Argumenttyp ''{0}'' i anrop till ''{1}'' \u00E4r inte giltig"}, /* * Note to translators: There is way of specifying a format for a * number using a pattern; the processor was unable to format the * particular value using the specified pattern. */ {BasisLibrary.FORMAT_NUMBER_ERR, "F\u00F6rs\u00F6ker formatera talet ''{0}'' med m\u00F6nstret ''{1}''."}, /* * Note to translators: The following represents an internal error * situation in XSLTC. The processor was unable to create a copy of an * iterator. (See definition of iterator above.) */ {BasisLibrary.ITERATOR_CLONE_ERR, "Kan inte klona iteratorn ''{0}''."}, /* * Note to translators: The following represents an internal error * situation in XSLTC. The processor attempted to create an iterator * for a particular axis (see definition above) that it does not * support. */ {BasisLibrary.AXIS_SUPPORT_ERR, "Iteratorn f\u00F6r axeln ''{0}'' underst\u00F6ds inte."}, /* * Note to translators: The following represents an internal error * situation in XSLTC. The processor attempted to create an iterator * for a particular axis (see definition above) that it does not * support. */ {BasisLibrary.TYPED_AXIS_SUPPORT_ERR, "Iteratorn f\u00F6r den typade axeln ''{0}'' underst\u00F6ds inte."}, /* * Note to translators: This message is reported if the stylesheet * being processed attempted to construct an XML document with an * attribute in a place other than on an element. The substitution text * specifies the name of the attribute. */ {BasisLibrary.STRAY_ATTRIBUTE_ERR, "Attributet ''{0}'' finns utanf\u00F6r elementet."}, /* * Note to translators: As with the preceding message, a namespace * declaration has the form of an attribute and is only permitted to * appear on an element. The substitution text {0} is the namespace * prefix and {1} is the URI that was being used in the erroneous * namespace declaration. */ {BasisLibrary.STRAY_NAMESPACE_ERR, "Namnrymdsdeklarationen ''{0}''=''{1}'' finns utanf\u00F6r element."}, /* * Note to translators: The stylesheet contained a reference to a * namespace prefix that was undefined. The value of the substitution * text is the name of the prefix. */ {BasisLibrary.NAMESPACE_PREFIX_ERR, "Namnrymd f\u00F6r prefix ''{0}'' har inte deklarerats."}, /* * Note to translators: The following represents an internal error. * DOMAdapter is a Java class in XSLTC. */ {BasisLibrary.DOM_ADAPTER_INIT_ERR, "DOMAdapter har skapats med fel typ av DOM-k\u00E4lla."}, /* * Note to translators: The following message indicates that the XML * parser that is providing input to XSLTC cannot be used because it * does not describe to XSLTC the structure of the input XML document's * DTD. */ {BasisLibrary.PARSER_DTD_SUPPORT_ERR, "Den SAX-parser som du anv\u00E4nder hanterar inga DTD-deklarationsh\u00E4ndelser."}, /* * Note to translators: The following message indicates that the XML * parser that is providing input to XSLTC cannot be used because it * does not distinguish between ordinary XML attributes and namespace * declarations. */ {BasisLibrary.NAMESPACES_SUPPORT_ERR, "Den SAX-parser som du anv\u00E4nder saknar st\u00F6d f\u00F6r XML-namnrymder."}, /* * Note to translators: The substitution text is the URI that was in * error. */ {BasisLibrary.CANT_RESOLVE_RELATIVE_URI_ERR, "Kunde inte matcha URI-referensen ''{0}''."}, /* * Note to translators: The stylesheet contained an element that was * not recognized as part of the XSL syntax. The substitution text * gives the element name. */ {BasisLibrary.UNSUPPORTED_XSL_ERR, "XSL-elementet ''{0}'' st\u00F6ds inte"}, /* * Note to translators: The stylesheet referred to an extension to the * XSL syntax and indicated that it was defined by XSLTC, but XSLTC does * not recognize the particular extension named. The substitution text * gives the extension name. */ {BasisLibrary.UNSUPPORTED_EXT_ERR, "XSLTC-till\u00E4gget ''{0}'' \u00E4r ok\u00E4nt"}, /* * Note to translators: This error message is produced if the translet * class was compiled using a newer version of XSLTC and deployed for * execution with an older version of XSLTC. The substitution text is * the name of the translet class. */ {BasisLibrary.UNKNOWN_TRANSLET_VERSION_ERR, "Angiven translet, ''{0}'', har skapats med en XSLTC-version som \u00E4r senare \u00E4n den XSLTC-k\u00F6rning i bruk. F\u00F6r att kunna k\u00F6ra denna translet m\u00E5ste du omkompilera formatmallen eller anv\u00E4nda en senare version av XSLTC."}, /* * Note to translators: An attribute whose effective value is required * to be a "QName" had a value that was incorrect. * 'QName' is an XML syntactic term that must not be translated. The * substitution text contains the actual value of the attribute. */ {BasisLibrary.INVALID_QNAME_ERR, "Ett attribut vars v\u00E4rde m\u00E5ste vara ett QName hade v\u00E4rdet ''{0}''"}, /* * Note to translators: An attribute whose effective value is required * to be a "NCName" had a value that was incorrect. * 'NCName' is an XML syntactic term that must not be translated. The * substitution text contains the actual value of the attribute. */ {BasisLibrary.INVALID_NCNAME_ERR, "Ett attribut vars v\u00E4rde m\u00E5ste vara ett NCName hade v\u00E4rdet ''{0}''"}, {BasisLibrary.UNALLOWED_EXTENSION_FUNCTION_ERR, "Anv\u00E4ndning av till\u00E4ggsfunktionen ''{0}'' \u00E4r inte till\u00E5tet n\u00E4r s\u00E4ker bearbetning till\u00E4mpas."}, {BasisLibrary.UNALLOWED_EXTENSION_ELEMENT_ERR, "Anv\u00E4ndning av till\u00E4ggselementet ''{0}'' \u00E4r inte till\u00E5tet n\u00E4r s\u00E4ker bearbetning till\u00E4mpas."}, }; /** Get the lookup table for error messages. * * @return The message lookup table. */ public Object[][] getContents() { return _contents; } }
gpl-2.0
GamesCrafters/GamesmanIndie
tictactwo/brian_src/Solver.java
7240
package brian_src; import java.util.ArrayList; import java.util.HashMap; import java.util.TreeMap; public class Solver { private IntGame game; private HashMap<Integer, GameState> statemap; private boolean removeSymmetries; private String gameName; public Solver(IntGame game) { this.game = game; statemap = new HashMap<>(); removeSymmetries = false; gameName = "Default Name"; } public Solver(IntGame game, boolean remove) { this.game = game; statemap = new HashMap<>(); removeSymmetries = remove; gameName = "Default Name"; } public Solver (IntGame game, String name) { this.game = game; statemap = new HashMap<>(); removeSymmetries = false; gameName = name; } public Solver(IntGame game, boolean remove, String name) { this.game = game; statemap = new HashMap<>(); removeSymmetries = remove; gameName = name; } public GameState solve(int position) { if (statemap.containsKey(position)) { return statemap.get(position); } if (removeSymmetries) { ArrayList<Integer> symmetries = game.getSymmetries(position); for (Integer symmetry : symmetries) { if (statemap.containsKey(symmetry)) { return statemap.get(symmetry); } } } try { PositionValue pVal = game.primitiveValue(position); GameState gs; switch (pVal) { case ERROR: return new GameState(PositionValue.ERROR, -1); case WIN: case LOSE: case TIE: gs = new GameState(pVal, 0); statemap.put(position, gs); return gs; case NOT_PRIMITIVE: default: ArrayList<Integer> moves = game.generateMoves(position); HashMap<PositionValue, Integer> states = new HashMap<>(); for (Integer move : moves) { gs = solve(game.doMove(position, move)); switch (gs.positionValue()) { case LOSE: case TIE: if (states.containsKey(gs.positionValue())) { states.put(gs.positionValue(), Math.min(gs.remoteness(), states.get(gs.positionValue()))); } else { states.put(gs.positionValue(), gs.remoteness()); } break; case WIN: if (states.containsKey(PositionValue.WIN)) { states.put(PositionValue.WIN, Math.max(gs.remoteness(), states.get(PositionValue.WIN))); } else { states.put(PositionValue.WIN, gs.remoteness()); } break; } } if (states.containsKey(PositionValue.LOSE)) { gs = new GameState(PositionValue.WIN, states.get(PositionValue.LOSE) + 1); } else if (states.containsKey(PositionValue.TIE)) { gs = new GameState(PositionValue.TIE, states.get(PositionValue.TIE) + 1); } else { gs = new GameState(PositionValue.LOSE, states.get(PositionValue.WIN) + 1); } statemap.put(position, gs); //System.out.print("State: "); //((brian_src.TicTacTwo)game).printPos(position); //System.out.println("Remoteness: " + gs.remoteness()); return gs; } } catch (StackOverflowError err) { GameState gs = new GameState(PositionValue.DRAW, Integer.MAX_VALUE); statemap.put(position, gs); return gs; } } public void detailedAnalysis() { // Solve solve(game.startPosition()); TicTacTwo temp = new TicTacTwo(); TreeMap<Integer, Integer[]> results = new TreeMap<>(); // needs to be sorted for (GameState gs : statemap.values()) { Integer[] stateArray = {0, 0, 0}; if (results.containsKey(gs.remoteness())) { stateArray = results.get(gs.remoteness()); } switch (gs.positionValue()) { case WIN: stateArray[0]++; break; case LOSE: stateArray[1]++; break; case TIE: stateArray[2]++; break; } results.put(gs.remoteness(), stateArray); } // Print System.out.print(gameName + " analysis "); if (removeSymmetries) { System.out.println("(symmetries removed):"); } else { System.out.println("(symmetries not removed):"); } System.out.println("Remote Win Lose Tie Total"); System.out.println("----------------------------------------"); int winTotal = 0, loseTotal = 0, tieTotal = 0, total = 0; for (Integer i : results.descendingKeySet()) { Integer[] arr = results.get(i); int sum = arr[0] + arr[1] + arr[2]; System.out.printf("%-3d %-7d %-7d %-7d %-7d\n", i, arr[0], arr[1], arr[2], sum); winTotal += arr[0]; loseTotal += arr[1]; tieTotal += arr[2]; total += sum; } System.out.println("------------------------------------------"); System.out.printf("Total %-7d %-7d %-7d %-7d\n", winTotal, loseTotal, tieTotal, total); } public static void main(String[] args) { /* G10_to_0_by_1_or_2 g = new G10_to_0_by_1_or_2(); brian_src.Solver s = new brian_src.Solver(g, "10 to 0 by 1 or 2"); s.detailedAnalysis(); System.out.println("\n"); brian_src.TicTacToe ttt = new brian_src.TicTacToe(); s = new brian_src.Solver(ttt, "Tic Tac Toe"); s.detailedAnalysis(); System.out.println("\n"); s = new brian_src.Solver(ttt, true, "Tic Tac Toe"); s.detailedAnalysis();*/ TicTacTwo tttwo = new TicTacTwo(); Solver s = new Solver(tttwo, false, "Tic Tac Two"); s.detailedAnalysis(); } /*ArrayList<Integer> list = new ArrayList<>(); for (Integer hash : statemap.keySet()) { GameState gs = statemap.get(hash); if (gs.remoteness() == 0 && gs.positionValue() == PositionValue.LOSE) { list.add(hash); } } System.out.println("Start of print"); java.util.Collections.sort(list); for (Integer hash: list){ temp.printPos(hash); // Need to print to file }*/ }
gpl-2.0
bodom91/mystamps
src/test/java/ru/mystamps/web/tests/cases/WhenUserAtRegisterAccountPage.java
2015
/* * Copyright (C) 2009-2017 Slava Semushin <slava.semushin@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ru.mystamps.web.tests.cases; import org.springframework.beans.factory.annotation.Value; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.fest.assertions.api.Assertions.assertThat; import static ru.mystamps.web.tests.TranslationUtils.tr; import ru.mystamps.web.tests.page.RegisterAccountPage; public class WhenUserAtRegisterAccountPage extends WhenAnyUserAtAnyPageWithForm<RegisterAccountPage> { @Value("${valid_user_login}") private String validUserLogin; @Value("${valid_user_password}") private String validUserPassword; public WhenUserAtRegisterAccountPage() { super(RegisterAccountPage.class); } @BeforeClass public void setUp() { page.open(); page.login(validUserLogin, validUserPassword); } @AfterClass(alwaysRun = true) public void tearDown() { page.logout(); } @Test(groups = "logic") public void messageShouldBeShown() { assertThat(page.textPresent(tr("t_already_registered"))).isTrue(); } @Test(groups = "misc") public void formWithLegendShouldBeAbsent() { assertThat(page.registrationFormExists()).isFalse(); assertThat(page.getFormHints()).isEmpty(); } }
gpl-2.0
stiez/jeveassets
src/main/java/net/nikr/eve/jeveasset/gui/tabs/reprocessed/ReprocessedTableFormat.java
4378
/* * Copyright 2009-2015 Contributors (see credits.txt) * * This file is part of jEveAssets. * * jEveAssets is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * jEveAssets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jEveAssets; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package net.nikr.eve.jeveasset.gui.tabs.reprocessed; import ca.odell.glazedlists.GlazedLists; import java.util.Comparator; import net.nikr.eve.jeveasset.gui.shared.table.EnumTableColumn; import net.nikr.eve.jeveasset.i18n.TabsReprocessed; public enum ReprocessedTableFormat implements EnumTableColumn<ReprocessedInterface> { NAME(String.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnName(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getName(); } }, QUANTITY_MAX(Long.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnQuantityMax(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getQuantityMax(); } }, QUANTITY_SKILL(Long.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnQuantitySkill(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getQuantitySkill(); } }, PRICE(Double.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnPrice(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getDynamicPrice(); } }, VALUE_MAX(Double.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnValueMax(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getValueMax(); } }, VALUE_SKILL(Double.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnValueSkill(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getValueSkill(); } }, VALUE_DIFFERENCE(Double.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnValueDifference(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getValueDifference(); } }, TYPE_ID(Integer.class, GlazedLists.comparableComparator()) { @Override public String getColumnName() { return TabsReprocessed.get().columnTypeID(); } @Override public Object getColumnValue(final ReprocessedInterface from) { return from.getItem().getTypeID(); } }; private Class<?> type; private Comparator<?> comparator; private ReprocessedTableFormat(final Class<?> type, final Comparator<?> comparator) { this.type = type; this.comparator = comparator; } @Override public Class<?> getType() { return type; } @Override public Comparator<?> getComparator() { return comparator; } @Override public String toString() { return getColumnName(); } @Override public boolean isColumnEditable(final Object baseObject) { return false; } @Override public boolean isShowDefault() { return true; } @Override public ReprocessedInterface setColumnValue(final Object baseObject, final Object editedValue) { return null; } //XXX - TableFormat.getColumnValue(...) Workaround @Override public abstract Object getColumnValue(final ReprocessedInterface from); }
gpl-2.0
AntoineDelacroix/NewSuperProject-
com.celad.rental.ui/src/com/celad/rental/ui/RentalUIActivator.java
970
package com.celad.rental.ui; import javax.inject.Inject; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class RentalUIActivator implements BundleActivator { private static BundleContext context; static BundleContext getContext() { return context; } /* * (non-Javadoc) * * @see org.osgi.framework.BundleActivator#start(org.osgi.framework. * BundleContext) */ public void start(BundleContext bundleContext) throws Exception { RentalUIActivator.context = bundleContext; } /* * (non-Javadoc) * * @see * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext bundleContext) throws Exception { RentalUIActivator.context = null; } }
gpl-2.0
Christqnd/Parqueadero
Parqueadero/src/DAO/PuertasDAO.java
4056
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package DAO; import MODELO.Puerta; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author pablopc */ public class PuertasDAO { private Map<String,List<Puerta>> puertas=new HashMap(); private static PuertasDAO instancia=null; public PuertasDAO() { } public static PuertasDAO getInstancia(){ if(instancia==null) instancia=new PuertasDAO(); return instancia; } public void AgregarPuerta(String codcampus,Puerta p){ if(this.getPuertas().containsKey(codcampus)){ this.getPuertas().get(codcampus).add(p); }else{ List lista=new ArrayList(); lista.add(p); this.getPuertas().put(codcampus, lista); } System.out.println("Puerta: "+p.getCodigo()+" Guardada en campus: "+codcampus); } public List<Puerta> obtenerPuertas(String codCampus) throws CodigodeCampusNoExisteException{ if(!this.puertas.containsKey(codCampus)){ throw new CodigodeCampusNoExisteException(); } return this.getPuertas().get(codCampus); } public Puerta obtenerPuerta(String codcampus,String codpuerta) throws CodigodeCampusNoExisteException, PuertaNoexisteException{ if(!this.puertas.containsKey(codcampus)){ throw new CodigodeCampusNoExisteException(); } int valor=this.buscarPuerta(codcampus, codpuerta); if(valor==-1){ throw new PuertaNoexisteException(); } return this.puertas.get(codcampus).get(valor-1); } public void eliminarpuerta(String codcampus,String codpuerta) throws CodigodeCampusNoExisteException{ if(!this.puertas.containsKey(codcampus)){ throw new CodigodeCampusNoExisteException(); } List<Puerta> lista=this.getPuertas().get(codcampus); int i=0; for(i=0;i<lista.size();i++){ if(lista.get(i).getCodigo().equals(codpuerta)){ i=lista.size(); } } lista.remove(i); System.out.println("puerta Elimindada"); this.getPuertas().put(codcampus, lista); } public List<Puerta> obtenerListaPuertasPor(String codcampus,String filtro) throws CodigodeCampusNoExisteException{ List<Puerta> lista=this.obtenerPuertas(codcampus); List<Puerta> listareturn=new ArrayList(); for(Puerta p:lista){ if(p.getTipoDePuerta().estadoPuerta().equalsIgnoreCase(filtro)){ listareturn.add(p); } } return listareturn; } public int buscarPuerta(String codcampus,String codpuerta){ List <Puerta> lista=new ArrayList<>(this.puertas.get(codcampus)); boolean valor=true; int i=0; while(valor){ if(lista.get(i).getCodigo().equalsIgnoreCase(codpuerta)){ valor=false; } i++; } if(valor) i=-1; return i; } /** * @return the puertas */ public Map<String,List<Puerta>> getPuertas() { return puertas; } /** * @param puertas the puertas to set */ public void setPuertas(Map<String,List<Puerta>> puertas) { this.puertas = puertas; } public void mostrar(){ List<String> lista=new ArrayList<>(this.puertas.keySet()); for(String s:lista){ System.out.println(s); List<Puerta> lista2=this.puertas.get(s); for(Puerta p:lista2){ System.out.println("/t"+p); } } } }
gpl-2.0
iquesters/ams
src/com/iq/ams/dao/apartment/ApartmentDao.java
1653
package com.iq.ams.dao.apartment; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import org.iq.db.dao.BaseDao; import org.iq.db.dao.BaseSearchDao; import org.iq.exception.DbException; import com.iq.ams.valueobject.apartment.ApartmentMasterVO; /** * @author Sam * */ public interface ApartmentDao extends BaseDao<ApartmentMasterVO>, BaseSearchDao<ApartmentMasterVO> { int insertMultiple(int communityId, List<ApartmentMasterVO> apartmentMasterVOs) throws DbException; int insertAndGetApartmentId(ApartmentMasterVO apartmentMasterVO) throws DbException; List<ApartmentMasterVO> selectByCommunityId(int communityId) throws DbException; ApartmentMasterVO selectByApartmentId(int apartmentId) throws DbException; int getLastApartmentId() throws DbException; ArrayList<ApartmentMasterVO> selectByApartmentsDwellerId(int dwellerId) throws DbException; boolean isAssigned(int apartmentId) throws DbException; HashMap<String, Date> getApartmentDates(int apartmentId, int dwellerId) throws DbException; // for list dweller service List<ApartmentMasterVO> selectByDwellerId(int dwellerId) throws DbException; int countByCommunityId(int communityId) throws DbException; int countVacantByCommunityId(int communityId) throws DbException; // Update current dweller in the table int updateCurrentDweller(int apartmentId, Integer dwellerId, int apartmentStatus, int userId, Date date) throws DbException; List<ApartmentMasterVO> vacantByCommunityId(int communityId) throws DbException; int updateStatus(Integer apartmentId, int apartmentStatus, int userId) throws DbException; }
gpl-2.0
automenta/opennars
nars_gui/nars/gui/output/OutputLogPanel.java
7361
package nars.gui.output; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Document; import javax.swing.text.MutableAttributeSet; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import nars.core.NAR; import nars.entity.Sentence; import nars.gui.NARControls; import nars.gui.NPanel; import nars.gui.NSlider; import nars.io.Output; /** * * @author me */ public class OutputLogPanel extends NPanel implements Output { private final DefaultStyledDocument doc; private final JTextPane ioText; private final Style mainStyle; private final NAR nar; int maxIOTextSize = (int) 8E6; private boolean showErrors = false; private Collection nextOutput = new ConcurrentLinkedQueue(); public OutputLogPanel(NAR s) { super(); setLayout(new BorderLayout()); this.nar = s; StyleContext sc = new StyleContext(); doc = new DefaultStyledDocument(sc); ioText = new JTextPane(doc); ioText.setEditable(false); // Create and add the main document style Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE); mainStyle = sc.addStyle("MainStyle", defaultStyle); //StyleConstants.setLeftIndent(mainStyle, 16); //StyleConstants.setRightIndent(mainStyle, 16); //StyleConstants.setFirstLineIndent(mainStyle, 16); //StyleConstants.setFontFamily(mainStyle, "serif"); //StyleConstants.setFontSize(mainStyle, 12); doc.setLogicalStyle(0, mainStyle); //http://stackoverflow.com/questions/4702891/toggling-text-wrap-in-a-jtextpane JPanel ioTextWrap = new JPanel(new BorderLayout()); ioTextWrap.add(ioText); add(new JScrollPane(ioTextWrap), BorderLayout.CENTER); JPanel menu = new JPanel(new FlowLayout(FlowLayout.LEFT)); final JCheckBox showErrorBox = new JCheckBox("Show Errors"); showErrorBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showErrors = showErrorBox.isSelected(); } }); menu.add(showErrorBox); final NSlider fontSlider = new NSlider(ioText.getFont().getSize(), 6, 40) { @Override public void onChange(double v) { ioText.setFont(ioText.getFont().deriveFont((float)v)); } }; fontSlider.setPrefix("Font size: "); menu.add(fontSlider); add(menu, BorderLayout.SOUTH); addContainerListener(new ContainerListener() { @Override public void componentAdded(ContainerEvent e) { } @Override public void componentRemoved(ContainerEvent e) { } }); } @Override protected void onShowing(boolean showing) { if (showing) nar.addOutputChannel(this); else nar.removeOutputChannel(this); } @Override public void output(final Class c, Object o) { if ((!showErrors) && (c == ERR.class)) { return; } if (o instanceof Exception) { o = (o.toString() + " @ " + Arrays.asList(((Exception) o).getStackTrace())); } nextOutput.add(c.getSimpleName() + ": "); nextOutput.add(o); nextOutput.add('\n'); SwingUtilities.invokeLater(nextOutputRunnable); } void limitBuffer(int incomingDataSize) { Document doc = ioText.getDocument(); int overLength = doc.getLength() + incomingDataSize - maxIOTextSize; if (overLength > 0) { try { doc.remove(0, overLength); } catch (BadLocationException ex) { } } } protected void print(Color c, float size, String text, boolean bold) { StyleContext sc = StyleContext.getDefaultStyleContext(); MutableAttributeSet aset = ioText.getInputAttributes(); Font f = ioText.getFont(); StyleConstants.setForeground(aset, c); //StyleConstants.setFontSize(aset, (int)(f.getSize()*size)); StyleConstants.setBold(aset, bold); try { doc.insertString(doc.getLength(), text, null); ioText.getStyledDocument().setCharacterAttributes(doc.getLength() - text.length(), text.length(), aset, true); } catch (BadLocationException ex) { Logger.getLogger(NARControls.class.getName()).log(Level.SEVERE, null, ex); } } private Runnable nextOutputRunnable = new Runnable() { @Override public void run() { if (nextOutput.size() > 0) { //limitBuffer(nextOutput.length()); limitBuffer(128); for (Object o : nextOutput) { if ((o instanceof String) || (o instanceof Character)) print(Color.BLACK, 1.0f, o.toString(), false); else if (o instanceof Sentence) { Sentence s = (Sentence)o; float conf = 0.5f, freq = 0.5f; if (s.getTruth() != null) { conf = s.getTruth().getConfidence(); freq = s.getTruth().getFrequency(); } float contentSize = 1f; //0.75f+conf; Color contentColor = Color.getHSBColor(0.5f + (freq-0.5f)/2f, 1.0f, 0.05f + 0.5f - conf/4f); print(contentColor, contentSize, s.getContent().toString() + s.getPunctuation(), s.isQuestion()); if (s.getTruth()!=null) { Color truthColor = Color.getHSBColor(freq, 0, 0.25f - conf/4f); print(truthColor, contentSize, s.getTruth().toString(), false); } if (s.getStamp()!=null) { Color stampColor = Color.GRAY; print(stampColor, contentSize, s.getStamp().toString(), false); } } else { print(Color.BLACK, 1.0f, o.toString(), false); } } nextOutput.clear(); } } }; }
gpl-2.0
eitansuez/ashkelon
src/org/ashkelon/pages/NoopPage.java
372
package org.ashkelon.pages; import java.sql.*; /** * jsp's with no or empty associated java class can refer to * this one in the config.xml file * * @author Eitan Suez */ public class NoopPage extends Page { public NoopPage() throws SQLException { super(); } public String handleRequest() throws SQLException { return null; } }
gpl-2.0
xperiment-Mobi/PythonScriptingLanguage
src/pythonj/TreeWalker.java
41528
// $ANTLR 3.5 C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g 2014-05-12 19:03:38 package pythonj; import nodes.*; import java.util.Map; import java.util.HashMap; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; @SuppressWarnings("all") public class TreeWalker extends TreeParser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "Comment", "DEDENT", "EOL", "EXP", "ID", "INDENT", "INT", "LOOKUP", "NUMBER", "STATEMENTS", "STRING", "Skip", "Spaces", "'!='", "'%'", "'('", "')'", "'*'", "'+'", "','", "'-'", "'.'", "'/'", "':'", "'<'", "'<='", "'='", "'=='", "'>'", "'>='", "'and'", "'contains'", "'elif'", "'else'", "'for'", "'if'", "'in'", "'or'", "'print'", "'while'", "'list'" }; public static final int EOF=-1; public static final int T__17=17; public static final int T__18=18; public static final int T__19=19; public static final int T__20=20; public static final int T__21=21; public static final int T__22=22; public static final int T__23=23; public static final int T__24=24; public static final int T__25=25; public static final int T__26=26; public static final int T__27=27; public static final int T__28=28; public static final int T__29=29; public static final int T__30=30; public static final int T__31=31; public static final int T__32=32; public static final int T__33=33; public static final int T__34=34; public static final int T__35=35; public static final int T__36=36; public static final int T__37=37; public static final int T__38=38; public static final int T__39=39; public static final int T__40=40; public static final int T__41=41; public static final int T__42=42; public static final int T__43=43; public static final int Comment=4; public static final int DEDENT=5; public static final int EOL=6; public static final int EXP=7; public static final int ID=8; public static final int INDENT=9; public static final int INT=10; public static final int LOOKUP=11; public static final int NUMBER=12; public static final int STATEMENTS=13; public static final int STRING=14; public static final int Skip=15; public static final int Spaces=16; public static final int T__44=44; // delegates public TreeParser[] getDelegates() { return new TreeParser[] {}; } // delegators public TreeWalker(TreeNodeStream input) { this(input, new RecognizerSharedState()); } public TreeWalker(TreeNodeStream input, RecognizerSharedState state) { super(input, state); } @Override public String[] getTokenNames() { return TreeWalker.tokenNames; } @Override public String getGrammarFileName() { return "C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g"; } public Map<String, SLValue> memory = new HashMap<String, SLValue>(); // $ANTLR start "prog" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:23:1: prog returns [SLNode node] : ( EOL )* block ; public final SLNode prog() throws RecognitionException { SLNode node = null; SLNode block1 =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:23:27: ( ( EOL )* block ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:23:29: ( EOL )* block { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:23:29: ( EOL )* loop1: while (true) { int alt1=2; int LA1_0 = input.LA(1); if ( (LA1_0==EOL) ) { alt1=1; } switch (alt1) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:23:29: EOL { match(input,EOL,FOLLOW_EOL_in_prog58); } break; default : break loop1; } } pushFollow(FOLLOW_block_in_prog61); block1=block(); state._fsp--; node= block1 ; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "prog" // $ANTLR start "block" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:25:1: block returns [SLNode node] : (stats= stat )* ; public final SLNode block() throws RecognitionException { SLNode node = null; SLNode stats =null; BlockNode bn= new BlockNode(); node= bn; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:30:2: ( (stats= stat )* ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:31:2: (stats= stat )* { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:31:2: (stats= stat )* loop2: while (true) { int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0==ID||LA2_0==INT||LA2_0==NUMBER||LA2_0==STRING||LA2_0==17||(LA2_0 >= 21 && LA2_0 <= 22)||LA2_0==24||LA2_0==26||(LA2_0 >= 28 && LA2_0 <= 29)||(LA2_0 >= 32 && LA2_0 <= 33)||(LA2_0 >= 38 && LA2_0 <= 39)||(LA2_0 >= 42 && LA2_0 <= 44)) ) { alt2=1; } switch (alt2) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:31:2: stats= stat { pushFollow(FOLLOW_stat_in_block83); stats=stat(); state._fsp--; bn.addStatement(stats); } break; default : break loop2; } } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "block" // $ANTLR start "stat" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:33:1: stat returns [SLNode node] : ( expr EOL | assignment | for_stat | if_stat | while_stat ); public final SLNode stat() throws RecognitionException { SLNode node = null; SLNode expr2 =null; SLNode assignment3 =null; SLNode for_stat4 =null; SLNode if_stat5 =null; SLNode while_stat6 =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:33:27: ( expr EOL | assignment | for_stat | if_stat | while_stat ) int alt3=5; switch ( input.LA(1) ) { case INT: case NUMBER: case STRING: case 17: case 21: case 22: case 24: case 26: case 28: case 29: case 32: case 33: case 42: case 44: { alt3=1; } break; case ID: { int LA3_2 = input.LA(2); if ( (LA3_2==DOWN||LA3_2==EOL) ) { alt3=1; } else if ( (LA3_2==30) ) { alt3=2; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 3, 2, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case 38: { alt3=3; } break; case 39: { alt3=4; } break; case 43: { alt3=5; } break; default: NoViableAltException nvae = new NoViableAltException("", 3, 0, input); throw nvae; } switch (alt3) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:34:3: expr EOL { pushFollow(FOLLOW_expr_in_stat100); expr2=expr(); state._fsp--; node= expr2; match(input,EOL,FOLLOW_EOL_in_stat104); } break; case 2 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:35:5: assignment { pushFollow(FOLLOW_assignment_in_stat110); assignment3=assignment(); state._fsp--; node=assignment3; } break; case 3 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:36:5: for_stat { pushFollow(FOLLOW_for_stat_in_stat117); for_stat4=for_stat(); state._fsp--; node=for_stat4; } break; case 4 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:37:5: if_stat { pushFollow(FOLLOW_if_stat_in_stat124); if_stat5=if_stat(); state._fsp--; node=if_stat5; } break; case 5 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:38:5: while_stat { pushFollow(FOLLOW_while_stat_in_stat132); while_stat6=while_stat(); state._fsp--; node = while_stat6; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "stat" // $ANTLR start "assignment" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:42:1: assignment returns [SLNode node] : ID '=' expr EOL ; public final SLNode assignment() throws RecognitionException { SLNode node = null; CommonTree ID7=null; SLNode expr8 =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:42:33: ( ID '=' expr EOL ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:42:35: ID '=' expr EOL { ID7=(CommonTree)match(input,ID,FOLLOW_ID_in_assignment153); match(input,30,FOLLOW_30_in_assignment155); pushFollow(FOLLOW_expr_in_assignment157); expr8=expr(); state._fsp--; node= new AssignmentNode(ID7.getText(), expr8,memory); match(input,EOL,FOLLOW_EOL_in_assignment166); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "assignment" // $ANTLR start "for_stat" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:47:1: for_stat returns [SLNode node] : ^( 'for' item= ID items= expr action= block ) ; public final SLNode for_stat() throws RecognitionException { SLNode node = null; CommonTree item=null; SLNode items =null; SLNode action =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:47:31: ( ^( 'for' item= ID items= expr action= block ) ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:48:3: ^( 'for' item= ID items= expr action= block ) { match(input,38,FOLLOW_38_in_for_stat185); match(input, Token.DOWN, null); item=(CommonTree)match(input,ID,FOLLOW_ID_in_for_stat189); pushFollow(FOLLOW_expr_in_for_stat193); items=expr(); state._fsp--; pushFollow(FOLLOW_block_in_for_stat197); action=block(); state._fsp--; match(input, Token.UP, null); node= new ForNode(item.getText(), items, action, memory); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "for_stat" // $ANTLR start "if_stat" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:54:1: if_stat returns [SLNode node] : 'if' condition= expr ':' EOL INDENT blk= block DEDENT ( EOL )* ( 'elif' cond= expr ':' EOL INDENT blk1= block DEDENT ( EOL )* )* ( 'else' ':' EOL INDENT blk2= block DEDENT ( EOL )* )? ; public final SLNode if_stat() throws RecognitionException { SLNode node = null; SLNode condition =null; SLNode blk =null; SLNode cond =null; SLNode blk1 =null; SLNode blk2 =null; IfNode ifnode= new IfNode(); node= ifnode; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:59:2: ( 'if' condition= expr ':' EOL INDENT blk= block DEDENT ( EOL )* ( 'elif' cond= expr ':' EOL INDENT blk1= block DEDENT ( EOL )* )* ( 'else' ':' EOL INDENT blk2= block DEDENT ( EOL )* )? ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:59:2: 'if' condition= expr ':' EOL INDENT blk= block DEDENT ( EOL )* ( 'elif' cond= expr ':' EOL INDENT blk1= block DEDENT ( EOL )* )* ( 'else' ':' EOL INDENT blk2= block DEDENT ( EOL )* )? { match(input,39,FOLLOW_39_in_if_stat223); pushFollow(FOLLOW_expr_in_if_stat227); condition=expr(); state._fsp--; match(input,27,FOLLOW_27_in_if_stat229); match(input,EOL,FOLLOW_EOL_in_if_stat231); match(input,INDENT,FOLLOW_INDENT_in_if_stat233); pushFollow(FOLLOW_block_in_if_stat237); blk=block(); state._fsp--; match(input,DEDENT,FOLLOW_DEDENT_in_if_stat239); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:59:54: ( EOL )* loop4: while (true) { int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0==EOL) ) { alt4=1; } switch (alt4) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:59:54: EOL { match(input,EOL,FOLLOW_EOL_in_if_stat241); } break; default : break loop4; } } ifnode.addChoice(condition, blk); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:63:2: ( 'elif' cond= expr ':' EOL INDENT blk1= block DEDENT ( EOL )* )* loop6: while (true) { int alt6=2; int LA6_0 = input.LA(1); if ( (LA6_0==36) ) { alt6=1; } switch (alt6) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:63:2: 'elif' cond= expr ':' EOL INDENT blk1= block DEDENT ( EOL )* { match(input,36,FOLLOW_36_in_if_stat248); pushFollow(FOLLOW_expr_in_if_stat252); cond=expr(); state._fsp--; match(input,27,FOLLOW_27_in_if_stat254); match(input,EOL,FOLLOW_EOL_in_if_stat255); match(input,INDENT,FOLLOW_INDENT_in_if_stat257); pushFollow(FOLLOW_block_in_if_stat261); blk1=block(); state._fsp--; match(input,DEDENT,FOLLOW_DEDENT_in_if_stat263); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:63:51: ( EOL )* loop5: while (true) { int alt5=2; int LA5_0 = input.LA(1); if ( (LA5_0==EOL) ) { alt5=1; } switch (alt5) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:63:51: EOL { match(input,EOL,FOLLOW_EOL_in_if_stat265); } break; default : break loop5; } } ifnode.addChoice(cond, blk1); } break; default : break loop6; } } // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:69:2: ( 'else' ':' EOL INDENT blk2= block DEDENT ( EOL )* )? int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0==37) ) { alt8=1; } switch (alt8) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:69:2: 'else' ':' EOL INDENT blk2= block DEDENT ( EOL )* { match(input,37,FOLLOW_37_in_if_stat278); match(input,27,FOLLOW_27_in_if_stat280); match(input,EOL,FOLLOW_EOL_in_if_stat282); match(input,INDENT,FOLLOW_INDENT_in_if_stat284); pushFollow(FOLLOW_block_in_if_stat288); blk2=block(); state._fsp--; match(input,DEDENT,FOLLOW_DEDENT_in_if_stat290); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:69:42: ( EOL )* loop7: while (true) { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0==EOL) ) { alt7=1; } switch (alt7) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:69:42: EOL { match(input,EOL,FOLLOW_EOL_in_if_stat292); } break; default : break loop7; } } ifnode.addElse(blk2); } break; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "if_stat" // $ANTLR start "while_stat" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:76:1: while_stat returns [SLNode node] : ^( 'while' condition= expr action= block ) ; public final SLNode while_stat() throws RecognitionException { SLNode node = null; SLNode condition =null; SLNode action =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:76:33: ( ^( 'while' condition= expr action= block ) ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:77:3: ^( 'while' condition= expr action= block ) { match(input,43,FOLLOW_43_in_while_stat317); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_while_stat321); condition=expr(); state._fsp--; pushFollow(FOLLOW_block_in_while_stat325); action=block(); state._fsp--; match(input, Token.UP, null); node = new WhileNode(condition, action); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "while_stat" // $ANTLR start "expr" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:83:1: expr returns [SLNode node] : ( ^( '+' a= expr b= expr ) | ^( '-' a= expr b= expr ) | ^( '*' a= expr b= expr ) | ^( '/' a= expr b= expr ) | ^( '<' a= expr b= expr ) | ^( '>' a= expr b= expr ) | ^( '<=' a= expr b= expr ) | ^( '>=' a= expr b= expr ) | ^( '!=' a= expr b= expr ) | ID | INT | NUMBER | STRING | 'print' stuff= expr | ^( ID tail ) | makelist_expr ); public final SLNode expr() throws RecognitionException { SLNode node = null; CommonTree ID9=null; CommonTree INT10=null; CommonTree NUMBER11=null; CommonTree STRING12=null; CommonTree ID13=null; SLNode a =null; SLNode b =null; SLNode stuff =null; SLNode tail14 =null; SLNode makelist_expr15 =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:84:2: ( ^( '+' a= expr b= expr ) | ^( '-' a= expr b= expr ) | ^( '*' a= expr b= expr ) | ^( '/' a= expr b= expr ) | ^( '<' a= expr b= expr ) | ^( '>' a= expr b= expr ) | ^( '<=' a= expr b= expr ) | ^( '>=' a= expr b= expr ) | ^( '!=' a= expr b= expr ) | ID | INT | NUMBER | STRING | 'print' stuff= expr | ^( ID tail ) | makelist_expr ) int alt9=16; switch ( input.LA(1) ) { case 22: { alt9=1; } break; case 24: { alt9=2; } break; case 21: { alt9=3; } break; case 26: { alt9=4; } break; case 28: { alt9=5; } break; case 32: { alt9=6; } break; case 29: { alt9=7; } break; case 33: { alt9=8; } break; case 17: { alt9=9; } break; case ID: { int LA9_10 = input.LA(2); if ( (LA9_10==DOWN) ) { alt9=15; } else if ( (LA9_10==UP||LA9_10==EOL||LA9_10==ID||LA9_10==INT||LA9_10==NUMBER||LA9_10==STRING||LA9_10==17||(LA9_10 >= 20 && LA9_10 <= 24)||(LA9_10 >= 26 && LA9_10 <= 29)||(LA9_10 >= 32 && LA9_10 <= 33)||(LA9_10 >= 38 && LA9_10 <= 39)||(LA9_10 >= 42 && LA9_10 <= 44)) ) { alt9=10; } else { int nvaeMark = input.mark(); try { input.consume(); NoViableAltException nvae = new NoViableAltException("", 9, 10, input); throw nvae; } finally { input.rewind(nvaeMark); } } } break; case INT: { alt9=11; } break; case NUMBER: { alt9=12; } break; case STRING: { alt9=13; } break; case 42: { alt9=14; } break; case 44: { alt9=16; } break; default: NoViableAltException nvae = new NoViableAltException("", 9, 0, input); throw nvae; } switch (alt9) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:84:4: ^( '+' a= expr b= expr ) { match(input,22,FOLLOW_22_in_expr343); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr347); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr351); b=expr(); state._fsp--; match(input, Token.UP, null); node = new AddNode(a, b); } break; case 2 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:85:4: ^( '-' a= expr b= expr ) { match(input,24,FOLLOW_24_in_expr360); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr364); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr368); b=expr(); state._fsp--; match(input, Token.UP, null); node = new SubNode(a, b); } break; case 3 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:86:4: ^( '*' a= expr b= expr ) { match(input,21,FOLLOW_21_in_expr377); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr381); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr385); b=expr(); state._fsp--; match(input, Token.UP, null); node = new MulNode(a, b); } break; case 4 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:87:4: ^( '/' a= expr b= expr ) { match(input,26,FOLLOW_26_in_expr394); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr398); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr402); b=expr(); state._fsp--; match(input, Token.UP, null); node = new DivNode(a, b); } break; case 5 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:88:4: ^( '<' a= expr b= expr ) { match(input,28,FOLLOW_28_in_expr411); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr415); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr419); b=expr(); state._fsp--; match(input, Token.UP, null); node = new CompNode(a, b, "<"); } break; case 6 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:89:4: ^( '>' a= expr b= expr ) { match(input,32,FOLLOW_32_in_expr428); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr432); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr436); b=expr(); state._fsp--; match(input, Token.UP, null); node = new CompNode(a, b, ">"); } break; case 7 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:90:4: ^( '<=' a= expr b= expr ) { match(input,29,FOLLOW_29_in_expr445); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr449); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr453); b=expr(); state._fsp--; match(input, Token.UP, null); node = new CompNode(a, b, "<="); } break; case 8 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:91:4: ^( '>=' a= expr b= expr ) { match(input,33,FOLLOW_33_in_expr463); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr467); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr471); b=expr(); state._fsp--; match(input, Token.UP, null); node = new CompNode(a, b, ">="); } break; case 9 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:92:4: ^( '!=' a= expr b= expr ) { match(input,17,FOLLOW_17_in_expr480); match(input, Token.DOWN, null); pushFollow(FOLLOW_expr_in_expr484); a=expr(); state._fsp--; pushFollow(FOLLOW_expr_in_expr488); b=expr(); state._fsp--; match(input, Token.UP, null); node = new CompNode(a, b, "!="); } break; case 10 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:93:4: ID { ID9=(CommonTree)match(input,ID,FOLLOW_ID_in_expr496); node= new IdNode(ID9.getText(), memory); } break; case 11 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:94:4: INT { INT10=(CommonTree)match(input,INT,FOLLOW_INT_in_expr503); node = new IntNode(INT10.getText()); } break; case 12 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:95:4: NUMBER { NUMBER11=(CommonTree)match(input,NUMBER,FOLLOW_NUMBER_in_expr510); node= new NumNode(NUMBER11.getText()); } break; case 13 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:96:4: STRING { STRING12=(CommonTree)match(input,STRING,FOLLOW_STRING_in_expr516); node = new StringNode(STRING12.getText()); } break; case 14 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:97:4: 'print' stuff= expr { match(input,42,FOLLOW_42_in_expr523); pushFollow(FOLLOW_expr_in_expr527); stuff=expr(); state._fsp--; node = new PrintNode(stuff); } break; case 15 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:98:4: ^( ID tail ) { ID13=(CommonTree)match(input,ID,FOLLOW_ID_in_expr535); match(input, Token.DOWN, null); pushFollow(FOLLOW_tail_in_expr537); tail14=tail(); state._fsp--; match(input, Token.UP, null); node = new FunctionCallNode(new IdNode(ID13.getText(), memory),tail14); } break; case 16 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:99:4: makelist_expr { pushFollow(FOLLOW_makelist_expr_in_expr545); makelist_expr15=makelist_expr(); state._fsp--; node = makelist_expr15; } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "expr" // $ANTLR start "tail" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:102:2: tail returns [SLNode node] : '.' ID params ; public final SLNode tail() throws RecognitionException { SLNode node = null; CommonTree ID16=null; List<SLNode> params17 =null; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:102:28: ( '.' ID params ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:102:30: '.' ID params { match(input,25,FOLLOW_25_in_tail563); ID16=(CommonTree)match(input,ID,FOLLOW_ID_in_tail565); pushFollow(FOLLOW_params_in_tail567); params17=params(); state._fsp--; node = new TailNode(ID16.getText(), params17); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "tail" // $ANTLR start "params" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:107:2: params returns [List<SLNode> node] : '(' (p1= expr )? ( ',' p2= expr )* ')' ; public final List<SLNode> params() throws RecognitionException { List<SLNode> node = null; SLNode p1 =null; SLNode p2 =null; List<SLNode> parameters = new ArrayList<SLNode>(); node = parameters; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:112:3: ( '(' (p1= expr )? ( ',' p2= expr )* ')' ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:113:2: '(' (p1= expr )? ( ',' p2= expr )* ')' { match(input,19,FOLLOW_19_in_params591); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:113:8: (p1= expr )? int alt10=2; int LA10_0 = input.LA(1); if ( (LA10_0==ID||LA10_0==INT||LA10_0==NUMBER||LA10_0==STRING||LA10_0==17||(LA10_0 >= 21 && LA10_0 <= 22)||LA10_0==24||LA10_0==26||(LA10_0 >= 28 && LA10_0 <= 29)||(LA10_0 >= 32 && LA10_0 <= 33)||LA10_0==42||LA10_0==44) ) { alt10=1; } switch (alt10) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:113:8: p1= expr { pushFollow(FOLLOW_expr_in_params595); p1=expr(); state._fsp--; } break; } parameters.add(p1); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:113:43: ( ',' p2= expr )* loop11: while (true) { int alt11=2; int LA11_0 = input.LA(1); if ( (LA11_0==23) ) { alt11=1; } switch (alt11) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:113:44: ',' p2= expr { match(input,23,FOLLOW_23_in_params601); pushFollow(FOLLOW_expr_in_params605); p2=expr(); state._fsp--; parameters.add(p2); } break; default : break loop11; } } match(input,20,FOLLOW_20_in_params610); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "params" // $ANTLR start "makelist_expr" // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:116:2: makelist_expr returns [SLNode node] : 'list' '(' e= expr ( ',' e1= expr )* ')' ; public final SLNode makelist_expr() throws RecognitionException { SLNode node = null; SLNode e =null; SLNode e1 =null; ListNode listnode = new ListNode(); node = listnode; try { // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:121:2: ( 'list' '(' e= expr ( ',' e1= expr )* ')' ) // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:121:4: 'list' '(' e= expr ( ',' e1= expr )* ')' { match(input,44,FOLLOW_44_in_makelist_expr632); match(input,19,FOLLOW_19_in_makelist_expr634); pushFollow(FOLLOW_expr_in_makelist_expr638); e=expr(); state._fsp--; listnode.addItem(e); // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:121:50: ( ',' e1= expr )* loop12: while (true) { int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0==23) ) { alt12=1; } switch (alt12) { case 1 : // C:\\Users\\Jangedoo\\Documents\\GitHub\\PythonScriptingLanguage\\src\\pythonj\\TreeWalker.g:121:51: ',' e1= expr { match(input,23,FOLLOW_23_in_makelist_expr642); pushFollow(FOLLOW_expr_in_makelist_expr646); e1=expr(); state._fsp--; listnode.addItem(e1); } break; default : break loop12; } } match(input,20,FOLLOW_20_in_makelist_expr651); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return node; } // $ANTLR end "makelist_expr" // Delegated rules public static final BitSet FOLLOW_EOL_in_prog58 = new BitSet(new long[]{0x00001CC335625540L}); public static final BitSet FOLLOW_block_in_prog61 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_stat_in_block83 = new BitSet(new long[]{0x00001CC335625502L}); public static final BitSet FOLLOW_expr_in_stat100 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_EOL_in_stat104 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_assignment_in_stat110 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_for_stat_in_stat117 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_if_stat_in_stat124 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_while_stat_in_stat132 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ID_in_assignment153 = new BitSet(new long[]{0x0000000040000000L}); public static final BitSet FOLLOW_30_in_assignment155 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_assignment157 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_EOL_in_assignment166 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_38_in_for_stat185 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_ID_in_for_stat189 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_for_stat193 = new BitSet(new long[]{0x00001CC335625508L}); public static final BitSet FOLLOW_block_in_for_stat197 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_39_in_if_stat223 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_if_stat227 = new BitSet(new long[]{0x0000000008000000L}); public static final BitSet FOLLOW_27_in_if_stat229 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_EOL_in_if_stat231 = new BitSet(new long[]{0x0000000000000200L}); public static final BitSet FOLLOW_INDENT_in_if_stat233 = new BitSet(new long[]{0x00001CC335625520L}); public static final BitSet FOLLOW_block_in_if_stat237 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_DEDENT_in_if_stat239 = new BitSet(new long[]{0x0000003000000042L}); public static final BitSet FOLLOW_EOL_in_if_stat241 = new BitSet(new long[]{0x0000003000000042L}); public static final BitSet FOLLOW_36_in_if_stat248 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_if_stat252 = new BitSet(new long[]{0x0000000008000000L}); public static final BitSet FOLLOW_27_in_if_stat254 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_EOL_in_if_stat255 = new BitSet(new long[]{0x0000000000000200L}); public static final BitSet FOLLOW_INDENT_in_if_stat257 = new BitSet(new long[]{0x00001CC335625520L}); public static final BitSet FOLLOW_block_in_if_stat261 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_DEDENT_in_if_stat263 = new BitSet(new long[]{0x0000003000000042L}); public static final BitSet FOLLOW_EOL_in_if_stat265 = new BitSet(new long[]{0x0000003000000042L}); public static final BitSet FOLLOW_37_in_if_stat278 = new BitSet(new long[]{0x0000000008000000L}); public static final BitSet FOLLOW_27_in_if_stat280 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_EOL_in_if_stat282 = new BitSet(new long[]{0x0000000000000200L}); public static final BitSet FOLLOW_INDENT_in_if_stat284 = new BitSet(new long[]{0x00001CC335625520L}); public static final BitSet FOLLOW_block_in_if_stat288 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_DEDENT_in_if_stat290 = new BitSet(new long[]{0x0000000000000042L}); public static final BitSet FOLLOW_EOL_in_if_stat292 = new BitSet(new long[]{0x0000000000000042L}); public static final BitSet FOLLOW_43_in_while_stat317 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_while_stat321 = new BitSet(new long[]{0x00001CC335625508L}); public static final BitSet FOLLOW_block_in_while_stat325 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_22_in_expr343 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr347 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr351 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_24_in_expr360 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr364 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr368 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_21_in_expr377 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr381 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr385 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_26_in_expr394 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr398 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr402 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_28_in_expr411 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr415 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr419 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_32_in_expr428 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr432 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr436 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_29_in_expr445 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr449 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr453 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_33_in_expr463 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr467 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr471 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_17_in_expr480 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_expr_in_expr484 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr488 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_ID_in_expr496 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_INT_in_expr503 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NUMBER_in_expr510 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_STRING_in_expr516 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_42_in_expr523 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_expr527 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_ID_in_expr535 = new BitSet(new long[]{0x0000000000000004L}); public static final BitSet FOLLOW_tail_in_expr537 = new BitSet(new long[]{0x0000000000000008L}); public static final BitSet FOLLOW_makelist_expr_in_expr545 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_25_in_tail563 = new BitSet(new long[]{0x0000000000000100L}); public static final BitSet FOLLOW_ID_in_tail565 = new BitSet(new long[]{0x0000000000080000L}); public static final BitSet FOLLOW_params_in_tail567 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_19_in_params591 = new BitSet(new long[]{0x0000140335F25500L}); public static final BitSet FOLLOW_expr_in_params595 = new BitSet(new long[]{0x0000000000900000L}); public static final BitSet FOLLOW_23_in_params601 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_params605 = new BitSet(new long[]{0x0000000000900000L}); public static final BitSet FOLLOW_20_in_params610 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_44_in_makelist_expr632 = new BitSet(new long[]{0x0000000000080000L}); public static final BitSet FOLLOW_19_in_makelist_expr634 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_makelist_expr638 = new BitSet(new long[]{0x0000000000900000L}); public static final BitSet FOLLOW_23_in_makelist_expr642 = new BitSet(new long[]{0x0000140335625500L}); public static final BitSet FOLLOW_expr_in_makelist_expr646 = new BitSet(new long[]{0x0000000000900000L}); public static final BitSet FOLLOW_20_in_makelist_expr651 = new BitSet(new long[]{0x0000000000000002L}); }
gpl-2.0
SFYA/rebeca1
src/main/java/org/rebecalang/compiler/modelcompiler/timedrebeca/objectmodel/package-info.java
607
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.10.04 at 10:23:12 AM GMT // @javax.xml.bind.annotation.XmlSchema(namespace = "http://rebecalang.org/compiler/modelcompiler/timedrebecaexpression", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.rebecalang.compiler.modelcompiler.timedrebeca.objectmodel;
gpl-2.0
dmcennis/jMir
jMIR_2_4_developer/jSymbolic/src/jsymbolic/features/NumberOfCommonMelodicIntervalsFeature.java
3387
/* * NumberOfCommonMelodicIntervalsFeature.java * Version 1.2 * * Last modified on April 11, 2010. * McGill University */ package jsymbolic.features; import java.util.LinkedList; import javax.sound.midi.*; import ace.datatypes.FeatureDefinition; import jsymbolic.processing.MIDIIntermediateRepresentations; /** * A feature exractor that finds the number of melodic intervals that represent * at least 9% of all melodic intervals. * * <p>No extracted feature values are stored in objects of this class. * * @author Cory McKay */ public class NumberOfCommonMelodicIntervalsFeature extends MIDIFeatureExtractor { /* CONSTRUCTOR ***********************************************************/ /** * Basic constructor that sets the definition and dependencies (and their * offsets) of this feature. */ public NumberOfCommonMelodicIntervalsFeature() { String name = "Number of Common Melodic Intervals"; String description = "Number of melodic intervals that represent at least\n" + "9% of all melodic intervals."; boolean is_sequential = true; int dimensions = 1; definition = new FeatureDefinition( name, description, is_sequential, dimensions ); dependencies = null; offsets = null; } /* PUBLIC METHODS ********************************************************/ /** * Extracts this feature from the given MIDI sequence given the other * feature values. * * <p>In the case of this feature, the other_feature_values parameters * are ignored. * * @param sequence The MIDI sequence to extract the feature * from. * @param sequence_info Additional data about the MIDI sequence. * @param other_feature_values The values of other features that are * needed to calculate this value. The * order and offsets of these features * must be the same as those returned by * this class's getDependencies and * getDependencyOffsets methods * respectively. The first indice indicates * the feature/window and the second * indicates the value. * @return The extracted feature value(s). * @throws Exception Throws an informative exception if the * feature cannot be calculated. */ public double[] extractFeature( Sequence sequence, MIDIIntermediateRepresentations sequence_info, double[][] other_feature_values ) throws Exception { double value; if (sequence_info != null) { // Find the number of pitches int count = 0; for (int bin = 0; bin < sequence_info.melodic_histogram.length; bin++) if (sequence_info.melodic_histogram[bin] >= 0.09) count++; // Calculate the value value = (double) count; } else value = -1.0; double[] result = new double[1]; result[0] = value; return result; } }
gpl-2.0
tauprojects/mpp
src/main/java/hashtables/lockfree/cliffutils/AbstractEntry.java
1754
/* * Written by Cliff Click and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package hashtables.lockfree.cliffutils; import java.util.Map; /** * A simple implementation of {@link java.util.Map.Entry}. * Does not implement {@link java.util.Map.Entry.setValue}, that is done by users of the class. * * @since 1.5 * @author Cliff Click * @param <TypeK> the type of keys maintained by this map * @param <TypeV> the type of mapped values */ public abstract class AbstractEntry<TypeK,TypeV> implements Map.Entry<TypeK,TypeV> { /** Strongly typed key */ protected final TypeK _key; /** Strongly typed value */ protected TypeV _val; public AbstractEntry(final TypeK key, final TypeV val) { _key = key; _val = val; } public AbstractEntry(final Map.Entry<TypeK,TypeV> e ) { _key = e.getKey(); _val = e.getValue(); } /** Return "key=val" string */ public String toString() { return _key + "=" + _val; } /** Return key */ public TypeK getKey () { return _key; } /** Return val */ public TypeV getValue() { return _val; } /** Equal if the underlying key & value are equal */ public boolean equals(final Object o) { if (!(o instanceof Map.Entry)) return false; final Map.Entry e = (Map.Entry)o; return eq(_key, e.getKey()) && eq(_val, e.getValue()); } /** Compute <code>"key.hashCode() ^ val.hashCode()"</code> */ public int hashCode() { return ((_key == null) ? 0 : _key.hashCode()) ^ ((_val == null) ? 0 : _val.hashCode()); } private static boolean eq(final Object o1, final Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } }
gpl-2.0
timomwa/cmp
src/main/java/com/pixelandtag/sms/mt/workerthreads/GenericHTTPParam.java
1903
package com.pixelandtag.sms.mt.workerthreads; import java.io.Serializable; import java.util.List; import java.util.Map; import javax.ws.rs.HttpMethod; import org.apache.http.NameValuePair; import com.pixelandtag.bulksms.BulkSMSQueue; import com.pixelandtag.entities.MTsms; import com.pixelandtag.sms.producerthreads.Billable; /** * * @author Timothy * Holds generic http params. * TODO add header. * */ public class GenericHTTPParam implements Serializable{ /** * */ private static final long serialVersionUID = 8834391423692237679L; private String url; private Long id; private MTsms mtsms; private BulkSMSQueue bulktext; private List<NameValuePair> httpParams; private Map<String,String> headerParams; private String stringentity; private String httpmethod; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<NameValuePair> getHttpParams() { return httpParams; } public void setHttpParams(List<NameValuePair> httpParams) { this.httpParams = httpParams; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public MTsms getMtsms() { return mtsms; } public void setMtsms(MTsms mtsms) { this.mtsms = mtsms; } public Map<String, String> getHeaderParams() { return headerParams; } public void setHeaderParams(Map<String, String> headerParams) { this.headerParams = headerParams; } public String getStringentity() { return stringentity; } public void setStringentity(String stringentity) { this.stringentity = stringentity; } public BulkSMSQueue getBulktext() { return bulktext; } public void setBulktext(BulkSMSQueue bulktext) { this.bulktext = bulktext; } public String getHttpmethod() { return httpmethod==null ? HttpMethod.POST : httpmethod; } public void setHttpmethod(String httpmethod) { this.httpmethod = httpmethod; } }
gpl-2.0
InfinityStudio/ExoticPower
src/main/java/infstudio/exoticpower/api/item/IToolWrench.java
946
package infstudio.exoticpower.api.item; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.BlockPos; public interface IToolWrench { /*** * Called to ensure that the wrench can be used. To get the ItemStack that is used, check player.inventory.getCurrentItem() * * @param player - The player doing the wrenching * @param bp - The coordinates for the block being wrenched * @return true if wrenching is allowed, false if not */ boolean canWrench(EntityPlayer player, BlockPos bp); /*** * Callback after the wrench has been used. This can be used to decrease durability or for other purposes. To get the ItemStack that was used, check * player.inventory.getCurrentItem() * * @param player - The player doing the wrenching * @param bp - The coordinates of the block being wrenched */ void wrenchUsed(EntityPlayer player, BlockPos bp); }
gpl-2.0
CarlAtComputer/tracker
playground/other_gef/Filesystem.diagram/src/jfb/examples/gmf/filesystem/diagram/edit/policies/FileItemSemanticEditPolicy.java
4039
package jfb.examples.gmf.filesystem.diagram.edit.policies; import java.util.Iterator; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand; import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyReferenceCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyReferenceRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientReferenceRelationshipRequest; import org.eclipse.gmf.runtime.notation.Edge; import org.eclipse.gmf.runtime.notation.View; import jfb.examples.gmf.filesystem.diagram.edit.commands.FolderFilesCreateCommand; import jfb.examples.gmf.filesystem.diagram.edit.commands.FolderFilesReorientCommand; import jfb.examples.gmf.filesystem.diagram.edit.parts.FolderFilesEditPart; import jfb.examples.gmf.filesystem.diagram.part.FilesystemVisualIDRegistry; import jfb.examples.gmf.filesystem.diagram.providers.FilesystemElementTypes; /** * @generated */ public class FileItemSemanticEditPolicy extends FilesystemBaseItemSemanticEditPolicy { /** * @generated */ public FileItemSemanticEditPolicy() { super(FilesystemElementTypes.File_2002); } /** * @generated */ protected Command getDestroyElementCommand(DestroyElementRequest req) { View view = (View) getHost().getModel(); CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null); cmd.setTransactionNestingEnabled(false); for (Iterator<?> it = view.getTargetEdges().iterator(); it.hasNext();) { Edge incomingLink = (Edge) it.next(); if (FilesystemVisualIDRegistry.getVisualID(incomingLink) == FolderFilesEditPart.VISUAL_ID) { DestroyReferenceRequest r = new DestroyReferenceRequest(incomingLink.getSource().getElement(), null, incomingLink.getTarget().getElement(), false); cmd.add(new DestroyReferenceCommand(r)); cmd.add(new DeleteCommand(getEditingDomain(), incomingLink)); continue; } } EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$ if (annotation == null) { // there are indirectly referenced children, need extra commands: false addDestroyShortcutsCommand(cmd, view); // delete host element cmd.add(new DestroyElementCommand(req)); } else { cmd.add(new DeleteCommand(getEditingDomain(), view)); } return getGEFWrapper(cmd.reduce()); } /** * @generated */ protected Command getCreateRelationshipCommand(CreateRelationshipRequest req) { Command command = req.getTarget() == null ? getStartCreateRelationshipCommand(req) : getCompleteCreateRelationshipCommand(req); return command != null ? command : super.getCreateRelationshipCommand(req); } /** * @generated */ protected Command getStartCreateRelationshipCommand(CreateRelationshipRequest req) { if (FilesystemElementTypes.FolderFiles_4002 == req.getElementType()) { return null; } return null; } /** * @generated */ protected Command getCompleteCreateRelationshipCommand(CreateRelationshipRequest req) { if (FilesystemElementTypes.FolderFiles_4002 == req.getElementType()) { return getGEFWrapper(new FolderFilesCreateCommand(req, req.getSource(), req.getTarget())); } return null; } /** * Returns command to reorient EReference based link. New link target or source * should be the domain model element associated with this node. * * @generated */ protected Command getReorientReferenceRelationshipCommand(ReorientReferenceRelationshipRequest req) { switch (getVisualID(req)) { case FolderFilesEditPart.VISUAL_ID: return getGEFWrapper(new FolderFilesReorientCommand(req)); } return super.getReorientReferenceRelationshipCommand(req); } }
gpl-2.0
Mimalef/nursys
app/src/main/java/fuzzium/nursys/activities/AddInsurenceActivity.java
3457
package fuzzium.nursys.activities; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.List; import fuzzium.nursys.R; import fuzzium.nursys.entities.Insurence; /** * Created by yasi on 10/7/2015. */ // /* @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_student); student_name_et = (EditText) findViewById(R.id.student_name_et); address_et = (EditText) findViewById(R.id.address_et); teacher_sp = (Spinner) findViewById(R.id.teacher_sp); reset_btn = (Button) findViewById(R.id.reset_btn); submit_btn = (Button) findViewById(R.id.submit_btn); try { // This is how, a reference of DAO object can be done // Need to find out list of TeacherDetails from database, so initialize DAO for TeacherDetails first final Dao<TeacherDetails, Integer> teachDao = getHelper().getTeacherDao(); // Query the database. We need all the records so, used queryForAll() teacherList = teachDao.queryForAll(); // Populate the spinner with Teachers data by using CustomAdapter teacher_sp.setAdapter(new CustomAdapter(this,android.R.layout.simple_spinner_item, android.R.layout.simple_spinner_dropdown_item, teacherList)); } catch (SQLException e) { e.printStackTrace(); } reset_btn.setOnClickListener(this); submit_btn.setOnClickListener(this); } // This is how, DatabaseHelper can be initialized for future use private DatabaseHelper getHelper() { if (databaseHelper == null) { databaseHelper = OpenHelperManager.getHelper(this,DatabaseHelper.class); } return databaseHelper; } * * */ public class AddInsurenceActivity extends ActionBarActivity { private EditText insurenceType,discount; private List<Insurence> insurenceList; private Spinner insur_sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_insurence); initContol(); } private void initContol() { insurenceType=(EditText)findViewById(R.id.insurencname); discount=(EditText)findViewById(R.id.insuranceDiscount); insur_sp = (Spinner) findViewById(R.id.insur_sp); insurenceList=Insurence.listAll(Insurence.class); ArrayAdapter<Insurence> dataAdapter = new ArrayAdapter<Insurence>(this, android.R.layout.simple_spinner_item, insurenceList); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); insur_sp.setAdapter(dataAdapter); } public void registerInsurence(View view) { Insurence newInsurence=new Insurence(); newInsurence.setDiscount(Integer.parseInt(discount.getText().toString())); newInsurence.setInsurenceType(insurenceType.getText().toString()); newInsurence.save(); Insurence in=new Insurence(); in=(Insurence)insur_sp.getSelectedItem(); Toast.makeText(this,String.valueOf(in.getDiscount()),Toast.LENGTH_SHORT).show(); } }
gpl-2.0
akrogp/EhuBio
Projects/java/EhuBio/src/es/ehubio/proteomics/psi/mzid11/PersonType.java
4441
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.06.02 at 06:39:37 PM CEST // package es.ehubio.proteomics.psi.mzid11; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * A person's name and contact details. Any additional information such as the address, contact email etc. should be supplied using CV parameters or user parameters. * * <p>Java class for PersonType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PersonType"> * &lt;complexContent> * &lt;extension base="{http://psidev.info/psi/pi/mzIdentML/1.1}AbstractContactType"> * &lt;sequence> * &lt;element name="Affiliation" type="{http://psidev.info/psi/pi/mzIdentML/1.1}AffiliationType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="lastName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="firstName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="midInitials" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PersonType", propOrder = { "affiliations" }) public class PersonType extends AbstractContactType { @XmlElement(name = "Affiliation") protected List<AffiliationType> affiliations; @XmlAttribute(name = "lastName") protected String lastName; @XmlAttribute(name = "firstName") protected String firstName; @XmlAttribute(name = "midInitials") protected String midInitials; /** * Gets the value of the affiliations property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the affiliations property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAffiliations().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AffiliationType } * * */ public List<AffiliationType> getAffiliations() { if (affiliations == null) { affiliations = new ArrayList<AffiliationType>(); } return this.affiliations; } /** * Gets the value of the lastName property. * * @return * possible object is * {@link String } * */ public String getLastName() { return lastName; } /** * Sets the value of the lastName property. * * @param value * allowed object is * {@link String } * */ public void setLastName(String value) { this.lastName = value; } /** * Gets the value of the firstName property. * * @return * possible object is * {@link String } * */ public String getFirstName() { return firstName; } /** * Sets the value of the firstName property. * * @param value * allowed object is * {@link String } * */ public void setFirstName(String value) { this.firstName = value; } /** * Gets the value of the midInitials property. * * @return * possible object is * {@link String } * */ public String getMidInitials() { return midInitials; } /** * Sets the value of the midInitials property. * * @param value * allowed object is * {@link String } * */ public void setMidInitials(String value) { this.midInitials = value; } }
gpl-2.0
NPGuys/NPGuys
src/main/java/goldob/npguys/exception/MessageNotFoundException.java
1144
/* * NPGuys - Bukkit plugin for better NPC interaction * Copyright (C) 2014 Adam Gotlib <Goldob> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package goldob.npguys.exception; public class MessageNotFoundException extends Exception { /** * */ private static final long serialVersionUID = 1L; String npguy, dialogue; public MessageNotFoundException(String npguy, String dialogue) { this.npguy = npguy; this.dialogue = dialogue; } public String getMessage() { return "Dialogue '"+dialogue+"' not found @ NPGuy '"+npguy+"'!"; } }
gpl-2.0
rex-xxx/mt6572_x201
sdk/lint/libs/lint_api/src/com/android/tools/lint/detector/api/Detector.java
24239
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint.detector.api; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.tools.lint.client.api.LintDriver; import com.google.common.annotations.Beta; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import lombok.ast.AstVisitor; import lombok.ast.MethodInvocation; /** * A detector is able to find a particular problem. It might also be thought of as enforcing * a rule, but "rule" is a bit overloaded in ADT terminology since ViewRules are used in * the Rules API to allow views to specify designtime behavior in the graphical layout editor. * <p> * Each detector provides information about the issues it can find, such as an explanation * of how to fix the issue, the priority, the category, etc. It also has an id which is * used to persistently identify a particular type of error. * <p> * Detectors will be called in a predefined order: * <ol> * <li> Manifest file * <li> Resource files, in alphabetical order by resource type * (therefore, "layout" is checked before "values", "values-de" is checked before * "values-en" but after "values", and so on. * <li> Java sources * <li> Java classes * <li> Proguard files * </ol> * If a detector needs information when processing a file type that comes from a type of * file later in the order above, they can request a second phase; see * {@link LintDriver#requestRepeat}. * <p> * NOTE: Detectors might be constructed just once and shared between lint runs, so * any per-detector state should be initialized and reset via the before/after * methods. * <p/> * <b>NOTE: This is not a public or final API; if you rely on this be prepared * to adjust your code for the next tools release.</b> */ @Beta public abstract class Detector { /** Specialized interface for detectors that scan Java source file parse trees */ public interface JavaScanner { /** * Create a parse tree visitor to process the parse tree. All * {@link JavaScanner} detectors must provide a visitor, unless they * either return true from {@link #appliesToResourceRefs()} or return * non null from {@link #getApplicableMethodNames()}. * <p> * If you return specific AST node types from * {@link #getApplicableNodeTypes()}, then the visitor will <b>only</b> * be called for the specific requested node types. This is more * efficient, since it allows many detectors that apply to only a small * part of the AST (such as method call nodes) to share iteration of the * majority of the parse tree. * <p> * If you return null from {@link #getApplicableNodeTypes()}, then your * visitor will be called from the top and all node types visited. * <p> * Note that a new visitor is created for each separate compilation * unit, so you can store per file state in the visitor. * * @param context the {@link Context} for the file being analyzed * @return a visitor, or null. */ @Nullable AstVisitor createJavaVisitor(@NonNull JavaContext context); /** * Return the types of AST nodes that the visitor returned from * {@link #createJavaVisitor(JavaContext)} should visit. See the * documentation for {@link #createJavaVisitor(JavaContext)} for details * on how the shared visitor is used. * <p> * If you return null from this method, then the visitor will process * the full tree instead. * <p> * Note that for the shared visitor, the return codes from the visit * methods are ignored: returning true will <b>not</b> prune iteration * of the subtree, since there may be other node types interested in the * children. If you need to ensure that your visitor only processes a * part of the tree, use a full visitor instead. See the * OverdrawDetector implementation for an example of this. * * @return the list of applicable node types (AST node classes), or null */ @Nullable List<Class<? extends lombok.ast.Node>> getApplicableNodeTypes(); /** * Return the list of method names this detector is interested in, or * null. If this method returns non-null, then any AST nodes that match * a method call in the list will be passed to the * {@link #visitMethod(JavaContext, AstVisitor, MethodInvocation)} * method for processing. The visitor created by * {@link #createJavaVisitor(JavaContext)} is also passed to that * method, although it can be null. * <p> * This makes it easy to write detectors that focus on some fixed calls. * For example, the StringFormatDetector uses this mechanism to look for * "format" calls, and when found it looks around (using the AST's * {@link lombok.ast.Node#getParent()} method) to see if it's called on * a String class instance, and if so do its normal processing. Note * that since it doesn't need to do any other AST processing, that * detector does not actually supply a visitor. * * @return a set of applicable method names, or null. */ @Nullable List<String> getApplicableMethodNames(); /** * Method invoked for any method calls found that matches any names * returned by {@link #getApplicableMethodNames()}. This also passes * back the visitor that was created by * {@link #createJavaVisitor(JavaContext)}, but a visitor is not * required. It is intended for detectors that need to do additional AST * processing, but also want the convenience of not having to look for * method names on their own. * * @param context the context of the lint request * @param visitor the visitor created from * {@link #createJavaVisitor(JavaContext)}, or null * @param node the {@link MethodInvocation} node for the invoked method */ void visitMethod( @NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node); /** * Returns whether this detector cares about Android resource references * (such as {@code R.layout.main} or {@code R.string.app_name}). If it * does, then the visitor will look for these patterns, and if found, it * will invoke {@link #visitResourceReference} passing the resource type * and resource name. It also passes the visitor, if any, that was * created by {@link #createJavaVisitor(JavaContext)}, such that a * detector can do more than just look for resources. * * @return true if this detector wants to be notified of R resource * identifiers found in the code. */ boolean appliesToResourceRefs(); /** * Called for any resource references (such as {@code R.layout.main} * found in Java code, provided this detector returned {@code true} from * {@link #appliesToResourceRefs()}. * * @param context the lint scanning context * @param visitor the visitor created from * {@link #createJavaVisitor(JavaContext)}, or null * @param node the variable reference for the resource * @param type the resource type, such as "layout" or "string" * @param name the resource name, such as "main" from * {@code R.layout.main} * @param isFramework whether the resource is a framework resource * (android.R) or a local project resource (R) */ void visitResourceReference( @NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull lombok.ast.Node node, @NonNull String type, @NonNull String name, boolean isFramework); } /** Specialized interface for detectors that scan Java class files */ public interface ClassScanner { /** * Checks the given class' bytecode for issues. * * @param context the context of the lint check, pointing to for example * the file * @param classNode the root class node */ void checkClass(@NonNull ClassContext context, @NonNull ClassNode classNode); /** * Returns the list of node types (corresponding to the constants in the * {@link AbstractInsnNode} class) that this scanner applies to. The * {@link #checkInstruction(ClassContext, ClassNode, MethodNode, AbstractInsnNode)} * method will be called for each match. * * @return an array containing all the node types this detector should be * called for, or null if none. */ @Nullable int[] getApplicableAsmNodeTypes(); /** * Process a given instruction node, and register lint issues if * applicable. * * @param context the context of the lint check, pointing to for example * the file * @param classNode the root class node * @param method the method node containing the call * @param instruction the actual instruction */ void checkInstruction(@NonNull ClassContext context, @NonNull ClassNode classNode, @NonNull MethodNode method, @NonNull AbstractInsnNode instruction); /** * Return the list of method call names (in VM format, e.g. "<init>" for * constructors, etc) for method calls this detector is interested in, * or null. T his will be used to dispatch calls to * {@link #checkCall(ClassContext, ClassNode, MethodNode, MethodInsnNode)} * for only the method calls in owners that the detector is interested * in. * <p> * <b>NOTE</b>: If you return non null from this method, then <b>only</b> * {@link #checkCall(ClassContext, ClassNode, MethodNode, MethodInsnNode)} * will be called if a suitable method is found; * {@link #checkClass(ClassContext, ClassNode)} will not be called under * any circumstances. * <p> * This makes it easy to write detectors that focus on some fixed calls, * and allows lint to make a single pass over the bytecode over a class, * and efficiently dispatch method calls to any detectors that are * interested in it. Without this, each new lint check interested in a * single method, would be doing a complete pass through all the * bytecode instructions of the class via the * {@link #checkClass(ClassContext, ClassNode)} method, which would make * each newly added lint check make lint slower. Now a single dispatch * map is used instead, and for each encountered call in the single * dispatch, it looks up in the map which if any detectors are * interested in the given call name, and dispatches to each one in * turn. * * @return a list of applicable method names, or null. */ @Nullable List<String> getApplicableCallNames(); /** * Just like {@link Detector#getApplicableCallNames()}, but for the owner * field instead. The * {@link #checkCall(ClassContext, ClassNode, MethodNode, MethodInsnNode)} * method will be called for all {@link MethodInsnNode} instances where the * owner field matches any of the members returned in this node. * <p> * Note that if your detector provides both a name and an owner, the * method will be called for any nodes matching either the name <b>or</b> * the owner, not only where they match <b>both</b>. Note also that it will * be called twice - once for the name match, and (at least once) for the owner * match. * * @return a list of applicable owner names, or null. */ @Nullable List<String> getApplicableCallOwners(); /** * Process a given method call node, and register lint issues if * applicable. This is similar to the * {@link #checkInstruction(ClassContext, ClassNode, MethodNode, AbstractInsnNode)} * method, but has the additional advantage that it is only called for known * method names or method owners, according to * {@link #getApplicableCallNames()} and {@link #getApplicableCallOwners()}. * * @param context the context of the lint check, pointing to for example * the file * @param classNode the root class node * @param method the method node containing the call * @param call the actual method call node */ void checkCall(@NonNull ClassContext context, @NonNull ClassNode classNode, @NonNull MethodNode method, @NonNull MethodInsnNode call); } /** Specialized interface for detectors that scan XML files */ public interface XmlScanner { /** * Visit the given document. The detector is responsible for its own iteration * through the document. * @param context information about the document being analyzed * @param document the document to examine */ void visitDocument(@NonNull XmlContext context, @NonNull Document document); /** * Visit the given element. * @param context information about the document being analyzed * @param element the element to examine */ void visitElement(@NonNull XmlContext context, @NonNull Element element); /** * Visit the given element after its children have been analyzed. * @param context information about the document being analyzed * @param element the element to examine */ void visitElementAfter(@NonNull XmlContext context, @NonNull Element element); /** * Visit the given attribute. * @param context information about the document being analyzed * @param attribute the attribute node to examine */ void visitAttribute(@NonNull XmlContext context, @NonNull Attr attribute); /** * Returns the list of elements that this detector wants to analyze. If non * null, this detector will be called (specifically, the * {@link #visitElement} method) for each matching element in the document. * <p> * If this method returns null, and {@link #getApplicableAttributes()} also returns * null, then the {@link #visitDocument} method will be called instead. * * @return a collection of elements, or null, or the special * {@link XmlScanner#ALL} marker to indicate that every single * element should be analyzed. */ @Nullable Collection<String> getApplicableElements(); /** * Returns the list of attributes that this detector wants to analyze. If non * null, this detector will be called (specifically, the * {@link #visitAttribute} method) for each matching attribute in the document. * <p> * If this method returns null, and {@link #getApplicableElements()} also returns * null, then the {@link #visitDocument} method will be called instead. * * @return a collection of attributes, or null, or the special * {@link XmlScanner#ALL} marker to indicate that every single * attribute should be analyzed. */ @Nullable Collection<String> getApplicableAttributes(); /** * Special marker collection returned by {@link #getApplicableElements()} or * {@link #getApplicableAttributes()} to indicate that the check should be * invoked on all elements or all attributes */ @NonNull public static final List<String> ALL = new ArrayList<String>(0); // NOT Collections.EMPTY! // We want to distinguish this from just an *empty* list returned by the caller! } /** * Runs the detector. This method will not be called for certain specialized * detectors, such as {@link XmlScanner} and {@link JavaScanner}, where * there are specialized analysis methods instead such as * {@link XmlScanner#visitElement(XmlContext, Element)}. * * @param context the context describing the work to be done */ public void run(@NonNull Context context) { } /** * Returns true if this detector applies to the given file * * @param context the context to check * @param file the file in the context to check * @return true if this detector applies to the given context and file */ public boolean appliesTo(@NonNull Context context, @NonNull File file) { return false; } /** * Analysis is about to begin, perform any setup steps. * * @param context the context for the check referencing the project, lint * client, etc */ public void beforeCheckProject(@NonNull Context context) { } /** * Analysis has just been finished for the whole project, perform any * cleanup or report issues that require project-wide analysis. * * @param context the context for the check referencing the project, lint * client, etc */ public void afterCheckProject(@NonNull Context context) { } /** * Analysis is about to begin for the given library project, perform any setup steps. * * @param context the context for the check referencing the project, lint * client, etc */ public void beforeCheckLibraryProject(@NonNull Context context) { } /** * Analysis has just been finished for the given library project, perform any * cleanup or report issues that require library-project-wide analysis. * * @param context the context for the check referencing the project, lint * client, etc */ public void afterCheckLibraryProject(@NonNull Context context) { } /** * Analysis is about to be performed on a specific file, perform any setup * steps. * <p> * Note: When this method is called at the beginning of checking an XML * file, the context is guaranteed to be an instance of {@link XmlContext}, * and similarly for a Java source file, the context will be a * {@link JavaContext} and so on. * * @param context the context for the check referencing the file to be * checked, the project, etc. */ public void beforeCheckFile(@NonNull Context context) { } /** * Analysis has just been finished for a specific file, perform any cleanup * or report issues found * <p> * Note: When this method is called at the end of checking an XML * file, the context is guaranteed to be an instance of {@link XmlContext}, * and similarly for a Java source file, the context will be a * {@link JavaContext} and so on. * * @param context the context for the check referencing the file to be * checked, the project, etc. */ public void afterCheckFile(@NonNull Context context) { } /** * Returns the expected speed of this detector * * @return the expected speed of this detector */ @NonNull public Speed getSpeed() { return Speed.NORMAL; } // ---- Dummy implementations to make implementing XmlScanner easier: ---- @SuppressWarnings("javadoc") public void visitDocument(@NonNull XmlContext context, @NonNull Document document) { // This method must be overridden if your detector does // not return something from getApplicableElements or // getApplicableATtributes assert false; } @SuppressWarnings("javadoc") public void visitElement(@NonNull XmlContext context, @NonNull Element element) { // This method must be overridden if your detector returns // tag names from getApplicableElements assert false; } @SuppressWarnings("javadoc") public void visitElementAfter(@NonNull XmlContext context, @NonNull Element element) { } @SuppressWarnings("javadoc") public void visitAttribute(@NonNull XmlContext context, @NonNull Attr attribute) { // This method must be overridden if your detector returns // attribute names from getApplicableAttributes assert false; } @SuppressWarnings("javadoc") @Nullable public Collection<String> getApplicableElements() { return null; } @Nullable @SuppressWarnings("javadoc") public Collection<String> getApplicableAttributes() { return null; } // ---- Dummy implementations to make implementing JavaScanner easier: ---- @Nullable @SuppressWarnings("javadoc") public List<String> getApplicableMethodNames() { return null; } @Nullable @SuppressWarnings("javadoc") public AstVisitor createJavaVisitor(@NonNull JavaContext context) { return null; } @Nullable @SuppressWarnings("javadoc") public List<Class<? extends lombok.ast.Node>> getApplicableNodeTypes() { return null; } @SuppressWarnings("javadoc") public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { } @SuppressWarnings("javadoc") public boolean appliesToResourceRefs() { return false; } @SuppressWarnings("javadoc") public void visitResourceReference(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull lombok.ast.Node node, @NonNull String type, @NonNull String name, boolean isFramework) { } // ---- Dummy implementations to make implementing a ClassScanner easier: ---- @SuppressWarnings("javadoc") public void checkClass(@NonNull ClassContext context, @NonNull ClassNode classNode) { } @SuppressWarnings("javadoc") @Nullable public List<String> getApplicableCallNames() { return null; } @SuppressWarnings("javadoc") @Nullable public List<String> getApplicableCallOwners() { return null; } @SuppressWarnings("javadoc") public void checkCall(@NonNull ClassContext context, @NonNull ClassNode classNode, @NonNull MethodNode method, @NonNull MethodInsnNode call) { } @SuppressWarnings("javadoc") @Nullable public int[] getApplicableAsmNodeTypes() { return null; } @SuppressWarnings("javadoc") public void checkInstruction(@NonNull ClassContext context, @NonNull ClassNode classNode, @NonNull MethodNode method, @NonNull AbstractInsnNode instruction) { } }
gpl-2.0
gpalma/gdbb
ve/usb/gdbb/DensestSubgraph.java
7538
/* * Copyright (C) 2013, Universidad Simon Bolivar * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package ve.usb.gdbb; import java.util.*; public class DensestSubgraph { private ArrayList<Integer> inDegrees; private ArrayList<Integer> outDegrees; private ArrayList<String> indexToString; private HashMap<String, Integer> stringToIndex; private Boolean validIn[]; private Boolean validOut[]; private ArrayList<ArrayList<Integer>> predecessors; private Integer addedVertexs; /* Comparator used to sort nodes by in degree by increasing order */ private class CustomComparatorInDegree implements Comparator<Integer> { public int compare(Integer o1, Integer o2) { if (!validIn[o1].booleanValue() && validIn[o2].booleanValue()) { return 1; } else if (validIn[o1].booleanValue() && !validIn[o2].booleanValue()) { return -1; } else if (!validIn[o1].booleanValue() && !validIn[o2].booleanValue()) { return 0; } return inDegrees.get(o1).compareTo(inDegrees.get(o2)); } } /* Comparator used to sort nodes by out degree by increasing order */ private class CustomComparatorOutDegree implements Comparator<Integer> { public int compare(Integer o1, Integer o2) { if (!validOut[o1].booleanValue() && validOut[o2].booleanValue()) { return 1; } else if (validOut[o1].booleanValue() && !validOut[o2].booleanValue()) { return -1; } else if (!validOut[o1].booleanValue() && !validOut[o2].booleanValue()) { return 0; } return outDegrees.get(o1).compareTo(outDegrees.get(o2)); } } public DensestSubgraph(){ } /* Procedure that updates the predecessors of all nodes * in the graph. */ private void initializePredecessors(Graph g) { GraphIterator<String> itNodes = g.getNodes(); this.addedVertexs = 0; while (itNodes.hasNext()) { addNode(itNodes.next()); } itNodes.close(); GraphIterator<Edge> it = g.getEdges(); Edge curEdge; while (it.hasNext()) { curEdge = it.next(); predecessors.get(stringToIndex.get(curEdge.getDst())) .add(stringToIndex.get(curEdge.getSrc())); } it.close(); } private void addNode(String nodeId) { if (!stringToIndex.containsKey(nodeId)) { stringToIndex.put(nodeId, addedVertexs); indexToString.add(addedVertexs, nodeId); predecessors.add(addedVertexs, new ArrayList<Integer>()); addedVertexs++; } } /* Procedure that deletes all incoming edges from the node * with "nodeIndex" as index. */ protected void deleteIncoming(int nodeIndex) { ArrayList<Integer> pred = predecessors.get(nodeIndex); int size = pred.size(), predIndx; for (int i = 0; i < size; i++) { predIndx = pred.get(i); if (validOut[predIndx]) { outDegrees.set(predIndx, outDegrees.get(predIndx) - 1); } } validIn[nodeIndex] = false; } /* Procedure that deletes all outgoing edges from the node * with "nodeIndex" as index. */ protected void deleteOutgoing(int nodeIndex, Graph g) { GraphIterator<String> it = g.adj(indexToString.get(nodeIndex)); int succIndx; while (it.hasNext()) { succIndx = stringToIndex.get(it.next()); if (validIn[succIndx]) { inDegrees.set(succIndx, inDegrees.get(succIndx) - 1); } } it.close(); validOut[nodeIndex] = false; } /* Function used to calculate the current density of the graph */ private double calculateDensity(Graph g) { int EdgesST = 0; ArrayList<Integer> S = new ArrayList<Integer>(); ArrayList<Integer> T = new ArrayList<Integer>(); GraphIterator<String> it; int sizeIn = inDegrees.size(); int sizeOut = outDegrees.size(); for ( int i = 0; i < sizeIn; i++ ) { if (validIn[i]) { if (inDegrees.get(i) > 0) { T.add(i); } } } for ( int j = 0; j < sizeOut; j++ ) { if (validOut[j]) { if (outDegrees.get(j) > 0) { S.add(j); } } } int sizeS = S.size(), curr, indexCurr; for (int i = 0; i < sizeS; i++) { curr = S.get(i); it = g.adj(indexToString.get(curr)); while (it.hasNext()) { indexCurr = stringToIndex.get(it.next()); if(validIn[indexCurr]){ EdgesST++; } } it.close(); } int sizeT = T.size(); return sizeS*sizeT != 0 ? (EdgesST/Math.sqrt(sizeS*sizeT)) : 0.0; } public Graph DenseSubgraph(Graph g) { ArrayList<Integer> indexIn = new ArrayList<Integer>(); ArrayList<Integer> indexOut = new ArrayList<Integer>(); GraphIterator<String> it = g.getNodes(); int i, j, vertexs, vertexsAll = g.V(); double density, tmp; String cur; Boolean densestValidIn[] = new Boolean[vertexsAll]; Boolean densestValidOut[] = new Boolean[vertexsAll]; this.indexToString = new ArrayList<String>(); this.stringToIndex = new HashMap<String, Integer>(); this.inDegrees = new ArrayList<Integer>(); this.outDegrees = new ArrayList<Integer>(); this.validIn = new Boolean[vertexsAll]; this.validOut = new Boolean[vertexsAll]; this.predecessors = new ArrayList<ArrayList<Integer>>(); initializePredecessors(g); i = 0; while (it.hasNext()) { cur = it.next(); inDegrees.add(g.getInDegree(cur)); outDegrees.add(g.getOutDegree(cur)); indexIn.add(i); indexOut.add(i); i++; } it.close(); for (int k = 0; k < vertexsAll; k++) { validIn[k] = true; validOut[k] = true; densestValidIn[k] = true; densestValidOut[k] = true; } Collections.sort(indexIn, new CustomComparatorInDegree()); Collections.sort(indexOut, new CustomComparatorOutDegree()); density = calculateDensity(g); i = 0; j = 0; vertexs = 2*vertexsAll; while ( vertexs > 0 ) { if (i < vertexsAll && j < vertexsAll) { if (inDegrees.get(indexIn.get(0)) <= outDegrees.get(indexOut.get(0)) ) { deleteIncoming(indexIn.get(0)); i++; } else { deleteOutgoing(indexOut.get(0), g); j++; } } else if (i < vertexsAll && j == vertexsAll) { deleteIncoming(indexIn.get(0)); i++; } else if (i == vertexsAll && j < vertexsAll) { deleteOutgoing(indexOut.get(0), g); j++; } tmp = calculateDensity(g); if (density < tmp) { density = tmp; for (int k = 0; k < vertexsAll; k++) { densestValidIn[k] = this.validIn[k]; densestValidOut[k] = this.validOut[k]; } } Collections.sort(indexIn, new CustomComparatorInDegree()); Collections.sort(indexOut, new CustomComparatorOutDegree()); vertexs--; } Graph densestGraph = new DiGraphAdjList(); GraphIterator<Edge> itEdges = g.getEdges(); Edge curEdge; int srcIndx, dstIndx; while (itEdges.hasNext()) { curEdge = itEdges.next(); srcIndx = stringToIndex.get(curEdge.getSrc()); dstIndx = stringToIndex.get(curEdge.getDst()); if (densestValidOut[srcIndx] && densestValidIn[dstIndx]) { densestGraph.addNode(curEdge.getSrc()); densestGraph.addNode(curEdge.getDst()); densestGraph.addEdge(curEdge); } } itEdges.close(); return densestGraph; } }
gpl-2.0
smalyshev/blazegraph
bigdata-rdf/src/java/com/bigdata/rdf/changesets/DelegatingChangeLog.java
3170
/** Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.bigdata.rdf.changesets; import java.util.concurrent.CopyOnWriteArraySet; import org.apache.log4j.Logger; /** * This delegating change log allows change events to be propagated to multiple * delegates through a listener pattern. * * @author mike */ public class DelegatingChangeLog implements IChangeLog { private static transient final Logger log = Logger .getLogger(DelegatingChangeLog.class); private final CopyOnWriteArraySet<IChangeLog> delegates; public DelegatingChangeLog() { this.delegates = new CopyOnWriteArraySet<IChangeLog>(); } @Override public String toString() { return getClass().getName() + "{delegates=" + delegates.toString() + "}"; } public void addDelegate(final IChangeLog delegate) { this.delegates.add(delegate); } public void removeDelegate(final IChangeLog delegate) { this.delegates.remove(delegate); } @Override public void changeEvent(final IChangeRecord record) { if (log.isInfoEnabled()) log.info(record); for (IChangeLog delegate : delegates) { delegate.changeEvent(record); } } @Override public void transactionBegin() { if (log.isInfoEnabled()) log.info(""); for (IChangeLog delegate : delegates) { delegate.transactionBegin(); } } @Override public void transactionPrepare() { if (log.isInfoEnabled()) log.info(""); for (IChangeLog delegate : delegates) { delegate.transactionPrepare(); } } @Override public void transactionCommited(final long commitTime) { if (log.isInfoEnabled()) log.info("transaction committed"); for (IChangeLog delegate : delegates) { delegate.transactionCommited(commitTime); } } @Override public void transactionAborted() { if (log.isInfoEnabled()) log.info("transaction aborted"); for (IChangeLog delegate : delegates) { delegate.transactionAborted(); } } }
gpl-2.0
speakingcode/andrioidaudiostream
app/src/main/java/com/speakingcode/android/media/mediaplayer/IMediaPlayerServiceClient.java
646
package com.speakingcode.android.media.mediaplayer; /** * Created by unknown on 9/15/14. */ public interface IMediaPlayerServiceClient { /** * A callback made by a MediaPlayerService onto its clients to indicate that a player is initializing. */ public void onInitializePlayerStart(); /** * A callback made by a MediaPlayerService onto its clients to indicate that a player was successfully initialized. */ public void onInitializePlayerSuccess(); /** * A callback made by a MediaPlayerService onto its clients to indicate that a player encountered an error. */ public void onError(); }
gpl-2.0
tkdiooo/framework
QI-Basic/QI-Basic-Menu/src/main/java/com/qi/menu/web/controller/EntityController.java
1297
package com.qi.menu.web.controller; import com.qi.common.constants.JdbcConstants; import com.qi.common.model.model.DBConfigModel; import com.qi.common.tool.Logger; import com.qi.common.util.ResponseUtil; import com.qi.menu.web.service.read.EntityReadService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Class EntityController * * @author 张麒 2016/9/27. * @version Description: */ @Controller @RequestMapping("/entity") public class EntityController { private static final Logger logger = new Logger(EntityController.class); @Autowired private EntityReadService readService; @RequestMapping(value = "index.html") public String index(ModelMap model) { return "entity/index"; } @RequestMapping(value = "findTableForZTree.ajax") public void findMenuForZTree(DBConfigModel configModel, HttpServletResponse response) throws IOException { configModel.setDriver(JdbcConstants.Driver.MySQL); ResponseUtil.writeJson(readService.findTableNameByDBName(configModel), response); } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/hibernate-core/org/hibernate/boot/model/process/spi/MetadataBuildingProcess.java
14489
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.boot.model.process.spi; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.hibernate.boot.AttributeConverterInfo; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.internal.InFlightMetadataCollectorImpl; import org.hibernate.boot.internal.MetadataBuildingContextRootImpl; import org.hibernate.boot.jaxb.internal.MappingBinder; import org.hibernate.boot.model.TypeContributions; import org.hibernate.boot.model.TypeContributor; import org.hibernate.boot.model.process.internal.ManagedResourcesImpl; import org.hibernate.boot.model.process.internal.ScanningCoordinator; import org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl; import org.hibernate.boot.model.source.internal.hbm.EntityHierarchyBuilder; import org.hibernate.boot.model.source.internal.hbm.EntityHierarchySourceImpl; import org.hibernate.boot.model.source.internal.hbm.HbmMetadataSourceProcessorImpl; import org.hibernate.boot.model.source.internal.hbm.MappingDocument; import org.hibernate.boot.model.source.internal.hbm.ModelBinder; import org.hibernate.boot.model.source.spi.MetadataSourceProcessor; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.spi.AdditionalJaxbMappingProducer; import org.hibernate.boot.spi.BasicTypeRegistration; import org.hibernate.boot.spi.BootstrapContext; import org.hibernate.boot.spi.MetadataBuildingOptions; import org.hibernate.boot.spi.MetadataContributor; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.MetadataSourceType; import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.type.BasicType; import org.hibernate.type.BasicTypeRegistry; import org.hibernate.type.descriptor.java.JavaTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; import org.hibernate.type.spi.TypeConfiguration; import org.hibernate.usertype.CompositeUserType; import org.hibernate.usertype.UserType; import org.jboss.jandex.IndexView; import org.jboss.logging.Logger; /** * Represents the process of of transforming a {@link org.hibernate.boot.MetadataSources} * reference into a {@link org.hibernate.boot.Metadata} reference. Allows for 2 different process paradigms:<ul> * <li> * Single step : as defined by the {@link #build} method; internally leverages the 2-step paradigm * </li> * <li> * Two step : a first step coordinates resource scanning and some other preparation work; a second step * builds the {@link org.hibernate.boot.Metadata}. A hugely important distinction in the need for the * steps is that the first phase should strive to not load user entity/component classes so that we can still * perform enhancement on them later. This approach caters to the 2-phase bootstrap we use in regards * to WildFly Hibernate-JPA integration. The first step is defined by {@link #prepare} which returns * a {@link ManagedResources} instance. The second step is defined by calling * {@link #complete} * </li> * </ul> * * @author Steve Ebersole */ public class MetadataBuildingProcess { private static final Logger log = Logger.getLogger( MetadataBuildingProcess.class ); /** * Unified single phase for MetadataSources->Metadata process * * @param sources The MetadataSources * @param options The building options * * @return The built Metadata */ public static MetadataImplementor build( final MetadataSources sources, final BootstrapContext bootstrapContext, final MetadataBuildingOptions options) { return complete( prepare( sources, bootstrapContext ), bootstrapContext, options ); } /** * First step of 2-phase for MetadataSources->Metadata process * * @param sources The MetadataSources * @param bootstrapContext The bootstrapContext * * @return Token/memento representing all known users resources (classes, packages, mapping files, etc). */ public static ManagedResources prepare( final MetadataSources sources, final BootstrapContext bootstrapContext) { final ManagedResourcesImpl managedResources = ManagedResourcesImpl.baseline( sources, bootstrapContext ); ScanningCoordinator.INSTANCE.coordinateScan( managedResources, bootstrapContext, sources.getXmlMappingBinderAccess() ); return managedResources; } /** * Second step of 2-phase for MetadataSources->Metadata process * * @param managedResources The token/memento from 1st phase * @param options The building options * * @return Token/memento representing all known users resources (classes, packages, mapping files, etc). */ public static MetadataImplementor complete( final ManagedResources managedResources, final BootstrapContext bootstrapContext, final MetadataBuildingOptions options) { final InFlightMetadataCollectorImpl metadataCollector = new InFlightMetadataCollectorImpl( bootstrapContext, options ); handleTypes( bootstrapContext, options ); final ClassLoaderService classLoaderService = options.getServiceRegistry().getService( ClassLoaderService.class ); final MetadataBuildingContextRootImpl rootMetadataBuildingContext = new MetadataBuildingContextRootImpl( bootstrapContext, options, metadataCollector ); for ( AttributeConverterInfo converterInfo : managedResources.getAttributeConverterDefinitions() ) { metadataCollector.addAttributeConverter( converterInfo.toConverterDescriptor( rootMetadataBuildingContext ) ); } bootstrapContext.getTypeConfiguration().scope( rootMetadataBuildingContext ); final IndexView jandexView = bootstrapContext.getJandexView(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Set up the processors and start binding // NOTE : this becomes even more simplified after we move purely // to unified model final MetadataSourceProcessor processor = new MetadataSourceProcessor() { private final HbmMetadataSourceProcessorImpl hbmProcessor = new HbmMetadataSourceProcessorImpl( managedResources, rootMetadataBuildingContext ); private final AnnotationMetadataSourceProcessorImpl annotationProcessor = new AnnotationMetadataSourceProcessorImpl( managedResources, rootMetadataBuildingContext, jandexView ); @Override public void prepare() { hbmProcessor.prepare(); annotationProcessor.prepare(); } @Override public void processTypeDefinitions() { hbmProcessor.processTypeDefinitions(); annotationProcessor.processTypeDefinitions(); } @Override public void processQueryRenames() { hbmProcessor.processQueryRenames(); annotationProcessor.processQueryRenames(); } @Override public void processNamedQueries() { hbmProcessor.processNamedQueries(); annotationProcessor.processNamedQueries(); } @Override public void processAuxiliaryDatabaseObjectDefinitions() { hbmProcessor.processAuxiliaryDatabaseObjectDefinitions(); annotationProcessor.processAuxiliaryDatabaseObjectDefinitions(); } @Override public void processIdentifierGenerators() { hbmProcessor.processIdentifierGenerators(); annotationProcessor.processIdentifierGenerators(); } @Override public void processFilterDefinitions() { hbmProcessor.processFilterDefinitions(); annotationProcessor.processFilterDefinitions(); } @Override public void processFetchProfiles() { hbmProcessor.processFetchProfiles(); annotationProcessor.processFetchProfiles(); } @Override public void prepareForEntityHierarchyProcessing() { for ( MetadataSourceType metadataSourceType : options.getSourceProcessOrdering() ) { if ( metadataSourceType == MetadataSourceType.HBM ) { hbmProcessor.prepareForEntityHierarchyProcessing(); } if ( metadataSourceType == MetadataSourceType.CLASS ) { annotationProcessor.prepareForEntityHierarchyProcessing(); } } } @Override public void processEntityHierarchies(Set<String> processedEntityNames) { for ( MetadataSourceType metadataSourceType : options.getSourceProcessOrdering() ) { if ( metadataSourceType == MetadataSourceType.HBM ) { hbmProcessor.processEntityHierarchies( processedEntityNames ); } if ( metadataSourceType == MetadataSourceType.CLASS ) { annotationProcessor.processEntityHierarchies( processedEntityNames ); } } } @Override public void postProcessEntityHierarchies() { for ( MetadataSourceType metadataSourceType : options.getSourceProcessOrdering() ) { if ( metadataSourceType == MetadataSourceType.HBM ) { hbmProcessor.postProcessEntityHierarchies(); } if ( metadataSourceType == MetadataSourceType.CLASS ) { annotationProcessor.postProcessEntityHierarchies(); } } } @Override public void processResultSetMappings() { hbmProcessor.processResultSetMappings(); annotationProcessor.processResultSetMappings(); } @Override public void finishUp() { hbmProcessor.finishUp(); annotationProcessor.finishUp(); } }; processor.prepare(); processor.processTypeDefinitions(); processor.processQueryRenames(); processor.processAuxiliaryDatabaseObjectDefinitions(); processor.processIdentifierGenerators(); processor.processFilterDefinitions(); processor.processFetchProfiles(); final Set<String> processedEntityNames = new HashSet<>(); processor.prepareForEntityHierarchyProcessing(); processor.processEntityHierarchies( processedEntityNames ); processor.postProcessEntityHierarchies(); processor.processResultSetMappings(); processor.processNamedQueries(); processor.finishUp(); for ( MetadataContributor contributor : classLoaderService.loadJavaServices( MetadataContributor.class ) ) { log.tracef( "Calling MetadataContributor : %s", contributor ); contributor.contribute( metadataCollector, jandexView ); } metadataCollector.processSecondPasses( rootMetadataBuildingContext ); Iterable<AdditionalJaxbMappingProducer> producers = classLoaderService.loadJavaServices( AdditionalJaxbMappingProducer.class ); if ( producers != null ) { final EntityHierarchyBuilder hierarchyBuilder = new EntityHierarchyBuilder(); // final MappingBinder mappingBinder = new MappingBinder( true ); // We need to disable validation here. It seems Envers is not producing valid (according to schema) XML final MappingBinder mappingBinder = new MappingBinder( classLoaderService, false ); for ( AdditionalJaxbMappingProducer producer : producers ) { log.tracef( "Calling AdditionalJaxbMappingProducer : %s", producer ); Collection<MappingDocument> additionalMappings = producer.produceAdditionalMappings( metadataCollector, jandexView, mappingBinder, rootMetadataBuildingContext ); for ( MappingDocument mappingDocument : additionalMappings ) { hierarchyBuilder.indexMappingDocument( mappingDocument ); } } ModelBinder binder = ModelBinder.prepare( rootMetadataBuildingContext ); for ( EntityHierarchySourceImpl entityHierarchySource : hierarchyBuilder.buildHierarchies() ) { binder.bindEntityHierarchy( entityHierarchySource ); } } return metadataCollector.buildMetadataInstance( rootMetadataBuildingContext ); } // todo (7.0) : buildJandexInitializer // private static JandexInitManager buildJandexInitializer( // MetadataBuildingOptions options, // ClassLoaderAccess classLoaderAccess) { // final boolean autoIndexMembers = ConfigurationHelper.getBoolean( // org.hibernate.cfg.AvailableSettings.ENABLE_AUTO_INDEX_MEMBER_TYPES, // options.getServiceRegistry().getService( ConfigurationService.class ).getSettings(), // false // ); // // return new JandexInitManager( options.getJandexView(), classLoaderAccess, autoIndexMembers ); // } private static void handleTypes(BootstrapContext bootstrapContext, MetadataBuildingOptions options) { final ClassLoaderService classLoaderService = options.getServiceRegistry().getService( ClassLoaderService.class ); final TypeContributions typeContributions = new TypeContributions() { @Override public void contributeType(org.hibernate.type.BasicType type) { getBasicTypeRegistry().register( type ); } @Override public void contributeType(BasicType type, String... keys) { getBasicTypeRegistry().register( type, keys ); } @Override public void contributeType(UserType type, String[] keys) { getBasicTypeRegistry().register( type, keys ); } @Override public void contributeType(CompositeUserType type, String[] keys) { getBasicTypeRegistry().register( type, keys ); } @Override public void contributeJavaTypeDescriptor(JavaTypeDescriptor descriptor) { bootstrapContext.getTypeConfiguration().getJavaTypeDescriptorRegistry().addDescriptor( descriptor ); } @Override public void contributeSqlTypeDescriptor(SqlTypeDescriptor descriptor) { bootstrapContext.getTypeConfiguration().getSqlTypeDescriptorRegistry().addDescriptor( descriptor ); } @Override public TypeConfiguration getTypeConfiguration() { return bootstrapContext.getTypeConfiguration(); } final BasicTypeRegistry getBasicTypeRegistry() { return bootstrapContext.getTypeConfiguration().getBasicTypeRegistry(); } }; // add Dialect contributed types final Dialect dialect = options.getServiceRegistry().getService( JdbcServices.class ).getDialect(); dialect.contributeTypes( typeContributions, options.getServiceRegistry() ); // add TypeContributor contributed types. for ( TypeContributor contributor : classLoaderService.loadJavaServices( TypeContributor.class ) ) { contributor.contribute( typeContributions, options.getServiceRegistry() ); } // add explicit application registered types for ( BasicTypeRegistration basicTypeRegistration : options.getBasicTypeRegistrations() ) { bootstrapContext.getTypeConfiguration().getBasicTypeRegistry().register( basicTypeRegistration.getBasicType(), basicTypeRegistration.getRegistrationKeys() ); } } }
gpl-2.0
mornsun/javascratch
src/topcoder/xLC_857_Minimum_Cost_to_Hire_K_Workers.java
2744
/** * */ package topcoder; import java.util.*; /** * There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i]. Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules: Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. Every worker in the paid group must be paid at least their minimum wage expectation. Return the least amount of money needed to form a paid group satisfying the above conditions. Example 1: Input: quality = [10,20,5], wage = [70,50,30], K = 2 Output: 105.00000 Explanation: We pay 70 to 0-th worker and 35 to 2-th worker. Example 2: Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3 Output: 30.66667 Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately. Note: 1 <= K <= N <= 10000, where N = quality.length = wage.length 1 <= quality[i] <= 10000 1 <= wage[i] <= 10000 Answers within 10^-5 of the correct answer will be considered correct. Related Topic Heap * @author Chauncey * */ public class xLC_857_Minimum_Cost_to_Hire_K_Workers { public double mincostToHireWorkers(int[] quality, int[] wage, int K) { if (quality == null || quality.length == 0 || wage == null || wage.length != quality.length || K < 1) { return 0.0; } int n = quality.length; double[][] workers = new double[n][]; for (int i=0; i<n; ++i) { workers[i] = new double[]{(double)wage[i] / quality[i], (double)wage[i], (double)quality[i]}; } Arrays.sort(workers, (a, b) -> Double.compare(a[0], b[0])); PriorityQueue<Double> heap = new PriorityQueue<Double>(); double sum_heap = 0.0; double ans = Double.MAX_VALUE; for (double[] worker : workers) { heap.offer(-worker[2]); sum_heap += worker[2]; if (heap.size() > K) { sum_heap += heap.poll(); } if (heap.size() == K) { ans = Double.min(ans, sum_heap * worker[0]); } } return ans; } /** * @param args */ public static void main(String[] args) { long startTime = System.currentTimeMillis(); xLC_857_Minimum_Cost_to_Hire_K_Workers solution = new xLC_857_Minimum_Cost_to_Hire_K_Workers(); System.out.println(solution.mincostToHireWorkers(new int[]{10,20,5}, new int[]{70,50,30}, 2)); System.out.println(solution.mincostToHireWorkers(new int[]{3,1,10,10,1}, new int[]{4,8,2,2,7}, 3)); System.out.println("elapsed:" + (System.currentTimeMillis() - startTime)); } }
gpl-2.0
oonym/l2InterludeServer
L2J_Server/java/net/sf/l2j/gameserver/serverpackets/ExDuelUpdateUserInfo.java
1791
/* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package net.sf.l2j.gameserver.serverpackets; import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance; /** * Format: ch Sddddddddd * @author KenM */ public class ExDuelUpdateUserInfo extends L2GameServerPacket { private static final String _S__FE_4F_EXDUELUPDATEUSERINFO = "[S] FE:4F ExDuelUpdateUserInfo"; private final L2PcInstance _activeChar; public ExDuelUpdateUserInfo(L2PcInstance cha) { _activeChar = cha; } @Override protected void writeImpl() { writeC(0xfe); writeH(0x4f); writeS(_activeChar.getName()); writeD(_activeChar.getObjectId()); writeD(_activeChar.getClassId().getId()); writeD(_activeChar.getLevel()); writeD((int) _activeChar.getCurrentHp()); writeD(_activeChar.getMaxHp()); writeD((int) _activeChar.getCurrentMp()); writeD(_activeChar.getMaxMp()); writeD((int) _activeChar.getCurrentCp()); writeD(_activeChar.getMaxCp()); } @Override public String getType() { return _S__FE_4F_EXDUELUPDATEUSERINFO; } }
gpl-2.0
SeekingFor/jfniki
src/fniki/wiki/GraphLog.java
30576
// KNOWN LIMITATION: Doesn't handle 'octopus merges'. Suppports at most 2 parents per rev. /* Class to draw the revision graph. * * Changes Copyright (C) 2010, 2011 Darrell Karbott (see below). * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: djk@isFiaD04zgAgnrEC5XJt1i4IE7AkNPqhBG5bONi6Yks (changes) * * This file was developed as component of * "fniki" (a wiki implementation running over Freenet). * * This file is a derived work based on the graphlog.py * from rev:643b8212813e in the mercurial hg-stable repo. * * sha1sum graphlog.py * a0e599d4bd0b483025f0b5f182e737d8682a88ba graphlog.py * * Original header: * # ASCII graph log extension for Mercurial * # * # Copyright 2007 Joel Rosdahl <joel@rosdahl.net> * # * # This software may be used and distributed according to the terms of the * # GNU General Public License version 2 or any later version. * */ package fniki.wiki; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class GraphLog { //////////////////////////////////////////////////////////// // A quick and dirty port of the first ~= 200 lines of // graphlog.py from the mercurial codebase. //////////////////////////////////////////////////////////// public static ColumnData asciiedges(List<Integer> seen, int rev, List<Integer> parents) { // """adds edge info to changelog DAG walk suitable for ascii()""" if (!seen.contains(rev)) { seen.add(rev); } int nodeidx = seen.indexOf(rev); // i.e. just looking up the index of the rev // seen maps revs -> ordinals List<Integer> known_parents = new ArrayList<Integer>(); List<Integer> new_parents = new ArrayList<Integer>(); for (int parent : parents) { if (seen.contains(parent)) { known_parents.add(parent); } else { new_parents.add(parent); } } int ncols = seen.size(); seen.remove(nodeidx); // Correct? trying to get python slice assignement semantics seen.addAll(nodeidx, new_parents); List<AsciiEdge> edges = new ArrayList<AsciiEdge>(); for (int parent : known_parents) { edges.add(new AsciiEdge(nodeidx, seen.indexOf(parent))); } if (new_parents.size() > 0) { edges.add(new AsciiEdge(nodeidx, nodeidx)); } if (new_parents.size() > 1) { edges.add(new AsciiEdge(nodeidx, nodeidx + 1)); } int nmorecols = seen.size() - ncols; String edgeDump = ""; for (AsciiEdge edge : edges) { edgeDump += String.format("(%d, %d), ", edge.mStart, edge.mEnd); } return new ColumnData(nodeidx, edges, ncols, nmorecols); } static void fix_long_right_edges(List<AsciiEdge> edges) { int index = 0; for (AsciiEdge edge : edges) { if (edge.mEnd > edge.mStart) { edges.set(index, new AsciiEdge(edge.mStart, edge.mEnd + 1)); } index++; } } static List<String> get_nodeline_edges_tail(int node_index, int p_node_index, int n_columns, int n_columns_diff, int p_diff, boolean fix_tail) { if (fix_tail && n_columns_diff == p_diff && n_columns_diff != 0) { //# Still going in the same non-vertical direction. if (n_columns_diff == -1) { int start = Math.max(node_index + 1, p_node_index); List<String> tail = repeat(BAR_SPACE, (start - node_index - 1)); tail.addAll(repeat(SLASH_SPACE, (n_columns - start))); return tail; } else { return repeat(BACKSLASH_SPACE, (n_columns - node_index - 1)); } } else { return repeat(BAR_SPACE, (n_columns - node_index - 1)); } } static void draw_edges(List<AsciiEdge> edges, List<String> nodeline, List<String> interline) { int index = 0; for (AsciiEdge edge : edges) { if (edge.mStart == edge.mEnd + 1) { interline.set(2 * edge.mEnd + 1, "/"); } else if (edge.mStart == edge.mEnd - 1) { interline.set(2 * edge.mStart + 1, "\\"); } else if (edge.mStart == edge.mEnd) { interline.set(2 * edge.mStart, "|"); } else { nodeline.set(2 * edge.mEnd, "+"); if (edge.mStart > edge.mEnd) { edge = new AsciiEdge(edge.mEnd, edge.mStart); } for (int j = 2 * edge.mStart + 1; j < 2 * edge.mEnd; j++) { if (!nodeline.get(j).equals("+")) { nodeline.set(j, "-"); } } } index++; } } static List<String> get_padding_line(int ni, int n_columns, List<AsciiEdge> edges) { List<String> line = new ArrayList<String>(); line.addAll(repeat(BAR_SPACE, ni)); String c = null; //if (ni, ni - 1) in edges or (ni, ni) in edges: if (edges.contains(new AsciiEdge(ni, ni - 1)) || edges.contains(new AsciiEdge(ni, ni))) { //# (ni, ni - 1) (ni, ni) //# | | | | | | | | //# +---o | | o---+ //# | | c | | c | | //# | |/ / | |/ / //# | | | | | | c = "|"; } else { c = " "; } line.add(c); line.add(" "); line.addAll(repeat(BAR_SPACE, (n_columns - ni - 1))); return line; } public static AsciiState asciistate() { //"""returns the initial value for the "state" argument to ascii()""" return new AsciiState(0, 0); } static boolean should_add_padding_line(List<String> text, int coldiff, List<AsciiEdge> edges) { //add_padding_line = (len(text) > 2 and coldiff == -1 and // [x for (x, y) in edges if x + 1 < y]) if (!(text.size() > 2 && coldiff == -1)) { return false; } for (AsciiEdge edge : edges) { if (edge.mStart + 1 < edge.mEnd) { return true; } } return false; } // # Called once for each entry in the dag list public static void ascii(Writer ui, AsciiState state, /* type, */ String nodeChar, List<String> text, ColumnData coldata) throws IOException { //"""prints an ASCII graph of the DAG // //takes the following arguments (one call per node in the graph): //- ui to write to //- Somewhere to keep the needed state in (init to asciistate()) //- Column of the current node in the set of ongoing edges. //- Type indicator of node data == ASCIIDATA. //- Payload: (char, lines): //- Character to use as node's symbol. //- List of lines to display as the node's text. //- Edges; a list of (col, next_col) indicating the edges between // the current node and its parents. //- Number of columns (ongoing edges) in the current revision. //- The difference between the number of columns (ongoing edges) // in the next revision and the number of columns (ongoing edges) // in the current revision. That is: -1 means one column removed; // 0 means no columns added or removed; 1 means one column added. // """ int idx = coldata.mNodeIdx; List<AsciiEdge> edges = coldata.mEdges; int ncols = coldata.mNCols; int coldiff = coldata.mMoreCols; assert_(coldiff > -2 && coldiff < 2); if (coldiff == -1) { //# Transform //# //# | | | | | | //# o | | into o---+ //# |X / |/ / //# | | | | fix_long_right_edges(edges); } //# add_padding_line says whether to rewrite //# //# | | | | | | | | //# | o---+ into | o---+ //# | / / | | | # <--- padding line //# o | | | / / //# o | | //add_padding_line = (len(text) > 2 and coldiff == -1 and // [x for (x, y) in edges if x + 1 < y]) boolean add_padding_line = should_add_padding_line(text, coldiff, edges); //# fix_nodeline_tail says whether to rewrite //# //# | | o | | | | o | | //# | | |/ / | | |/ / //# | o | | into | o / / # <--- fixed nodeline tail //# | |/ / | |/ / //# o | | o | | boolean fix_nodeline_tail = (text.size() <= 2) && (!add_padding_line); // # nodeline is the line containing the node character (typically o) List<String> nodeline = repeat(BAR_SPACE, idx); nodeline.add(nodeChar); nodeline.add(" "); nodeline.addAll(get_nodeline_edges_tail(idx, state.mIdx, ncols, coldiff, state.mColDiff, fix_nodeline_tail)); //# shift_interline is the line containing the non-vertical //# edges between this entry and the next List<String> shift_interline = repeat(BAR_SPACE, idx); String edge_ch = null; int n_spaces = -1; if (coldiff == -1) { n_spaces = 1; edge_ch = "/"; } else if (coldiff == 0) { n_spaces = 2; edge_ch = "|"; } else { n_spaces = 3; edge_ch = "\\"; } shift_interline.addAll(repeat(ONE_SPACE, n_spaces)); List<String> valueToRepeat = new ArrayList<String>(); valueToRepeat.add(edge_ch); valueToRepeat.add(" "); shift_interline.addAll(repeat(valueToRepeat, (ncols - idx - 1))); //# draw edges from the current node to its parents draw_edges(edges, nodeline, shift_interline); //# lines is the list of all graph lines to print List<String> lines = new ArrayList<String>(Arrays.asList(list_to_string(nodeline))); if (add_padding_line) { lines.add(list_to_string(get_padding_line(idx, ncols, edges))); } lines.add(list_to_string(shift_interline)); //# make sure that there are as many graph lines as there are //# log strings while (text.size() < lines.size()) { text.add(""); } if (lines.size() < text.size()) { String extra_interline = list_to_string(repeat(BAR_SPACE, (ncols + coldiff))); while (lines.size() < text.size()) { lines.add(extra_interline); } } //# print lines int indentation_level = Math.max(ncols, ncols + coldiff); assert_(lines.size() == text.size()); int index = 0; for (String line : lines) { String logstr = text.get(index); index++; // "%-*s => means "left justify string with width specified in the tuple" // ln = "%-*s %s" % (2 * indentation_level, "".join(line), logstr) String fmt = "%-" + ("" + (2 * indentation_level)).trim() + "s %s"; ui.write(rstrip(String.format(fmt, line, logstr))); ui.write("\n"); } state.mColDiff = coldiff; state.mIdx = idx; } //////////////////////////////////////////////////////////// // Helper data structures and functions used to port // to Java. //////////////////////////////////////////////////////////// static final class AsciiEdge { public final int mStart; public final int mEnd; AsciiEdge(int start, int end) { mStart = start; mEnd = end; } } public static final class ColumnData { public final int mNodeIdx; public final int mNCols; public final List<AsciiEdge> mEdges; public final int mMoreCols; public ColumnData(int nodeidx, List<AsciiEdge> edges, int ncols, int nmorecols) { mNodeIdx = nodeidx; mEdges = edges; mNCols = ncols; mMoreCols = nmorecols; } } // NOT immutable. Hrmmm.. public static class AsciiState { public int mColDiff; public int mIdx; public AsciiState(int coldiff, int idx) { mColDiff = coldiff; mIdx = idx; } } // A directed graph node. public static class DAGNode implements Comparable<DAGNode> { public final String mTag; public final int mId; public final List<Integer> mParentIds; DAGNode(String tag, int id, List<Integer> parentIds) { mTag = tag; mId = id; mParentIds = parentIds; } public int compareTo(DAGNode other) { return other.mId - mId; // Descending order of integer id. } public String asString() { return "{" + mTag + ", " + mId + ", " + GraphLog.prettyString_(mParentIds) + "}"; } } final static List<String> BAR_SPACE = Collections.unmodifiableList(Arrays.asList("|", " ")); final static List<String> SLASH_SPACE = Collections.unmodifiableList(Arrays.asList("/", " ")); final static List<String> BACKSLASH_SPACE = Collections.unmodifiableList(Arrays.asList("\\", " ")); final static List<String> ONE_SPACE = Collections.unmodifiableList(Arrays.asList(" ")); static List<String> repeat(List<String> value, int count) { List<String> ret = new ArrayList<String>(); while (count > 0) { ret.addAll(value); count--; } return ret; } static void assert_(boolean condition) { if (condition) { return; } throw new RuntimeException("Assertion Failure!"); } // PARANOID: Can get rid of the explicit iteration later if this is too slow. static String list_to_string(List<String> values) { StringBuilder sb = new StringBuilder(); for (String singleChar : values) { assert_(singleChar.length() == 1); sb.append(singleChar); } return sb.toString(); } static String rstrip(String text) { if (text.length() == 0) { return ""; } int pos = text.length() - 1; while (pos >= 0 && text.charAt(pos) == ' ') { pos--; } if (pos == text.length() - 1) { return text; } return text.substring(0, pos + 1); } //////////////////////////////////////////////////////////// // New code written on top of the ported mercurial stuff. //////////////////////////////////////////////////////////// public static class GraphEdge { public final String mFrom; public final String mTo; public GraphEdge(String from, String to) { mFrom = from; mTo = to; } public boolean equals(Object obj) { if (obj == null || (!(obj instanceof GraphEdge))) { return false; } GraphEdge other = (GraphEdge)obj; return mFrom.equals(other.mFrom) && mTo.equals(other.mTo); } // LATER: Do better? Doesn't matter. public int hashCode() { return (mFrom + mTo).hashCode(); } // Hmmm... fast enough? } static class ParentInfo { public final Set<String> mAllParents; public final Set<String> mRootIds; public ParentInfo(Set<String> allParents, Set<String> rootIds) { mAllParents = allParents; mRootIds = rootIds; } } static class OrdinalMapper { private final Map<String, Integer> mLut = new HashMap<String, Integer>(); private int mCount; public OrdinalMapper() {} public int ordinal(String for_value) { if (!mLut.keySet().contains(for_value)) { mLut.put(for_value, mCount); mCount++; } return mLut.get(for_value); } public void dump() { List<String> keys = new ArrayList<String>(mLut.keySet()); Collections.sort(keys); for (String key : keys) { System.err.println(String.format("%s -> %d", key, mLut.get(key))); } } } static void remove_edges(List<GraphEdge> edges, String matchingFrom) { while (true) { top_of_while: for (int index = 0; index < edges.size(); index++) { if (edges.get(index).mFrom.equals(matchingFrom)) { edges.remove(index); continue top_of_while; // for } } break; // while } } static Set<String> allDescendants(Map<String, Set<String>> graph, String leaf_id) { Set<String> seen = new HashSet<String>(); List<String> stack = new ArrayList<String>(); stack.add(leaf_id); while (stack.size() > 0) { String edge_id = stack.remove(stack.size() - 1); if (seen.contains(edge_id)) { continue; } seen.add(edge_id); if (!graph.keySet().contains(edge_id)) { continue; } for (String parent : graph.get(edge_id)) { stack.add(parent); } } return seen; // # Hmmmm... includes leaf_id } static List<Map<String, Set<String>>> find_connected_subgraphs(Map<String, Set<String>> graph, Set<String> root_ids, Set<String> leaf_node_ids) { List<Set<String>> subgraph_id_sets = new ArrayList<Set<String>>(); for (String leaf_id : leaf_node_ids) { subgraph_id_sets.add(allDescendants(graph, leaf_id)); } //# Coalesce subgraphs which have common root nodes for(String key : root_ids) { Set<String> coalesced = new HashSet<String>(); // # Deep copy the list so I can mutate while iterating List<Set<String>> copyForMutatingIteration = new ArrayList<Set<String>>(); copyForMutatingIteration.addAll(subgraph_id_sets); for (Set<String> subgraph_id_set : copyForMutatingIteration) { if (!subgraph_id_set.contains(key)) { continue; } coalesced.addAll(subgraph_id_set); subgraph_id_sets.remove(subgraph_id_set); } if (coalesced.size() > 0) { subgraph_id_sets.add(coalesced); } if (subgraph_id_sets.size() < 2) { break; //# Bail out if there is only one graph } } List<Map<String, Set<String>>> subgraphs = new ArrayList<Map<String, Set<String>>>(); for (Set<String> subgraph_id_set : subgraph_id_sets) { Map<String, Set<String>>copy = new HashMap<String, Set<String>>(); for (String id_value : subgraph_id_set) { if (graph.keySet().contains(id_value)) { // # handle unseen parents Set<String> deepCopy = new HashSet<String>(); deepCopy.addAll(graph.get(id_value)); copy.put(id_value, deepCopy); } } //dumpGraph("subgraph", copy); subgraphs.add(copy); } return subgraphs; } // graph is a map of node identifiers -> set of parent nodes. public static Map<String, Set<String>> buildRawGraph(List<GraphEdge> edges) { Map<String, Set<String>> graph = new HashMap<String, Set<String>>(); for (GraphEdge edge : edges) { Set<String> parents = graph.get(edge.mTo); if (parents == null) { parents = new HashSet<String> (); graph.put(edge.mTo, parents); } parents.add(edge.mFrom); } return graph; } // DCI: fix name public static ParentInfo getParentInfo(Map<String, Set<String>> graph) { Set<String> allParents = new HashSet<String>(); for (Set<String> parents : graph.values()) { allParents.addAll(parents); } Set<String> unseenParents = new HashSet<String>(); unseenParents.addAll(allParents); unseenParents.removeAll(graph.keySet()); Set<String> rootIds = new HashSet<String>(); for(Map.Entry<String, Set<String>> entry : graph.entrySet()) { Set<String> parents = entry.getValue(); if (parents == null || parents.size() == 0) { rootIds.add(entry.getKey()); continue; } assert_(parents.size() > 0); Set<String> unknownParents = new HashSet<String>(); unknownParents.addAll(parents); unknownParents.removeAll(unseenParents); // BUG: ??? Revisit. what if only some parents are unknown? //# All parents are unknown if (unknownParents.size() == 0) { rootIds.add(entry.getKey()); } } return new ParentInfo(allParents, rootIds); } // Graph maps from child -> list of parents (i.e. like a commit DAG). static void set_ordinals_in_plausible_commit_order(Map<String, Set<String>> graph, OrdinalMapper ordinals) { // Make a list of all parent to child edges. // Each edge represents the constraint "the ordinal of this parent is less // than the ordinal of this child". List<GraphEdge> edges = new ArrayList<GraphEdge>(); Set<String> leaf_nodes = new HashSet<String>(); for (Map.Entry<String, Set<String>> entry : graph.entrySet()) { String child = entry.getKey(); Set<String> parents = entry.getValue(); if (parents.size() == 0) { leaf_nodes.add(child); continue; } for (String parent : parents) { edges.add(new GraphEdge(parent, child)); } } while (!edges.isEmpty()) { // Find edges to vertices that no other edges reference. Set<String> candidates = new HashSet<String>(); Set<String> referenced = new HashSet<String>(); for (GraphEdge edge : edges) { candidates.add(edge.mFrom); referenced.add(edge.mTo); } // i.e. "the parents which no remaining children reference." // Implies must have lower ordinals than all unprocessed children. candidates.removeAll(referenced); assert_(candidates.size() > 0); List<String> sorted = new ArrayList<String>(candidates); Collections.sort(sorted); for (String candidate : sorted) { // Set the ordinal. ordinals.ordinal(candidate); // Remove any unreferenced edges from the list. // LATER: fix crappy code. do in one pass outside loop. remove_edges(edges, candidate); } } // Tweak here to order by date? or some other metric? // Set the ordinals for nodes which have no children. List<String> sorted_leaf_nodes = new ArrayList<String>(leaf_nodes); Collections.sort(sorted_leaf_nodes); for (String leaf_node : sorted_leaf_nodes) { ordinals.ordinal(leaf_node); } } // Create a list of graph nodes in the correct order so that // they can be used to draw the graph with the ascii() function. static List<DAGNode> build_dag(Map<String, Set<String>> graph, String null_rev_name) { assert_(!graph.keySet().contains(null_rev_name)); OrdinalMapper ordinals = new OrdinalMapper(); int null_rev_ordinal = ordinals.ordinal(null_rev_name); //# Important: This sets the graph ordinals correctly. set_ordinals_in_plausible_commit_order(graph, ordinals); List<DAGNode> dag = new ArrayList<DAGNode>(); for(Map.Entry<String, Set<String>> entry : graph.entrySet()) { String child = entry.getKey(); List<Integer> parent_ids = new ArrayList<Integer>(); for (String parent : entry.getValue()) { parent_ids.add(ordinals.ordinal(parent)); } if (parent_ids.size() == 1 && parent_ids.get(0) == null_rev_ordinal) { // Causes ascii() not to draw a line down from the 'o'. parent_ids = new ArrayList<Integer>(); } dag.add(new DAGNode(child, ordinals.ordinal(child), parent_ids)); } //ordinals.dump(); // IMPORTANT: Sort in order of descending ordinal otherwise drawing code won't work. Collections.sort(dag); return dag; } // BUG: detect cylces? // REQUIRES: edges form an acyclic directed graph. public static List<List<DAGNode>> build_dags(List<GraphEdge> edges, String null_rev_name) { //""" Creates a list of DAG lists that can be printed with the ascii() // method, from an unordered list of edges. """ Map<String, Set<String>> graph = buildRawGraph(edges); ParentInfo parentInfo = getParentInfo(graph); Set<String> all_parents = parentInfo.mAllParents; Set<String> root_ids = parentInfo.mRootIds; Set<String> leaf_node_ids = new HashSet<String>(); leaf_node_ids.addAll(graph.keySet()); leaf_node_ids.removeAll(all_parents); List<Map<String, Set<String>>> subgraphs = find_connected_subgraphs(graph, root_ids, leaf_node_ids); List<List<DAGNode>> dags = new ArrayList<List<DAGNode>>(); for (Map<String, Set<String>> subgraph : subgraphs) { dags.add(build_dag(subgraph, null_rev_name)); } return dags; } private final static String prettyString(Set<String> set) { List<String> list = new ArrayList<String>(); list.addAll(set); Collections.sort(list); return prettyString(list); } private final static String prettyString(List<String> list) { String ret = "{"; for (String value : list) { ret += value + ", "; } ret = ret.trim() + "}"; return ret; } // GRRRR... Colliding type erasure. Java is a poor man's C++ :-( static String prettyString_(List<Integer> values) { List<String> list = new ArrayList<String>(); for (Integer value : values) { list.add(value.toString()); } return prettyString(list); } private final static void dumpGraph(String msg, Map<String, Set<String>> graph) { System.err.println("--- graph: " + msg); List<String> keys = new ArrayList<String>(); keys.addAll(graph.keySet()); Collections.sort(keys); for (String key : keys) { System.err.println(String.format(" [%s] -> [%s]", key, prettyString(graph.get(key)))); } } // File format: // <child_rev> <parent_rev> // one entry per line, lines starting with # and // are ignored. private final static List<GraphEdge> readEdgesFromFile(String fileName) throws IOException { List<GraphEdge> list = new ArrayList<GraphEdge>(); LineNumberReader reader = new LineNumberReader(new FileReader(fileName)); String line = reader.readLine(); while(line != null) { if (line.trim().equals("") || line.startsWith("#") || line.startsWith("//")) { line = reader.readLine(); continue; } String[] fields = line.trim().split(" "); list.add(new GraphEdge(fields[1], fields[0])); line = reader.readLine(); } return list; } public static void test_dumping_graph(List<DAGNode> dag) throws IOException { List<Integer> seen = new ArrayList<Integer>(); AsciiState state = asciistate(); Writer out = new OutputStreamWriter(System.out); for (DAGNode value : dag) { List<String> lines = new ArrayList<String>(); lines.add(String.format("id: %s (%d)", value.mTag, value.mId)); ascii(out, state, "o", lines, asciiedges(seen, value.mId, value.mParentIds)); } out.flush(); } public final static void main(String[] args) throws Exception { System.out.println(String.format("Reading edges from: %s", args[0])); List<GraphEdge> edges = readEdgesFromFile(args[0]); List<List<DAGNode>> dags = build_dags(edges, "null_rev"); for (List<DAGNode> dag : dags) { System.out.println("--- dag ---"); test_dumping_graph(dag); } } }
gpl-2.0
christianchristensen/resin
modules/resin/src/com/caucho/resources/ScheduledTask.java
7992
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.resources; import java.util.Date; import java.util.TimerTask; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.el.ELContext; import javax.el.MethodExpression; import javax.inject.Inject; import javax.enterprise.inject.Instance; import javax.resource.spi.work.Work; import javax.servlet.RequestDispatcher; import com.caucho.config.ConfigException; import com.caucho.config.Configurable; import com.caucho.config.Service; import com.caucho.config.Unbound; import com.caucho.config.inject.InjectManager; import com.caucho.config.types.CronType; import com.caucho.config.types.Period; import com.caucho.config.types.Trigger; import com.caucho.loader.Environment; import com.caucho.loader.EnvironmentClassLoader; import com.caucho.loader.EnvironmentListener; import com.caucho.server.http.StubServletRequest; import com.caucho.server.http.StubServletResponse; import com.caucho.server.util.ScheduledThreadPool; import com.caucho.server.webapp.WebApp; import com.caucho.util.Alarm; import com.caucho.util.AlarmListener; import com.caucho.util.L10N; /** * The cron resources starts application Work tasks at cron-specified * intervals. */ @Service @Unbound @Configurable public class ScheduledTask implements AlarmListener, EnvironmentListener { private static final L10N L = new L10N(ScheduledTask.class); private static final Logger log = Logger.getLogger(ScheduledTask.class.getName()); private Executor _threadPool; private ClassLoader _loader; private Trigger _trigger; private TimerTrigger _timerTrigger = new TimerTrigger(); private Runnable _task; private MethodExpression _method; private String _url; @SuppressWarnings("unused") private @Inject Instance<WebApp> _webAppInstance; private WebApp _webApp; private Alarm _alarm; private volatile boolean _isActive; /** * Constructor. */ public ScheduledTask() { _loader = Thread.currentThread().getContextClassLoader(); _threadPool = ScheduledThreadPool.getLocal(); } /** * Sets the delay */ @Configurable public void setDelay(Period delay) { _trigger = _timerTrigger; _timerTrigger.setFirstTime(Alarm.getExactTime() + delay.getPeriod()); } /** * Sets the period */ @Configurable public void setPeriod(Period period) { _trigger = _timerTrigger; _timerTrigger.setPeriod(period.getPeriod()); } /** * Sets the cron interval. */ @Configurable public void setCron(String cron) { _trigger = new CronType(cron); } /** * Sets the method expression as a task */ @Configurable public void setMethod(MethodExpression method) { _method = method; } /** * Sets the url expression as a task */ @Configurable public void setUrl(String url) { if (! url.startsWith("/")) throw new ConfigException(L.l("url '{0}' must be absolute", url)); _url = url; _webApp = WebApp.getCurrent(); /* throw new ConfigException(L.l("relative url '{0}' requires web-app context", url)); */ } /** * Sets the task. */ @Configurable public void setTask(Runnable task) { _task = task; } public Runnable getTask() { return _task; } /** * Initialization. */ @PostConstruct public void init() throws ConfigException { if (_task != null) { } else if (_method != null) { _task = new MethodTask(_method); } else if (_url != null) { _task = new ServletTask(_url, _webApp); } if (_task == null) throw new ConfigException(L.l("{0} requires a <task>, <method>, or <url> because the ScheduledTask needs a task to run.", this)); if (_trigger == null) { _timerTrigger.setFirstTime(Long.MAX_VALUE / 2); _trigger = _timerTrigger; } Environment.addEnvironmentListener(this); } private void start() { long now = Alarm.getCurrentTime(); long nextTime = _trigger.nextTime(now + 500); _isActive = true; assert(_task != null); _alarm = new Alarm("cron-resource", this, nextTime - now); if (log.isLoggable(Level.FINER)) log.finer(this + " started. Next event at " + new Date(nextTime)); } private void stop() { _isActive = false; Alarm alarm = _alarm; _alarm = null; if (alarm != null) alarm.dequeue(); if (_task instanceof Work) ((Work) _task).release(); else if (_task instanceof TimerTask) ((TimerTask) _task).cancel(); } /** * The runnable. */ public void handleAlarm(Alarm alarm) { if (! _isActive) return; Thread thread = Thread.currentThread(); ClassLoader oldLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(_loader); log.fine(this + " executing " + _task); _threadPool.execute(_task); // XXX: needs QA long now = Alarm.getExactTime(); long nextTime = _trigger.nextTime(now + 500); if (_isActive) alarm.queue(nextTime - now); } catch (Exception e) { log.log(Level.WARNING, e.toString(), e); } finally { thread.setContextClassLoader(oldLoader); } } public void environmentConfigure(EnvironmentClassLoader loader) throws ConfigException { } public void environmentBind(EnvironmentClassLoader loader) throws ConfigException { } public void environmentStart(EnvironmentClassLoader loader) { start(); } public void environmentStop(EnvironmentClassLoader loader) { stop(); } public String toString() { return getClass().getSimpleName() + "[" + _task + "," + _trigger + "]"; } public static class MethodTask implements Runnable { private static final Object[] _args = new Object[0]; private ELContext _elContext; private MethodExpression _method; MethodTask(MethodExpression method) { _method = method; _elContext = InjectManager.create().getELContext(); } public void run() { _method.invoke(_elContext, _args); } public String toString() { return getClass().getSimpleName() + "[" + _method + "]"; } } public class ServletTask implements Runnable { private String _url; private WebApp _webApp; ServletTask(String url, WebApp webApp) { _url = url; _webApp = webApp; } public void run() { StubServletRequest req = new StubServletRequest(); StubServletResponse res = new StubServletResponse(); try { RequestDispatcher dispatcher = _webApp.getRequestDispatcher(_url); dispatcher.forward(req, res); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } public String toString() { return getClass().getSimpleName() + "[" + _url + "," + _webApp + "]"; } } }
gpl-2.0
nhrdl/java_gnome
java-gnome-4.1.3-Webkitgtk2/src/bindings/org/gnome/webKit/DOMDocumentType.java
767
package org.gnome.webKit; public class DOMDocumentType extends DOMNode { protected DOMDocumentType(long pointer) { super(pointer); } public DOMNamedNodeMap getNotations() { return WebKitDOMDocumentType.getNotations(this); } public DOMNamedNodeMap getEntities() { return WebKitDOMDocumentType.getEntities(this); } public String getInternalSubset() { return WebKitDOMDocumentType.getInternalSubset(this); } public String getPublicId() { return WebKitDOMDocumentType.getPublicId(this); } public String getSystemId() { return WebKitDOMDocumentType.getSystemId(this); } public String getName() { return WebKitDOMDocumentType.getName(this); } }
gpl-2.0
chrisboyle/searchongreen
name/boyle/chris/searchongreen/SearchOnGreen.java
1384
/* Search on green - trivial hack to connect long-press of the green button to the new Voice Search in Android 1.6. Copyright (C) 2009 Chris Boyle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package name.boyle.chris.searchongreen; import android.app.Activity; import android.content.Intent; import android.widget.Toast; public class SearchOnGreen extends Activity { public void onStart() { try { startActivity(new Intent().setClassName("com.google.android.voicesearch","com.google.android.voicesearch.RecognitionActivity")); } catch (Exception e) { Toast.makeText(this, "Could not launch Voice Search, perhaps you don't have it?\n\n("+e.getClass().getName()+")", Toast.LENGTH_LONG).show(); } super.onStart(); finish(); } }
gpl-2.0
openthinclient/openthinclient-manager
sysreport/src/main/java/org/openthinclient/sysreport/SystemReport.java
3305
package org.openthinclient.sysreport; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; public class SystemReport extends AbstractReport { protected final Network network; private final Submitter submitter; @JsonProperty("package-management") private final PackageManagerSubsystem packageManager; public SystemReport() { super(); submitter = new Submitter(); packageManager = new PackageManagerSubsystem(); network = new Network(); } public PackageManagerSubsystem getPackageManager() { return packageManager; } public Submitter getSubmitter() { return submitter; } public Network getNetwork() { return network; } public enum SubmitterType { PERSON, AUTOMATED } public static final class Submitter { @JsonProperty("type") private SubmitterType submitterType; private String name; private String email; public SubmitterType getSubmitterType() { return submitterType; } public void setSubmitterType(SubmitterType submitterType) { this.submitterType = submitterType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } public static final class NetworkInterfaceDetails extends NetworkInterface { private final List<String> addresses; @JsonProperty("hardware-address") private String hardwareAddress; public NetworkInterfaceDetails() { addresses = new ArrayList<>(); } public String getHardwareAddress() { return hardwareAddress; } public void setHardwareAddress(String hardwareAddress) { this.hardwareAddress = hardwareAddress; } public List<String> getAddresses() { return addresses; } } public static final class Network { private final List<NetworkInterfaceDetails> interfaces; private final Proxy proxy; public Network() { proxy = new Proxy(); interfaces = new ArrayList<>(); } public List<NetworkInterfaceDetails> getInterfaces() { return interfaces; } public Proxy getProxy() { return proxy; } public static final class Proxy { private int port; private String user; private boolean passwordSpecified; private String host; private boolean enabled; public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public boolean isPasswordSpecified() { return passwordSpecified; } public void setPasswordSpecified(boolean passwordSpecified) { this.passwordSpecified = passwordSpecified; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } } }
gpl-2.0
vishwaAbhinav/OpenNMS
opennms-config/target/generated-sources/castor/org/opennms/netmgt/config/rancid/adapter/descriptors/RancidConfigurationDescriptor.java
16567
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML * Schema. * $Id$ */ package org.opennms.netmgt.config.rancid.adapter.descriptors; //---------------------------------/ //- Imported classes and packages -/ //---------------------------------/ import org.opennms.netmgt.config.rancid.adapter.RancidConfiguration; /** * Class RancidConfigurationDescriptor. * * @version $Revision$ $Date$ */ @SuppressWarnings("all") public class RancidConfigurationDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl { //--------------------------/ //- Class/Member Variables -/ //--------------------------/ /** * Field _elementDefinition. */ private boolean _elementDefinition; /** * Field _nsPrefix. */ private java.lang.String _nsPrefix; /** * Field _nsURI. */ private java.lang.String _nsURI; /** * Field _xmlName. */ private java.lang.String _xmlName; /** * Field _identity. */ private org.exolab.castor.xml.XMLFieldDescriptor _identity; //----------------/ //- Constructors -/ //----------------/ public RancidConfigurationDescriptor() { super(); _nsURI = "http://xmlns.opennms.org/xsd/config/rancid/adapter"; _xmlName = "rancid-configuration"; _elementDefinition = true; //-- set grouping compositor setCompositorAsSequence(); org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null; org.exolab.castor.mapping.FieldHandler handler = null; org.exolab.castor.xml.FieldValidator fieldValidator = null; //-- initialize attribute descriptors //-- _delay desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.Long.TYPE, "_delay", "delay", org.exolab.castor.xml.NodeType.Attribute); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { RancidConfiguration target = (RancidConfiguration) object; if (!target.hasDelay()) { return null; } return new java.lang.Long(target.getDelay()); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; // ignore null values for non optional primitives if (value == null) { return; } target.setDelay( ((java.lang.Long) value).longValue()); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("long"); desc.setHandler(handler); desc.setRequired(true); desc.setMultivalued(false); addFieldDescriptor(desc); //-- validation code for: _delay fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(1); { //-- local scope org.exolab.castor.xml.validators.LongValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.LongValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setMinInclusive(-9223372036854775808L); typeValidator.setMaxInclusive(9223372036854775807L); } desc.setValidator(fieldValidator); //-- _retries desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.Integer.TYPE, "_retries", "retries", org.exolab.castor.xml.NodeType.Attribute); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { RancidConfiguration target = (RancidConfiguration) object; if (!target.hasRetries()) { return null; } return new java.lang.Integer(target.getRetries()); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; // ignore null values for non optional primitives if (value == null) { return; } target.setRetries( ((java.lang.Integer) value).intValue()); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("int"); desc.setHandler(handler); desc.setRequired(true); desc.setMultivalued(false); addFieldDescriptor(desc); //-- validation code for: _retries fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(1); { //-- local scope org.exolab.castor.xml.validators.IntValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.IntValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setMinInclusive(-2147483648); typeValidator.setMaxInclusive(2147483647); } desc.setValidator(fieldValidator); //-- _useCategories desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.Boolean.TYPE, "_useCategories", "useCategories", org.exolab.castor.xml.NodeType.Attribute); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { RancidConfiguration target = (RancidConfiguration) object; if (!target.hasUseCategories()) { return null; } return (target.getUseCategories() ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; // if null, use delete method for optional primitives if (value == null) { target.deleteUseCategories(); return; } target.setUseCategories( ((java.lang.Boolean) value).booleanValue()); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("boolean"); desc.setHandler(handler); desc.setMultivalued(false); addFieldDescriptor(desc); //-- validation code for: _useCategories fieldValidator = new org.exolab.castor.xml.FieldValidator(); { //-- local scope org.exolab.castor.xml.validators.BooleanValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.BooleanValidator(); fieldValidator.setValidator(typeValidator); } desc.setValidator(fieldValidator); //-- _defaultType desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_defaultType", "default-type", org.exolab.castor.xml.NodeType.Attribute); desc.setImmutable(true); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { RancidConfiguration target = (RancidConfiguration) object; return target.getDefaultType(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; target.setDefaultType( (java.lang.String) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("string"); desc.setHandler(handler); desc.setMultivalued(false); addFieldDescriptor(desc); //-- validation code for: _defaultType fieldValidator = new org.exolab.castor.xml.FieldValidator(); { //-- local scope org.exolab.castor.xml.validators.StringValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.StringValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setWhiteSpace("preserve"); } desc.setValidator(fieldValidator); //-- initialize element descriptors //-- _policies desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.rancid.adapter.Policies.class, "_policies", "policies", org.exolab.castor.xml.NodeType.Element); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { RancidConfiguration target = (RancidConfiguration) object; return target.getPolicies(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; target.setPolicies( (org.opennms.netmgt.config.rancid.adapter.Policies) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return new org.opennms.netmgt.config.rancid.adapter.Policies(); } }; desc.setSchemaType("org.opennms.netmgt.config.rancid.adapter.Policies"); desc.setHandler(handler); desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/rancid/adapter"); desc.setMultivalued(false); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _policies fieldValidator = new org.exolab.castor.xml.FieldValidator(); { //-- local scope } desc.setValidator(fieldValidator); //-- _mappingList desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.rancid.adapter.Mapping.class, "_mappingList", "mapping", org.exolab.castor.xml.NodeType.Element); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { RancidConfiguration target = (RancidConfiguration) object; return target.getMapping(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; target.addMapping( (org.opennms.netmgt.config.rancid.adapter.Mapping) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException { try { RancidConfiguration target = (RancidConfiguration) object; target.removeAllMapping(); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return new org.opennms.netmgt.config.rancid.adapter.Mapping(); } }; desc.setSchemaType("org.opennms.netmgt.config.rancid.adapter.Mapping"); desc.setHandler(handler); desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/rancid/adapter"); desc.setMultivalued(true); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _mappingList fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(0); { //-- local scope } desc.setValidator(fieldValidator); } //-----------/ //- Methods -/ //-----------/ /** * Method getAccessMode. * * @return the access mode specified for this class. */ @Override() public org.exolab.castor.mapping.AccessMode getAccessMode( ) { return null; } /** * Method getIdentity. * * @return the identity field, null if this class has no * identity. */ @Override() public org.exolab.castor.mapping.FieldDescriptor getIdentity( ) { return _identity; } /** * Method getJavaClass. * * @return the Java class represented by this descriptor. */ @Override() public java.lang.Class<?> getJavaClass( ) { return org.opennms.netmgt.config.rancid.adapter.RancidConfiguration.class; } /** * Method getNameSpacePrefix. * * @return the namespace prefix to use when marshaling as XML. */ @Override() public java.lang.String getNameSpacePrefix( ) { return _nsPrefix; } /** * Method getNameSpaceURI. * * @return the namespace URI used when marshaling and * unmarshaling as XML. */ @Override() public java.lang.String getNameSpaceURI( ) { return _nsURI; } /** * Method getValidator. * * @return a specific validator for the class described by this * ClassDescriptor. */ @Override() public org.exolab.castor.xml.TypeValidator getValidator( ) { return this; } /** * Method getXMLName. * * @return the XML Name for the Class being described. */ @Override() public java.lang.String getXMLName( ) { return _xmlName; } /** * Method isElementDefinition. * * @return true if XML schema definition of this Class is that * of a global * element or element with anonymous type definition. */ public boolean isElementDefinition( ) { return _elementDefinition; } }
gpl-2.0
Buggaboo/xplatform
mobgen/src-gen/nl/sison/dsl/mobgen/impl/JsonArrayImpl.java
3634
/** */ package nl.sison.dsl.mobgen.impl; import java.util.Collection; import nl.sison.dsl.mobgen.JsonArray; import nl.sison.dsl.mobgen.JsonObjectValue; import nl.sison.dsl.mobgen.MobgenPackage; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Json Array</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link nl.sison.dsl.mobgen.impl.JsonArrayImpl#getItems <em>Items</em>}</li> * </ul> * </p> * * @generated */ public class JsonArrayImpl extends MinimalEObjectImpl.Container implements JsonArray { /** * The cached value of the '{@link #getItems() <em>Items</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getItems() * @generated * @ordered */ protected EList<JsonObjectValue> items; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected JsonArrayImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MobgenPackage.Literals.JSON_ARRAY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<JsonObjectValue> getItems() { if (items == null) { items = new EObjectContainmentEList<JsonObjectValue>(JsonObjectValue.class, this, MobgenPackage.JSON_ARRAY__ITEMS); } return items; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MobgenPackage.JSON_ARRAY__ITEMS: return ((InternalEList<?>)getItems()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MobgenPackage.JSON_ARRAY__ITEMS: return getItems(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MobgenPackage.JSON_ARRAY__ITEMS: getItems().clear(); getItems().addAll((Collection<? extends JsonObjectValue>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MobgenPackage.JSON_ARRAY__ITEMS: getItems().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MobgenPackage.JSON_ARRAY__ITEMS: return items != null && !items.isEmpty(); } return super.eIsSet(featureID); } } //JsonArrayImpl
gpl-2.0
jmogarrio/tetrad
tetrad-lib/src/main/java/edu/cmu/tetrad/sem/Ricf.java
25169
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.sem; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix1D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import cern.colt.matrix.linalg.Algebra; import cern.jet.math.Mult; import cern.jet.math.PlusMult; import edu.cmu.tetrad.data.ICovarianceMatrix; import edu.cmu.tetrad.graph.Endpoint; import edu.cmu.tetrad.graph.Graph; import edu.cmu.tetrad.graph.Node; import edu.cmu.tetrad.graph.SemGraph; import edu.cmu.tetrad.util.MatrixUtils; import java.text.DecimalFormat; import java.util.*; /** * Implements ICF as specified in Drton and Richardson (2003), Iterative Conditional Fitting for Gaussian Ancestral * Graph Models, using hints from previous implementations by Drton in the ggm package in R and by Silva in the Purify * class. The reason for reimplementing in this case is to take advantage of linear algebra optimizations in the COLT * library. * * @author Joseph Ramsey */ public class Ricf { private ICovarianceMatrix covMatrix; //==============================CONSTRUCTORS==========================// public Ricf() { } //=============================PUBLIC METHODS=========================// public RicfResult ricf(SemGraph mag, ICovarianceMatrix covMatrix, double tolerance) { this.covMatrix = covMatrix; mag.setShowErrorTerms(false); DoubleFactory2D factory = DoubleFactory2D.dense; Algebra algebra = new Algebra(); DoubleMatrix2D S = new DenseDoubleMatrix2D(covMatrix.getMatrix().toArray()); int p = covMatrix.getDimension(); if (p == 1) { return new RicfResult(S, S, null, null, 1, Double.NaN, covMatrix); } List<Node> nodes = new ArrayList<Node>(); for (String name : covMatrix.getVariableNames()) { nodes.add(mag.getNode(name)); } DoubleMatrix2D omega = factory.diagonal(factory.diagonal(S)); DoubleMatrix2D B = factory.identity(p); int[] ug = ugNodes(mag, nodes); int[] ugComp = complement(p, ug); if (ug.length > 0) { List<Node> _ugNodes = new LinkedList<Node>(); for (int i : ug) { _ugNodes.add(nodes.get(i)); } Graph ugGraph = mag.subgraph(_ugNodes); ICovarianceMatrix ugCov = covMatrix.getSubmatrix(ug); DoubleMatrix2D lambdaInv = fitConGraph(ugGraph, ugCov, p + 1, tolerance).shat; omega.viewSelection(ug, ug).assign(lambdaInv); } // Prepare lists of parents and spouses. int[][] pars = parentIndices(p, mag, nodes); int[][] spo = spouseIndices(p, mag, nodes); int i = 0; double _diff; while (true) { i++; DoubleMatrix2D omegaOld = omega.copy(); DoubleMatrix2D bOld = B.copy(); for (int _v = 0; _v < p; _v++) { // Need to exclude the UG part. // Exclude the UG part. if (Arrays.binarySearch(ug, _v) >= 0) { continue; } int[] v = new int[]{_v}; int[] vcomp = complement(p, v); int[] all = range(0, p - 1); int[] parv = pars[_v]; int[] spov = spo[_v]; DoubleMatrix2D a6 = B.viewSelection(v, parv); if (spov.length == 0) { if (parv.length != 0) { if (i == 1) { DoubleMatrix2D a1 = S.viewSelection(parv, parv); DoubleMatrix2D a2 = S.viewSelection(v, parv); DoubleMatrix2D a3 = algebra.inverse(a1); DoubleMatrix2D a4 = algebra.mult(a2, a3); a4.assign(Mult.mult(-1)); a6.assign(a4); DoubleMatrix2D a7 = S.viewSelection(parv, v); DoubleMatrix2D a9 = algebra.mult(a6, a7); DoubleMatrix2D a8 = S.viewSelection(v, v); DoubleMatrix2D a8b = omega.viewSelection(v, v); a8b.assign(a8); omega.viewSelection(v, v).assign(a9, PlusMult.plusMult(1)); } } } else { if (parv.length != 0) { DoubleMatrix2D oInv = new DenseDoubleMatrix2D(p, p); DoubleMatrix2D a2 = omega.viewSelection(vcomp, vcomp); DoubleMatrix2D a3 = algebra.inverse(a2); oInv.viewSelection(vcomp, vcomp).assign(a3); DoubleMatrix2D Z = algebra.mult(oInv.viewSelection(spov, vcomp), B.viewSelection(vcomp, all)); int lpa = parv.length; int lspo = spov.length; // Build XX DoubleMatrix2D XX = new DenseDoubleMatrix2D(lpa + lspo, lpa + lspo); int[] range1 = range(0, lpa - 1); int[] range2 = range(lpa, lpa + lspo - 1); // Upper left quadrant XX.viewSelection(range1, range1).assign(S.viewSelection(parv, parv)); // Upper right quadrant DoubleMatrix2D a11 = algebra.mult(S.viewSelection(parv, all), algebra.transpose(Z)); XX.viewSelection(range1, range2).assign(a11); // Lower left quadrant DoubleMatrix2D a12 = XX.viewSelection(range2, range1); DoubleMatrix2D a13 = algebra.transpose(XX.viewSelection(range1, range2)); a12.assign(a13); // Lower right quadrant DoubleMatrix2D a14 = XX.viewSelection(range2, range2); DoubleMatrix2D a15 = algebra.mult(Z, S); DoubleMatrix2D a16 = algebra.mult(a15, algebra.transpose(Z)); a14.assign(a16); // Build XY DoubleMatrix1D YX = new DenseDoubleMatrix1D(lpa + lspo); DoubleMatrix1D a17 = YX.viewSelection(range1); DoubleMatrix1D a18 = S.viewSelection(v, parv).viewRow(0); a17.assign(a18); DoubleMatrix1D a19 = YX.viewSelection(range2); DoubleMatrix2D a20 = S.viewSelection(v, all); DoubleMatrix1D a21 = algebra.mult(a20, algebra.transpose(Z)).viewRow(0); a19.assign(a21); // Temp DoubleMatrix2D a22 = algebra.inverse(XX); DoubleMatrix1D temp = algebra.mult(algebra.transpose(a22), YX); // Assign to b. DoubleMatrix1D a23 = a6.viewRow(0); DoubleMatrix1D a24 = temp.viewSelection(range1); a23.assign(a24); a23.assign(Mult.mult(-1)); // Assign to omega. omega.viewSelection(v, spov).viewRow(0).assign(temp.viewSelection(range2)); omega.viewSelection(spov, v).viewColumn(0).assign(temp.viewSelection(range2)); // Variance. double tempVar = S.get(_v, _v) - algebra.mult(temp, YX); DoubleMatrix2D a27 = omega.viewSelection(v, spov); DoubleMatrix2D a28 = oInv.viewSelection(spov, spov); DoubleMatrix2D a29 = omega.viewSelection(spov, v).copy(); DoubleMatrix2D a30 = algebra.mult(a27, a28); DoubleMatrix2D a31 = algebra.mult(a30, a29); omega.viewSelection(v, v).assign(tempVar); omega.viewSelection(v, v).assign(a31, PlusMult.plusMult(1)); } else { DoubleMatrix2D oInv = new DenseDoubleMatrix2D(p, p); DoubleMatrix2D a2 = omega.viewSelection(vcomp, vcomp); DoubleMatrix2D a3 = algebra.inverse(a2); oInv.viewSelection(vcomp, vcomp).assign(a3); // System.out.println("O.inv = " + oInv); DoubleMatrix2D a4 = oInv.viewSelection(spov, vcomp); DoubleMatrix2D a5 = B.viewSelection(vcomp, all); DoubleMatrix2D Z = algebra.mult(a4, a5); // System.out.println("Z = " + Z); // Build XX DoubleMatrix2D XX = algebra.mult(algebra.mult(Z, S), Z.viewDice()); // System.out.println("XX = " + XX); // Build XY DoubleMatrix2D a20 = S.viewSelection(v, all); DoubleMatrix1D YX = algebra.mult(a20, Z.viewDice()).viewRow(0); // System.out.println("YX = " + YX); // Temp DoubleMatrix2D a22 = algebra.inverse(XX); DoubleMatrix1D a23 = algebra.mult(algebra.transpose(a22), YX); // Assign to omega. DoubleMatrix1D a24 = omega.viewSelection(v, spov).viewRow(0); a24.assign(a23); DoubleMatrix1D a25 = omega.viewSelection(spov, v).viewColumn(0); a25.assign(a23); // System.out.println("Omega 2 " + omega); // Variance. double tempVar = S.get(_v, _v) - algebra.mult(a24, YX); // System.out.println("tempVar = " + tempVar); DoubleMatrix2D a27 = omega.viewSelection(v, spov); DoubleMatrix2D a28 = oInv.viewSelection(spov, spov); DoubleMatrix2D a29 = omega.viewSelection(spov, v).copy(); DoubleMatrix2D a30 = algebra.mult(a27, a28); DoubleMatrix2D a31 = algebra.mult(a30, a29); omega.set(_v, _v, tempVar + a31.get(0, 0)); // System.out.println("Omega final " + omega); } } } DoubleMatrix2D a32 = omega.copy(); a32.assign(omegaOld, PlusMult.plusMult(-1)); double diff1 = algebra.norm1(a32); DoubleMatrix2D a33 = B.copy(); a33.assign(bOld, PlusMult.plusMult(-1)); double diff2 = algebra.norm1(a32); double diff = diff1 + diff2; _diff = diff; if (diff < tolerance) break; } DoubleMatrix2D a34 = algebra.inverse(B); DoubleMatrix2D a35 = algebra.inverse(B.viewDice()); DoubleMatrix2D sigmahat = algebra.mult(algebra.mult(a34, omega), a35); DoubleMatrix2D lambdahat = omega.copy(); DoubleMatrix2D a36 = lambdahat.viewSelection(ugComp, ugComp); a36.assign(factory.make(ugComp.length, ugComp.length, 0.0)); DoubleMatrix2D omegahat = omega.copy(); DoubleMatrix2D a37 = omegahat.viewSelection(ug, ug); a37.assign(factory.make(ug.length, ug.length, 0.0)); DoubleMatrix2D bhat = B.copy(); return new RicfResult(sigmahat, lambdahat, bhat, omegahat, i, _diff, covMatrix); } /** * @return an enumeration of the cliques of the given graph considered as undirected. */ public List<List<Node>> cliques(Graph graph) { List<Node> nodes = graph.getNodes(); List<List<Node>> cliques = new ArrayList<List<Node>>(); for (int i = 0; i < nodes.size(); i++) { List<Node> adj = graph.getAdjacentNodes(nodes.get(i)); SortedSet<Integer> L1 = new TreeSet<Integer>(); L1.add(i); SortedSet<Integer> L2 = new TreeSet<Integer>(); for (Node _adj : adj) { L2.add(nodes.indexOf(_adj)); } int moved = -1; while (true) { addNodesToRight(L1, L2, graph, nodes, moved); if (isMaximal(L1, L2, graph, nodes)) { record(L1, cliques, nodes); } moved = moveLastBack(L1, L2); if (moved == -1) { break; } } } return cliques; } /** * Fits a concentration graph. Coding algorithm #2 only. */ public FitConGraphResult fitConGraph(Graph graph, ICovarianceMatrix cov, int n, double tol) { DoubleFactory2D factory = DoubleFactory2D.dense; Algebra algebra = new Algebra(); List<Node> nodes = graph.getNodes(); String[] nodeNames = new String[nodes.size()]; for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); if (!cov.getVariableNames().contains(node.getName())) { throw new IllegalArgumentException("Node in graph not in cov matrix: " + node); } nodeNames[i] = node.getName(); } DoubleMatrix2D S = new DenseDoubleMatrix2D(cov.getSubmatrix(nodeNames).getMatrix().toArray()); graph = graph.subgraph(nodes); List<List<Node>> cli = cliques(graph); int nc = cli.size(); if (nc == 1) { return new FitConGraphResult(S, 0, 0, 1); } int k = S.rows(); int it = 0; // Only coding alg #2 here. DoubleMatrix2D K = algebra.inverse(factory.diagonal(factory.diagonal(S))); int[] all = range(0, k - 1); while (true) { DoubleMatrix2D KOld = K.copy(); it++; for (int i = 0; i < nc; i++) { int[] a = asIndices(cli.get(i), nodes); int[] b = complement(all, a); DoubleMatrix2D a1 = S.viewSelection(a, a); DoubleMatrix2D a2 = algebra.inverse(a1); DoubleMatrix2D a3 = K.viewSelection(a, b); DoubleMatrix2D a4 = K.viewSelection(b, b); DoubleMatrix2D a5 = algebra.inverse(a4); DoubleMatrix2D a6 = K.viewSelection(b, a).copy(); DoubleMatrix2D a7 = algebra.mult(a3, a5); DoubleMatrix2D a8 = algebra.mult(a7, a6); a2.assign(a8, PlusMult.plusMult(1)); DoubleMatrix2D a9 = K.viewSelection(a, a); a9.assign(a2); } DoubleMatrix2D a32 = K.copy(); a32.assign(KOld, PlusMult.plusMult(-1)); double diff = algebra.norm1(a32); System.out.println(diff); if (diff < tol) break; } DoubleMatrix2D V = algebra.inverse(K); int numNodes = graph.getNumNodes(); int df = numNodes * (numNodes - 1) / 2 - graph.getNumEdges(); double dev = lik(algebra.inverse(V), S, n, k); return new FitConGraphResult(V, dev, df, it); } private int[] asIndices(List<Node> clique, List<Node> nodes) { int[] a = new int[clique.size()]; for (int j = 0; j < clique.size(); j++) { a[j] = nodes.indexOf(clique.get(j)); } return a; } private double lik(DoubleMatrix2D K, DoubleMatrix2D S, int n, int k) { Algebra algebra = new Algebra(); DoubleMatrix2D SK = algebra.mult(S, K); return (algebra.trace(SK) - Math.log(algebra.det(SK)) - k) * n; } //==============================PRIVATE METHODS=======================// private int[] range(int from, int to) { if (from < 0 || to < 0 || from > to) { throw new IllegalArgumentException(); } int[] range = new int[to - from + 1]; for (int k = from; k <= to; k++) { range[k - from] = k; } return range; } private int[] complement(int p, int[] a) { Arrays.sort(a); int[] vcomp = new int[p - a.length]; int k = -1; for (int j = 0; j < p; j++) { if (Arrays.binarySearch(a, j) >= 0) continue; vcomp[++k] = j; } return vcomp; } private int[] complement(int all[], int[] remove) { Arrays.sort(remove); int[] vcomp = new int[all.length - remove.length]; int k = -1; for (int j = 0; j < all.length; j++) { if (Arrays.binarySearch(remove, j) >= 0) continue; vcomp[++k] = j; } return vcomp; } private int[] ugNodes(Graph mag, List<Node> nodes) { List<Node> ugNodes = new LinkedList<Node>(); for (Node node : nodes) { if (mag.getNodesInTo(node, Endpoint.ARROW).size() == 0) { ugNodes.add(node); } } int[] indices = new int[ugNodes.size()]; for (int j = 0; j < ugNodes.size(); j++) { indices[j] = nodes.indexOf(ugNodes.get(j)); } return indices; } private int[][] parentIndices(int p, Graph mag, List<Node> nodes) { int[][] pars = new int[p][]; for (int i = 0; i < p; i++) { List<Node> parents = mag.getParents(nodes.get(i)); int[] indices = new int[parents.size()]; for (int j = 0; j < parents.size(); j++) { indices[j] = nodes.indexOf(parents.get(j)); } pars[i] = indices; } return pars; } private int[][] spouseIndices(int p, Graph mag, List<Node> nodes) { int[][] spo = new int[p][]; for (int i = 0; i < p; i++) { List<Node> list1 = mag.getNodesOutTo(nodes.get(i), Endpoint.ARROW); List<Node> list2 = mag.getNodesInTo(nodes.get(i), Endpoint.ARROW); list1.retainAll(list2); List<Node> list3 = new LinkedList<Node>(nodes); list3.removeAll(list1); int[] indices = new int[list1.size()]; for (int j = 0; j < list1.size(); j++) { indices[j] = nodes.indexOf(list1.get(j)); } spo[i] = indices; } return spo; } private int moveLastBack(SortedSet<Integer> L1, SortedSet<Integer> L2) { if (L1.size() == 1) { return -1; } int moved = L1.last(); L1.remove(moved); L2.add(moved); return moved; } /** * If L2 is nonempty, moves nodes from L2 to L1 that can be added to L1. Nodes less than max(L1) are not * considered--i.e. L1 is being extended to the right. Nodes not greater than the most recently moved node are not * considered--this is a mechanism for */ private void addNodesToRight(SortedSet<Integer> L1, SortedSet<Integer> L2, Graph graph, List<Node> nodes, int moved) { for (int j : new TreeSet<Integer>(L2)) { if (j > max(L1) && j > moved && addable(j, L1, graph, nodes)) { L1.add(j); L2.remove(j); } } } private void record(SortedSet<Integer> L1, List<List<Node>> cliques, List<Node> nodes) { List<Node> clique = new LinkedList<Node>(); for (int i : L1) { clique.add(nodes.get(i)); } cliques.add(clique); } private boolean isMaximal(SortedSet<Integer> L1, SortedSet<Integer> L2, Graph graph, List<Node> nodes) { for (int j : L2) { if (addable(j, L1, graph, nodes)) { return false; } } return true; } private int max(SortedSet<Integer> L1) { int max = Integer.MIN_VALUE; for (int i : L1) { if (i > max) { max = i; } } return max; } /** * @return true if j is adjacent to all the nodes in l1. */ private boolean addable(int j, SortedSet<Integer> L1, Graph graph, List<Node> nodes) { for (int k : L1) { if (!graph.isAdjacentTo(nodes.get(j), nodes.get(k))) { return false; } } return true; } //==============================PUBLIC CLASSES==========================// public static class RicfResult { private final ICovarianceMatrix covMatrix; private DoubleMatrix2D shat; private DoubleMatrix2D lhat; private DoubleMatrix2D bhat; private DoubleMatrix2D ohat; private int iterations; private double diff; public RicfResult(DoubleMatrix2D shat, DoubleMatrix2D lhat, DoubleMatrix2D bhat, DoubleMatrix2D ohat, int iterations, double diff, ICovarianceMatrix covMatrix) { this.shat = shat; this.lhat = lhat; this.bhat = bhat; this.ohat = ohat; this.iterations = iterations; this.diff = diff; this.covMatrix = covMatrix; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("\nSigma hat\n"); buf.append(MatrixUtils.toStringSquare(getShat().toArray(), new DecimalFormat("0.0000"), covMatrix.getVariableNames())); buf.append("\n\nLambda hat\n"); buf.append(MatrixUtils.toStringSquare(getLhat().toArray(), new DecimalFormat("0.0000"), covMatrix.getVariableNames())); buf.append("\n\nBeta hat\n"); buf.append(MatrixUtils.toStringSquare(getBhat().toArray(), new DecimalFormat("0.0000"), covMatrix.getVariableNames())); buf.append("\n\nOmega hat\n"); buf.append(MatrixUtils.toStringSquare(getOhat().toArray(), new DecimalFormat("0.0000"), covMatrix.getVariableNames())); buf.append("\n\nIterations\n"); buf.append(getIterations()); buf.append("\n\ndiff = " + diff); return buf.toString(); } public DoubleMatrix2D getShat() { return shat; } public DoubleMatrix2D getLhat() { return lhat; } public DoubleMatrix2D getBhat() { return bhat; } public DoubleMatrix2D getOhat() { return ohat; } public int getIterations() { return iterations; } } public static class FitConGraphResult { private DoubleMatrix2D shat; double deviance; int df; int iterations; public FitConGraphResult(DoubleMatrix2D shat, double deviance, int df, int iterations) { this.shat = shat; this.deviance = deviance; this.df = df; this.iterations = iterations; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("\nSigma hat\n"); buf.append(shat); buf.append("\nDeviance\n"); buf.append(deviance); buf.append("\nDf\n"); buf.append(df); buf.append("\nIterations\n"); buf.append(iterations); return buf.toString(); } } }
gpl-2.0
sebastic/GpsPrune
tim/prune/gui/colour/DateColourer.java
3226
package tim.prune.gui.colour; import java.awt.Color; import java.text.DateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.TimeZone; import tim.prune.data.DataPoint; import tim.prune.data.Timestamp; import tim.prune.data.Track; import tim.prune.data.TrackInfo; /** * Point colourer giving a different colour to each date * Uses the system timezone so may give funny results for * data from other timezones (eg far-away holidays) */ public class DateColourer extends DiscretePointColourer { // Doesn't really matter what format is used here, as long as dates are different private static final DateFormat DEFAULT_DATE_FORMAT = DateFormat.getDateInstance(); /** * Constructor * @param inStartColour start colour of scale * @param inEndColour end colour of scale * @param inWrapLength number of unique colours before wrap */ public DateColourer(Color inStartColour, Color inEndColour, int inWrapLength) { super(inStartColour, inEndColour, inWrapLength); } /** * Calculate the colours for each of the points in the given track * @param inTrackInfo track info object */ @Override public void calculateColours(TrackInfo inTrackInfo) { // initialise the array to the right size Track track = inTrackInfo == null ? null : inTrackInfo.getTrack(); final int numPoints = track == null ? 0 : track.getNumPoints(); init(numPoints); // Make a hashmap of the already-used dates HashMap<String, Integer> usedDates = new HashMap<String, Integer>(20); // Also store the previous one, because they're probably consecutive String prevDate = null; int prevIndex = -1; // loop over track points int dayIndex = -1; for (int i=0; i<numPoints; i++) { DataPoint p = track.getPoint(i); if (p != null && !p.isWaypoint()) { dayIndex = 0; // default index 0 will be used if no date found String date = getDate(p.getTimestamp()); if (date != null) { // Check if it's the previous one if (prevDate != null && date.equals(prevDate)) { dayIndex = prevIndex; } else { // Look up in the hashmap to see if it's been used before Integer foundIndex = usedDates.get(date); if (foundIndex == null) { // not been used before, so add it dayIndex = usedDates.size() + 1; usedDates.put(date, dayIndex); } else { // found it dayIndex = foundIndex; } // Remember what we've got for the next point prevDate = date; prevIndex = dayIndex; } } // if date is null (no timestamp or invalid) then dayIndex remains 0 setColour(i, dayIndex); } } // generate the colours needed generateDiscreteColours(usedDates.size() + 1); } /** * Find which date (in the system timezone) the given timestamp falls on * @param inTimestamp timestamp * @return String containing description of date, or null */ private static String getDate(Timestamp inTimestamp) { if (inTimestamp == null || !inTimestamp.isValid()) { return null; } Calendar cal = inTimestamp.getCalendar(); // use system time zone cal.setTimeZone(TimeZone.getDefault()); return DEFAULT_DATE_FORMAT.format(cal.getTime()); } }
gpl-2.0
phrh/ClusterDetection
ClustersDetection/src/RBP_Project.java
8358
/* # CLIP-seq CLuster Detection - Tool to detect clusters of an experimental data set of RBP obtained by CLIP-seq protocol. # # Created by Paula H. Reyes-Herrera PhD. and Msc. Carlos Andres Sierra on August 2014. # Copyright (c) 2014 Paula H. Reyes-Herrera PhD. and Msc. Carlos Andres Sierra. Universidad Antonio Narino. All rights reserved. # # This file is part of CLIP-seq Cluster Detection. # # CLIP-seq Cluster Detection is free software: you can redistribute it and/or modify it under the terms of the # GNU General Public License as published by the Free Software Foundation, version 2. */ import filesProcess.CD_FromSam; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import miscellaneous.Functions; /** * * @author Eng. Paula Reyes, Ph.D. -- M.Sc. Eng. Carlos Sierra * Universidad Antonio Narino */ public class RBP_Project { public static void main(String[] args) { if(args.length > 0) { //Parameters of clusterDetections String dataset = ""; String experiment = ""; int minSequences = 5; int minLenghts = 20; String folder = "results"; String mail = ""; String fastaPath = ""; String snpPath = ""; String noisePath = ""; String[] mutations = null; String[] deletions = null; String[] insertions = null; boolean exportSAM = false; boolean exportBED = false; boolean filterEntropy = true; int window = 8; int amount = 1000; int bg_score = 3; System.gc(); // Call Garbage Collector String setupFile = args[0]; //File to extract reads String line; try { BufferedReader br; br = new BufferedReader(new FileReader(setupFile)); String[] field_value; line = br.readLine(); while(line != null) { field_value = line.split("="); //Read parameters switch(field_value[0]) { case "DataSet": { String[] datasetPath = field_value[1].split("/"); experiment = datasetPath[datasetPath.length - 1]; dataset = field_value[1]; } break; case "Filter_Minimum_Ocurrences": { minSequences = Integer.parseInt(field_value[1]); } break; case "Filter_Minimum_Read_length": { minLenghts = Integer.parseInt(field_value[1]); } break; case "Folder_Results": { folder = field_value[1]; } break; case "E-mail": { mail = field_value[1]; } break; case "FASTA_Folder": { fastaPath = field_value[1]; File fastaPathF = new File(fastaPath); if (!fastaPathF.exists()) { System.out.println("Genome folder not exists."); System.exit(0); } } break; case "SNP_Folder": { snpPath = field_value[1]; File snpPathF = new File(snpPath); if (!snpPathF.exists()) { System.out.println("SNPs folder not exists."); System.exit(0); } } break; case "Noise_Reads": { noisePath = field_value[1]; } break; case "Export_SAM": { exportSAM = field_value[1].toLowerCase().equals("yes") ? true : false; } break; case "Export_BED": { exportBED = field_value[1].toLowerCase().equals("yes") ? true : false; } break; case "Mutations": { mutations = field_value[1].split(","); } break; case "Insertions": { insertions = field_value[1].split(","); } break; case "Deletions": { deletions = field_value[1].split(","); } break; case "Filter_Entrophy": { filterEntropy = field_value[1].toLowerCase().equals("yes") ? true : false; } break; case "Window": { window = Integer.parseInt(field_value[1]); } break; case "Ranking": { amount = Integer.parseInt(field_value[1]); } break; case "Background_Score": { bg_score = Integer.parseInt(field_value[1]); } break; } line = br.readLine(); } br.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(dataset.equals("")) { System.out.println("DataSet parameter is empty or invalid."); System.exit(0); } //Create folder to save the experiments results File folderPath = new File(folder); if (!folderPath.exists()) folderPath.mkdirs(); //Create the general log file String fileLog = folder + "/Log.txt"; //Read and process the file try { CD_FromSam cdSam = new CD_FromSam(); cdSam.readFile(dataset, folder, minLenghts, minSequences, fileLog, fastaPath, snpPath, filterEntropy, exportSAM, exportBED, noisePath, mutations, deletions, insertions, window, amount, setupFile, bg_score); Thread.sleep(500); Functions.sentMail(mail, "The experiment is complete.\n", "DataSet: " + experiment); } catch (InterruptedException e) { Logger.getLogger(RBP_Project.class.getName()).log(Level.SEVERE, null, e); Functions.sentMail(mail, "ERROR: Read and process file fail.\n" + e.getMessage() + "\n", "DataSet: " + experiment); System.exit(0); } catch (FileNotFoundException e) { Logger.getLogger(RBP_Project.class.getName()).log(Level.SEVERE, null, e); Functions.sentMail(mail, "ERROR: File not found.\n" + e.getMessage() + "\n", "DataSet: " + dataset); System.exit(0); } } else { System.out.println("Incorrect parameters..."); } System.gc(); // Call Garbage Collector } }
gpl-2.0
jensnerche/plantuml
src/net/sourceforge/plantuml/ugraphic/hand/UDotPathHand.java
1794
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Adrian Vogt * */ package net.sourceforge.plantuml.ugraphic.hand; import java.awt.geom.CubicCurve2D; import net.sourceforge.plantuml.posimo.DotPath; import net.sourceforge.plantuml.ugraphic.UPath; public class UDotPathHand { private final UPath path; public UDotPathHand(DotPath source) { final HandJiggle jiggle = new HandJiggle(source.getStartPoint(), 2.0); for (CubicCurve2D curve : source.getBeziers()) { jiggle.curveTo(curve); } this.path = jiggle.toUPath(); } public UPath getHanddrawn() { return this.path; } }
gpl-2.0
rmarting/fuse-samples
camel-amq-blueprint/src/main/java/com/redhat/fuse/samples/amq/Hello.java
145
package com.redhat.fuse.samples.amq; /** * An interface for implementing Hello services. */ public interface Hello { String hello(); }
gpl-2.0
andykuo1/mcplus_mods
java/net/minecraftplus/_api/base/_Mod.java
1143
package net.minecraftplus._api.base; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftplus._api.MCP; import net.minecraftplus._api.Munge; import net.minecraftplus._api.dictionary.Exceptions; public abstract class _Mod { static { Munge.Open(); Munge.PreInitialize(); } public _Mod() { Exceptions.InvalidFormat(this.getClass().getSimpleName().charAt(0) == '_'); } public void PreInitialize(FMLPreInitializationEvent parEvent) { Configuration config = new Configuration(parEvent.getSuggestedConfigurationFile()); config.load(); this.Configure(config); if (config.hasChanged()) { config.save(); } } public void Initialize(FMLInitializationEvent parEvent) { Munge.Initialize(MCP.mod()); } public void PostInitialize(FMLPostInitializationEvent parEvent) { Munge.Close(); } public void Configure(Configuration parConfiguration) { } public void Munge() { } }
gpl-2.0
theAgileFactory/maf-desktop-app
app/controllers/api/core/PortfolioEntryPlanningPackageGroupApiController.java
5940
/*! LICENSE * * Copyright (c) 2015, The Agile Factory SA and/or its affiliates. All rights * reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package controllers.api.core; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import controllers.api.ApiAuthenticationBizdockCheck; import controllers.api.ApiController; import dao.pmo.PortfolioEntryPlanningPackageDao; import framework.services.api.ApiError; import framework.services.api.server.ApiAuthentication; import models.pmo.PortfolioEntryPlanningPackageGroup; import models.pmo.PortfolioEntryPlanningPackagePattern; import play.mvc.Result; /** * The API controller for the {@link PortfolioEntryPlanningPackageGroup}. * * @author Oury Diallo */ @Api(value = "/api/core/portfolio-entry-planning-package-group", description = "Operations on Portfolio Entry Planning Package Groups") public class PortfolioEntryPlanningPackageGroupApiController extends ApiController { /** * Get the portfolio entry planning package groups list with filter. * * @param isActive * true to return only active package group, false only * non-active, null all. **/ @ApiAuthentication(additionalCheck = ApiAuthenticationBizdockCheck.class) @ApiOperation(value = "list the Portfolio Entry Planning Package Groups", notes = "Return the list of Portfolio Entry Planning Package Groups in the system", response = PortfolioEntryPlanningPackageGroup.class, httpMethod = "GET") @ApiResponses(value = { @ApiResponse(code = 200, message = "success"), @ApiResponse(code = 400, message = "bad request", response = ApiError.class), @ApiResponse(code = 500, message = "error", response = ApiError.class) }) public Result getPortfolioEntryPlanningPackageGroupsList(@ApiParam(value = "isActive", required = false) @QueryParam("isActive") Boolean isActive) { try { return getJsonSuccessResponse(PortfolioEntryPlanningPackageDao.getPEPlanningPackageGroupAsListByFilter(isActive)); } catch (Exception e) { return getJsonErrorResponse(new ApiError(500, "INTERNAL SERVER ERROR", e)); } } /** * Get a portfolio entry planning package group by id. * * @param id * the portfolio entry planning package group id */ @ApiAuthentication(additionalCheck = ApiAuthenticationBizdockCheck.class) @ApiOperation(value = "Get the specified Portfolio Entry Planning Package Group", notes = "Return the Portfolio Entry Planning Package Group with the specified id", response = PortfolioEntryPlanningPackageGroup.class, httpMethod = "GET") @ApiResponses(value = { @ApiResponse(code = 200, message = "success"), @ApiResponse(code = 400, message = "bad request", response = ApiError.class), @ApiResponse(code = 404, message = "not found", response = ApiError.class), @ApiResponse(code = 500, message = "error", response = ApiError.class) }) public Result getPortfolioEntryPlanningPackageGroupById( @ApiParam(value = "portfolio entry planning package group id", required = true) @PathParam("id") Long id) { try { if (PortfolioEntryPlanningPackageDao.getPEPlanningPackageGroupById(id) == null) { return getJsonErrorResponse(new ApiError(404, "The Portfolio Entry Planning Package Group with the specified id is not found")); } return getJsonSuccessResponse(PortfolioEntryPlanningPackageDao.getPEPlanningPackageGroupById(id)); } catch (Exception e) { return getJsonErrorResponse(new ApiError(500, "INTERNAL SERVER ERROR", e)); } } /** * Get a portfolio entry planning package pattern by id. * * @param id * the portfolio entry planning package id */ @ApiAuthentication(additionalCheck = ApiAuthenticationBizdockCheck.class) @ApiOperation(value = "list the Patterns of the specified Portfolio Entry Planning Package Group", notes = "Return the list of Patterns of the specified Portfolio Entry Planning Package Group in the system", response = PortfolioEntryPlanningPackagePattern.class, httpMethod = "GET") @ApiResponses(value = { @ApiResponse(code = 200, message = "success"), @ApiResponse(code = 500, message = "error", response = ApiError.class) }) public Result getPortfolioEntryPlanningPackagePatternsList( @ApiParam(value = "portfolio entry planning package group id", required = true) @PathParam("id") Long id) { try { if (PortfolioEntryPlanningPackageDao.getPEPlanningPackageGroupById(id) == null) { return getJsonErrorResponse(new ApiError(404, "The Portfolio Entry Planning Package Group with the specified id is not found")); } return getJsonSuccessResponse(PortfolioEntryPlanningPackageDao.getPEPlanningPackagePatternAsListByGroup(id)); } catch (Exception e) { return getJsonErrorResponse(new ApiError(500, "INTERNAL SERVER ERROR", e)); } } }
gpl-2.0
AlexIIL/CivCraft
src/main/java/alexiil/mods/civ/tech/BeakerEarningListener.java
6561
package alexiil.mods.civ.tech; import java.util.List; import net.minecraft.block.Block; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.ItemCraftedEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import net.minecraftforge.fml.common.gameevent.TickEvent.PlayerTickEvent; import alexiil.mods.civ.utils.CraftUtils; public class BeakerEarningListener { public static final BeakerEarningListener instance = new BeakerEarningListener(); @SubscribeEvent public void playerTick(PlayerTickEvent event) { if (event.phase != Phase.END) return; PlayerResearchHelper.decrementCooldown(event.player); // Handle exploration, but only server side if (event.player.worldObj.isRemote) return; boolean exploredNew = CraftUtils.addPlayerToChunk(event.player.worldObj, event.player.getPosition(), event.player); if (exploredNew) PlayerResearchHelper.progressResearch(event.player, "explore", 1, false); } /** @return true if the player is a real player (so not a fake one) */ public static boolean isPlayerFake(EntityPlayer player) { if (player == null) return true; return (player instanceof FakePlayer); } // Beaker earning events @SubscribeEvent public void playerBreakBlock(BreakEvent event) { if (event.world.isRemote) return; EntityPlayer player = event.getPlayer(); if (isPlayerFake(player)) return; int fortune = EnchantmentHelper.getFortuneModifier(player); String name = event.state.getBlock().getUnlocalizedName(); boolean harvest = false; List<ItemStack> stacks = event.state.getBlock().getDrops(event.world, event.pos, event.state, fortune); if (stacks.size() == 1) { ItemStack stack = stacks.get(0); Item item = stack.getItem(); if (item == null) ; else if (item instanceof ItemBlock) { ItemBlock ib = (ItemBlock) item; Block b = ib.block; harvest = b != event.state.getBlock(); } else harvest = true; } else harvest = stacks.size() != 0; if (name.startsWith("tile.")) name = name.substring(5); if (!harvest) PlayerResearchHelper.progressResearch(player, "block.break." + name, 1, true); else PlayerResearchHelper.progressResearch(player, "block.harvest." + name, 1, true); } @SubscribeEvent public void playerCrafted(ItemCraftedEvent event) { if (event.player.worldObj.isRemote) return; if (isPlayerFake(event.player)) return; if (event.crafting == null || event.crafting.getItem() == null) return; String itemName = "craft." + event.crafting.getItem().getUnlocalizedName(event.crafting); PlayerResearchHelper.progressResearch(event.player, itemName, 1, true); } @SubscribeEvent public void entityAttack(LivingHurtEvent event) { if (event.isCanceled()) return; if (event.entity.worldObj.isRemote) return; EntityPlayer player; boolean arrow = false; double distance = 0; if (event.source.getSourceOfDamage() instanceof EntityPlayer) player = (EntityPlayer) event.source.getSourceOfDamage(); else if (event.source.getSourceOfDamage() instanceof EntityArrow) { if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) { player = (EntityPlayer) ((EntityArrow) event.source.getSourceOfDamage()).shootingEntity; arrow = true; distance = event.entity.getDistanceSqToEntity(player); } else return; } else return; if (isPlayerFake(player)) return; if (event.entityLiving == null) return; String entName = "entity.attack." + EntityList.getEntityString(event.entityLiving); PlayerResearchHelper.progressResearch(player, entName, 1, true); if (arrow) PlayerResearchHelper.progressResearch(player, "entity.arrowHit", distance, true); } @SubscribeEvent public void entityDeath(LivingDeathEvent event) { if (event.isCanceled()) return; if (event.entity.worldObj.isRemote) return; if (event.source.getSourceOfDamage() == null) return; EntityPlayer player; Entity ent = event.source.getSourceOfDamage(); boolean arrow = false; double distance = 0; if (ent instanceof EntityPlayer) player = (EntityPlayer) event.source.getSourceOfDamage(); else if (ent instanceof EntityArrow) { if (((EntityArrow) ent).shootingEntity instanceof EntityPlayer) { player = (EntityPlayer) ((EntityArrow) ent).shootingEntity; arrow = true; distance = event.entity.getDistanceSqToEntity(player); } else return; } else return; if (isPlayerFake(player)) return; String name = "entity.kill." + EntityList.getEntityString(event.entity); PlayerResearchHelper.progressResearch(player, name, 1, true); if (arrow) PlayerResearchHelper.progressResearch(player, "entity.arrowHit", distance, true); } // TODO: item related stuffs. So, firing (where an infinity enchantment is less than normal) of bows and // breaking of tools }
gpl-2.0
PicoleDeLimao/MDLParser
src/io/github/picoledelimao/mdl/MDLFilterMode.java
832
package io.github.picoledelimao.mdl; public enum MDLFilterMode { NONE, TRANSPARENT, BLEND, ADDITIVE, ADD_ALPHA, MODULATE; @Override public String toString() { switch (this) { case NONE: return "None"; case TRANSPARENT: return "Transparent"; case BLEND: return "Blend"; case ADDITIVE: return "Additive"; case ADD_ALPHA: return "AddAlpha"; case MODULATE: return "Modulate"; default: return ""; } } public static String[] getStringValues() { String[] values = new String[values().length]; for (int i = 0; i < values().length; i++) { values[i] = values()[i].toString(); } return values; } public static MDLFilterMode getValue(String value) { for (MDLFilterMode type : values()) { if (type.toString().equals(value)) { return type; } } return null; } }
gpl-2.0
VVillwin/resource_controller
server/Receiver/src/test/java/org/presentation4you/resource_controller/server/Receiver/RequestReqTest.java
9011
package org.presentation4you.resource_controller.server.Receiver; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.presentation4you.resource_controller.commons.Request.*; import org.presentation4you.resource_controller.commons.RequestsFields.RequestsFields; import org.presentation4you.resource_controller.commons.Response.AddRequestResp; import org.presentation4you.resource_controller.commons.Response.GetRequestsResp; import org.presentation4you.resource_controller.commons.Response.IResponse; import org.presentation4you.resource_controller.commons.Response.ResponseStatus; import org.presentation4you.resource_controller.commons.Role.Coordinator; import org.presentation4you.resource_controller.commons.Role.Employee; import org.presentation4you.resource_controller.commons.Role.IRole; import org.presentation4you.resource_controller.server.Repository.IRepositoryWrapper; import org.presentation4you.resource_controller.server.Repository.IntegrationTestsRepository; import org.presentation4you.resource_controller.server.Repository.RepositoryWrapper; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import static org.junit.Assert.*; public class RequestReqTest { private static final String PROJECTOR = "Projector"; private static final int ID = 1; private final String DATE_TO_TEST = "14/06/2015 14:30"; private final String DATE_TO_TEST2 = "14/06/2015 15:30"; private IRole defaultRole = new Employee().setLogin("user") .setPassword("user"); private IRole admin = new Coordinator().setLogin("admin").setPassword("admin"); private IntegrationTestsRepository itr = new IntegrationTestsRepository(); private IRepositoryWrapper repo = new RepositoryWrapper().setRequestRepo(itr).setUserRepo(itr); private ResourceReqTest resourceTest = new ResourceReqTest(); @Before public void prepareTestDB() { itr.deleteAll(); } @After public void deleteAll() { itr.deleteAll(); } @Test public void canReturnOkIfRequestHasBeenAdded() { IResponse response = getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); assertTrue(response.isOk()); } @Test public void canAddRequest() { AddRequestResp response = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); assertTrue(itr.hasRequest(response.getId())); } @Test public void canReturnAlreadyHasIfRequestHasNotBeenAdded() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); IRequest request = new UpdateRequestReq(admin, addReqResponse.getId(), true); request.setRepository(repo); request.exec(); IResponse response = getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); assertEquals(response.getStatus(), ResponseStatus.ALREADY_HAS); } @Test public void canReturnOkIfRequestHasBeenRemoved() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); IRequest request = new RemoveRequestReq(defaultRole, addReqResponse.getId()); request.setRepository(repo); IResponse response = request.exec(); assertEquals(ResponseStatus.OK, response.getStatus()); } @Test public void canRemoveRequest() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); IRequest request = new RemoveRequestReq(defaultRole, addReqResponse.getId()); request.setRepository(repo); request.exec(); assertFalse(itr.hasRequest(addReqResponse.getId())); } @Test public void canReturnNotValidForRemoveRequestIfRoleIsNotStoredOwner() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); IRequest request = new RemoveRequestReq(defaultRole.setLogin("noSuchUser"), addReqResponse.getId()); request.setRepository(repo); IResponse response = request.exec(); assertEquals(response.getStatus(), ResponseStatus.NOT_VALID); } @Test public void canReturnOkIfRequestHasBeenUpdated() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); IRequest request = new UpdateRequestReq(admin, addReqResponse.getId(), true); request.setRepository(repo); IResponse response = request.exec(); assertTrue(response.isOk()); } @Test public void canReturnNotFoundIfRequestHasNotBeenUpdated() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); IRequest request = new UpdateRequestReq(admin, addReqResponse.getId() + 1, true); request.setRepository(repo); IResponse response = request.exec(); assertEquals(response.getStatus(), ResponseStatus.NOT_FOUND); } @Test public void canReturnNotValidForUpdateRequestIfRoleIsEmployee() { AddRequestResp addReqResponse = (AddRequestResp) getIResponseAfterAddedRequestReq(ID, DATE_TO_TEST); Request request = new UpdateRequestReq(defaultRole, addReqResponse.getId(), true); request.setRepository(repo); IResponse response = request.exec(); assertEquals(response.getStatus(), ResponseStatus.NOT_VALID); } @Test public void canGetOneRequest() { resourceTest.canAddResource(); int resId = resourceTest.getResId(); getIResponseAfterAddedRequestReq(resId, DATE_TO_TEST); RequestsFields match = new RequestsFields().setLogin(defaultRole.getLogin()) .setResourceId(resId); IRequest request = new GetRequestsReq(defaultRole, match); request.setRepository(repo); GetRequestsResp response = (GetRequestsResp) request.exec(); RequestsFields gotRequest = response.getRequests().get(0); assertEquals(resId, gotRequest.getResourceId()); } @Test public void canGetSeveralRequests() { resourceTest.canAddResource(); int resId = resourceTest.getResId(); getIResponseAfterAddedRequestReq(resId, DATE_TO_TEST); getIResponseAfterAddedRequestReq(resId, DATE_TO_TEST2); RequestsFields match = new RequestsFields().setLogin(defaultRole.getLogin()) .setResourceId(resId); IRequest request = new GetRequestsReq(defaultRole, match); request.setRepository(repo); GetRequestsResp response = (GetRequestsResp) request.exec(); List<RequestsFields> gotRequests = response.getRequests(); for (RequestsFields gotRequest : gotRequests) { assertEquals(defaultRole.getLogin(), gotRequest.getLogin()); assertEquals(resId, gotRequest.getResourceId()); } } @Test public void canGetRequestByFullMatch() { resourceTest.canAddResource(); int resId = resourceTest.getResId(); getIResponseAfterAddedRequestReq(resId, DATE_TO_TEST); RequestsFields match = new RequestsFields().setLogin(defaultRole.getLogin()) .setResourceId(resId).setFrom(buildCalendarFromString(DATE_TO_TEST)) .setTo(buildCalendarFromString(DATE_TO_TEST2)) .setIsApproved(false).setResourceType(resourceTest.PROJECTOR); IRequest request = new GetRequestsReq(defaultRole, match); request.setRepository(repo); GetRequestsResp response = (GetRequestsResp) request.exec(); RequestsFields gotRequest = response.getRequests().get(0); assertEquals(resId, gotRequest.getResourceId()); } private IResponse getIResponseAfterAddedRequestReq(final int resourceId, final String dateFrom) { Calendar from = buildCalendarFromString(dateFrom); Calendar to = (Calendar) from.clone(); to.add(Calendar.HOUR_OF_DAY, 1); Request request = createAddRequestReq(resourceId, from, to); return request.exec(); } private Calendar buildCalendarFromString(String requiredDate) { DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm"); Date date; try { date = formatter.parse(requiredDate); } catch (ParseException pe) { pe.printStackTrace(); return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar; } private Request createAddRequestReq(final int resourceId, final Calendar from, final Calendar to) { Request request = new AddRequestReq(defaultRole, resourceId, from, to); request.setRepository(repo); return request; } }
gpl-2.0
TheCommedian/ArqSoft
source/TurnsPOC/TurnsPOC-ejb/src/java/core/SourceCatalogBeanRemote.java
746
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package core; import java.util.List; import java.util.Optional; import javax.ejb.Remote; /** * * @author Marcelo Barberena / Fernando Maidana */ @Remote public interface SourceCatalogBeanRemote { List<TurnSource> getTurnSources(); void addSource(TurnSource source) throws IllegalArgumentException; void removeSource(TurnSource source); Optional<TurnSource> findSourceById(int sourceId); Optional<TurnSource> findSourceByDescription(String description) throws IllegalArgumentException; }
gpl-2.0
stratosk/semaphore_manager
sm/src/main/java/com/semaphore/smproperties/SMOndemandI9000Property.java
1397
/* Semaphore Manager * * Copyright (c) 2012 - 2014 Stratos Karafotis (stratosk@semaphore.gr) * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ package com.semaphore.smproperties; import java.util.List; public class SMOndemandI9000Property extends SMOndemandProperty { public SMIntProperty sampling_down_max_momentum; public SMIntProperty smooth_ui; public SMOndemandI9000Property() { super(); io_is_busy.setDefault(0); sampling_down_factor.setDefault(4); sampling_down_factor.setDynamic(true); sampling_down_max_momentum = new SMIntProperty("o_sampling_down_max_momentum", basepath.concat("sampling_down_max_momentum"), true, 1, 1000, 16); smooth_ui = new SMIntProperty("o_smooth_ui", basepath.concat("smooth_ui"), false, 0, 1, 0); } @Override public void readValue() { super.readValue(); sampling_down_max_momentum.readValue(); smooth_ui.readValue(); } @Override public void writeValue() { super.writeValue(); sampling_down_max_momentum.writeValue(); smooth_ui.writeValue(); } @Override public void writeBatch(List<String> cmds) { super.writeBatch(cmds); sampling_down_max_momentum.writeBatch(cmds); smooth_ui.writeBatch(cmds); } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/openws/org/opensaml/ws/wsaddressing/impl/AddressUnmarshaller.java
1093
/* * Licensed to the University Corporation for Advanced Internet Development, * Inc. (UCAID) under one or more contributor license agreements. See the * NOTICE file distributed with this work for additional information regarding * copyright ownership. The UCAID licenses this file to You under the Apache * License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensaml.ws.wsaddressing.impl; import org.opensaml.ws.wsaddressing.Address; /** * Unmarshaller for the &lt;wsa:Address&gt; element. * * @see Address * */ public class AddressUnmarshaller extends AttributedURIUnmarshaller { }
gpl-2.0
dzonekl/oss2nms
plugins/com.netxforge.oss2.icmp/src/com/netxforge/oss2/icmp/Pinger.java
6047
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package com.netxforge.oss2.icmp; import java.io.IOException; import java.net.InetAddress; import java.util.List; /** * <p>Pinger class.</p> * * @author <a href="mailto:ranger@opennms.org">Ben Reed</a> * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> */ public interface Pinger { /** * This method is used to ping a remote host to test for ICMP support. Calls * the callback method upon success or error. * * @param host The {@link java.net.InetAddress} address to poll. * @param timeout The time to wait between each retry. * @param retries The number of times to retry. * @param packetsize The size in byte of the ICMP packet. * @param sequenceId an ID representing the ping * * @param cb the {@link org.opennms.netmgt.ping.PingResponseCallback} callback to call upon success or error */ public void ping(InetAddress host, long timeout, int retries, int packetsize, int sequenceId, PingResponseCallback cb) throws Exception; /** * This method is used to ping a remote host to test for ICMP support. Calls * the callback method upon success or error. * * @param host The {@link java.net.InetAddress} address to poll. * @param timeout The time to wait between each retry. * @param retries The number of times to retry. * @param sequenceId an ID representing the ping * * @param cb the {@link org.opennms.netmgt.ping.PingResponseCallback} callback to call upon success or error */ public void ping(InetAddress host, long timeout, int retries, int sequenceId, PingResponseCallback cb) throws Exception; /** * This method is used to ping a remote host to test for ICMP support. If * the remote host responds within the specified period, defined by retries * and timeouts, then the response time is returned. * * @param host The {@link java.net.InetAddress} address to poll. * @param timeout The time to wait between each retry. * @param retries The number of times to retry. * @param packetsize The size in byte of the ICMP packet. * @return The response time in microseconds if the host is reachable and has responded with an echo reply, otherwise a null value. */ public Number ping(InetAddress host, long timeout, int retries, int packetsize) throws Exception; /** * This method is used to ping a remote host to test for ICMP support. If * the remote host responds within the specified period, defined by retries * and timeouts, then the response time is returned. * * @param host The {@link java.net.InetAddress} address to poll. * @param timeout The time to wait between each retry. * @param retries The number of times to retry. * @return The response time in microseconds if the host is reachable and has responded with an echo reply, otherwise a null value. */ public Number ping(InetAddress host, long timeout, int retries) throws Exception; /** * Ping a remote host, using the default number of retries and timeouts. * * @param host The {@link java.net.InetAddress} address to poll. * @return The response time in microseconds if the host is reachable and has responded with an echo reply, otherwise a null value. * @throws IOException if any. * @throws InterruptedException if any. * @throws java.lang.Exception if any. */ public Number ping(InetAddress host) throws Exception; /** * Ping a remote host, sending 1 or more packets at the given interval, and then * return the response times as a list. * * @param host The {@link java.net.InetAddress} address to poll. * @param count The number of packets to send. * @param timeout The time to wait between each retry. * @param pingInterval The interval at which packets will be sent. * @return a {@link java.util.List} of response times in microseconds. * If, for a given ping request, the host is reachable and has responded with an * echo reply, it will contain a number, otherwise a null value. */ public List<Number> parallelPing(InetAddress host, int count, long timeout, long pingInterval) throws Exception; /** * Initialize IPv4 in this Pinger implementation. If unable to do so, implementations should throw an exception. * @throws Exception */ public void initialize4() throws Exception; /** * Initialize IPv6 in this Pinger implementation. If unable to do so, implementations should throw an exception. * @throws Exception */ public void initialize6() throws Exception; /** * Whether or not IPv4 is initialized and available for this implementation. */ public boolean isV4Available(); /** * Whether or not IPv6 is initialized and available for this implementation. * @return */ public boolean isV6Available(); }
gpl-3.0
RekaDowney/gradprj
src/main/java/me/junbin/gradprj/util/validate/exception/PropertyIsBlankException.java
603
package me.junbin.gradprj.util.validate.exception; /** * @author : Zhong Junbin * @email : <a href="mailto:rekadowney@163.com">发送邮件</a> * @createDate : 2017/2/16 20:00 * @description : */ public class PropertyIsBlankException extends PropertyIsEmptyException { public PropertyIsBlankException() { } public PropertyIsBlankException(String message) { super(message); } public PropertyIsBlankException(String message, Throwable cause) { super(message, cause); } public PropertyIsBlankException(Throwable cause) { super(cause); } }
gpl-3.0
fofferhorn/Data-Mining-Individual
src/datamining/clustering/kMean/KMeans.java
6008
package datamining.clustering.kMean; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import datamining.datastructure.DataRow; import datamining.datastructure.Person; public class KMeans { public static Map<Person, KMeanCluster> KMeansPartition(int k, List<Person> data) { Map<Person, KMeanCluster> clustering = new HashMap<>(); // Make the first k irises the centers for the clusters for (int i = 0; i < k; i++) { clustering.put(data.get(i), new KMeanCluster()); } for (Person p : data) { double minDist = Double.MAX_VALUE; Person minCluster = new Person(0.0, DataRow.Gender.APACHE_HELICOPTER, 0.0, 0.0); for (Map.Entry<Person, KMeanCluster> cluster : clustering.entrySet()) { double dist = personDistance(p, cluster.getKey()); if (dist < minDist) { minDist = dist; minCluster = cluster.getKey(); } } // System.out.println("person: " + Person.toString(p) + " cluster: " + Person.toString(minCluster)); clustering.get(minCluster).ClusterMembers.add(p); } // for (Map.Entry<Person, KMeanCluster> clust : clustering.entrySet()) { // System.out.println("\n\n\n"); // System.out.println(Person.toString(clust.getKey())); // System.out.println(clust.getValue().toString()); // } Map<Person, KMeanCluster> newClustering = clustering; Map<Person, KMeanCluster> oldClustering; boolean oldEqualsNew = false; while (!oldEqualsNew) { // System.out.println("-------------------------------------------------------------------------"); oldClustering = newClustering; // for (Map.Entry<Person, KMeanCluster> clust : oldClustering.entrySet()) { // System.out.println("\n\n\n"); // System.out.println(Person.toString(clust.getKey())); // System.out.println(clust.getValue().toString()); // } // find centers of clusters newClustering = new HashMap<>(); for (Map.Entry<Person, KMeanCluster> cluster : oldClustering.entrySet()) { Person center = cluster.getValue().clusterMean(); newClustering.put(center, new KMeanCluster()); } // fill data into the clusters for (Person p : data) { double minDist = Double.MAX_VALUE; Person minCluster = new Person(0.0, DataRow.Gender.APACHE_HELICOPTER, 0.0, 0.0); for (Map.Entry<Person, KMeanCluster> cluster : newClustering.entrySet()) { double dist = personDistance(p, cluster.getKey()); if (dist < minDist) { minDist = dist; minCluster = cluster.getKey(); } } newClustering.get(minCluster).ClusterMembers.add(p); } // Check if the two clusterings are the same now oldEqualsNew = true; for (Map.Entry<Person, KMeanCluster> n : newClustering.entrySet()) { KMeanCluster o = oldClustering.get(n.getKey()); if (o == null) { oldEqualsNew = false; break; } else { if (n.getValue().ClusterMembers.size() != o.ClusterMembers.size()) { oldEqualsNew = false; break; } for (int i = 0; i < o.ClusterMembers.size(); i++) { Person p1 = n.getValue().ClusterMembers.get(i); Person p2 = o.ClusterMembers.get(i); if (!p1.equals(p2)) { oldEqualsNew = false; break; } } if (!oldEqualsNew) break; if (!n.getValue().ClusterMembers.equals(o.ClusterMembers)) { oldEqualsNew = false; break; } } } try { PrintWriter writer = new PrintWriter("resources/gender.txt", "UTF-8"); for (Map.Entry<Person, KMeanCluster> n : newClustering.entrySet()) { writer.println(Person.toString(n.getKey())); for (Person p : n.getValue().ClusterMembers) { writer.println("\t\t" + Person.toString(p)); } } writer.close(); } catch(IOException e){ System.out.println(e.getMessage()); } } return newClustering; } /** * Calculates the distance between two persons. * @param p1 * @param p2 * @return */ private static double personDistance(Person p1, Person p2) { double dist = 0.0; dist += Math.pow(Math.abs(p1.age - p2.age), 2); dist += Math.pow(Math.abs(p1.height - p2.height), 2); dist += Math.pow(Math.abs(p1.shoeSize - p2.shoeSize), 2); //if (!p1.gender.equals(p2.gender)) dist++; return Math.sqrt(dist); } /** * Prints a clustering * @param clustering */ public static void printClustering(Map<Person, KMeanCluster> clustering) { for (Map.Entry<Person, KMeanCluster> cluster : clustering.entrySet()) { System.out.println("----------------------------------------------------------------------"); System.out.println(Person.toString(cluster.getKey())); for (Person p : cluster.getValue().ClusterMembers) { System.out.println("\t" + Person.toString(p)); } System.out.println("----------------------------------------------------------------------"); } } }
gpl-3.0
bergerkiller/SpigotSource
src/main/java/net/minecraft/server/SlotFurnaceResult.java
2780
package net.minecraft.server; import javax.annotation.Nullable; // CraftBukkit start import org.bukkit.entity.Player; import org.bukkit.event.inventory.FurnaceExtractEvent; // CraftBukkit end public class SlotFurnaceResult extends Slot { private EntityHuman a; private int b; public SlotFurnaceResult(EntityHuman entityhuman, IInventory iinventory, int i, int j, int k) { super(iinventory, i, j, k); this.a = entityhuman; } public boolean isAllowed(@Nullable ItemStack itemstack) { return false; } public ItemStack a(int i) { if (this.hasItem()) { this.b += Math.min(i, this.getItem().count); } return super.a(i); } public void a(EntityHuman entityhuman, ItemStack itemstack) { this.c(itemstack); super.a(entityhuman, itemstack); } protected void a(ItemStack itemstack, int i) { this.b += i; this.c(itemstack); } protected void c(ItemStack itemstack) { itemstack.a(this.a.world, this.a, this.b); if (!this.a.world.isClientSide) { int i = this.b; float f = RecipesFurnace.getInstance().b(itemstack); int j; if (f == 0.0F) { i = 0; } else if (f < 1.0F) { j = MathHelper.d((float) i * f); if (j < MathHelper.f((float) i * f) && Math.random() < (double) ((float) i * f - (float) j)) { ++j; } i = j; } // CraftBukkit start - fire FurnaceExtractEvent Player player = (Player) a.getBukkitEntity(); TileEntityFurnace furnace = ((TileEntityFurnace) this.inventory); org.bukkit.block.Block block = a.world.getWorld().getBlockAt(furnace.position.getX(), furnace.position.getY(), furnace.position.getZ()); if (b != 0) { FurnaceExtractEvent event = new FurnaceExtractEvent(player, block, org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(itemstack.getItem()), b, i); a.world.getServer().getPluginManager().callEvent(event); i = event.getExpToDrop(); } // CraftBukkit end while (i > 0) { j = EntityExperienceOrb.getOrbValue(i); i -= j; this.a.world.addEntity(new EntityExperienceOrb(this.a.world, this.a.locX, this.a.locY + 0.5D, this.a.locZ + 0.5D, j)); } } this.b = 0; if (itemstack.getItem() == Items.IRON_INGOT) { this.a.b((Statistic) AchievementList.k); } if (itemstack.getItem() == Items.COOKED_FISH) { this.a.b((Statistic) AchievementList.p); } } }
gpl-3.0
puzza007/Etymon
src/etymology/context/CandidateFinder.java
16080
/** Copyright (C) 2010-2012 University of Helsinki. This file is part of Etymon. Etymon is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Etymon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Etymon. If not, see <http://www.gnu.org/licenses/>. **/ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package etymology.context; import etymology.config.Configuration; import etymology.context.FeatureTreeContainer.BabyTreeType; import etymology.context.FeatureTreeContainer.Context; import etymology.context.FeatureTreeContainer.Features; import etymology.context.FeatureTreeContainer.Level; import etymology.context.FeatureTreeContainer.TreeType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * * @author sxhiltun */ public class CandidateFinder { private static boolean binaryCandidates = false; private static boolean normalCandidates = true; private static boolean oneLevelCandidatesOnly = false; public static void setBinaryCandidates(boolean useCandidates) { binaryCandidates = useCandidates; } public static void setNormalCandidates(boolean use) { normalCandidates = use; } public static void setOneLevelCandidatesOnly(boolean oneLevelOnly) { oneLevelCandidatesOnly = oneLevelOnly; } public static List<Candidate> getRestrictedListOfCandidatesOfRootNode(FeatureTree tree) { List<Candidate> candidates = new ArrayList(); List<Level> sourceLevel = new ArrayList<Level>(Arrays.asList(Level.SOURCE)); switch(tree.getBabyTreeType()) { case SOURCE: if (Configuration.getInstance().isCodeCompleteWordFirst()) { return new ArrayList<Candidate>(); } //zero-depth-converge: while sim-ann, no candidates on source side! if (Configuration.getInstance().isZeroDepthTricks() && Configuration.getInstance().isUseSimulatedAnnealing()) { return new ArrayList<Candidate>(); } //root-restrictions when normal sim-ann (= infinite depth model): if (Configuration.getInstance().getInfiniteDepth()) { candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.SOURCE); candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); return candidates; } //no restrictions!!! candidates = getListOfCandidates(tree); break; case TARGET: if (Configuration.getInstance().isCodeCompleteWordFirst()) { return getListOfCandidates(tree); } //zero-depth-converge if (Configuration.getInstance().isZeroDepthTricks() && Configuration.getInstance().isUseSimulatedAnnealing()) { candidates = getCandidatesOfItselfContextOnOppositeLevel(tree, candidates); return candidates; } //root-restrictions when sim-ann on: if (Configuration.getInstance().getInfiniteDepth()) { //old version of inf-depth-restricted if (Configuration.getInstance().isUsePreviousVersion()) { candidates = getCandidatesOfItselfContextOnOppositeLevel(tree, candidates); candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); return candidates; } candidates = getCandidatesOfItselfContextOnOppositeLevel(tree, candidates); return candidates; } //no restrictions!!! candidates = getListOfCandidates(tree); break; case JOINT: //return nothing if (Configuration.getInstance().isZeroDepthTricks() && Configuration.getInstance().isUseSimulatedAnnealing()) { return candidates; } candidates = getListOfCandidates(tree); //closest context missing. --> find out when ok? // candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.SOURCE); // candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.TARGET); // candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); // candidates = getCommonCandidatesOfAllTrees(candidates, targetLevel); break; default: throw new RuntimeException("Unknown alignment type"); } return candidates; } public static List<Candidate> getListOfCandidates(FeatureTree tree) { List<Candidate> candidates = new ArrayList<Candidate>(); List<Level> sourceLevel = new ArrayList<Level>(Arrays.asList(Level.SOURCE)); List<Level> targetLevel = new ArrayList<Level>(Arrays.asList(Level.TARGET)); switch(tree.getBabyTreeType()) { case SOURCE: //first code the complete sourceword, check if ok if (Configuration.getInstance().isCodeCompleteWordFirst()) { return new ArrayList<Candidate>(); } //zero-depth-converge if (Configuration.getInstance().isZeroDepthTricks() && Configuration.getInstance().isUseSimulatedAnnealing()) { return new ArrayList<Candidate>(); } //inf-depth has restrictions only on root level if (oneLevelCandidatesOnly) { candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.SOURCE); candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); return candidates; } //no restrictions - normal tree building candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.SOURCE); candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); candidates = getCommonCandidatesOfAllTrees(candidates, targetLevel); break; case TARGET: if (!Configuration.getInstance().isCodeCompleteWordFirst() && Configuration.getInstance().isZeroDepthTricks() && Configuration.getInstance().isUseSimulatedAnnealing()) { //old version, do nothing on deeper levels if (Configuration.getInstance().isUsePreviousVersion()) { return new ArrayList<Candidate>(); } return getCandidatesOfItselfContextOnOppositeLevel(tree, candidates); } //no restrictions - normal tree building candidates = getCandidatesOfItselfContextOnOppositeLevel(tree, candidates); candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.TARGET); candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); candidates = getCommonCandidatesOfAllTrees(candidates, targetLevel); if (Configuration.getInstance().isCodeCompleteWordFirst()) { candidates = getFutureCandidates(candidates, sourceLevel); } candidates = getCandidatesOfClosestContext(tree, candidates); break; case JOINT: //zero-depth-converge if (Configuration.getInstance().isZeroDepthTricks() && Configuration.getInstance().isUseSimulatedAnnealing()) { return new ArrayList<Candidate>(); } //prev context always ok candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.SOURCE); candidates = getCandidatesOfItselfContextOnMyLevel(tree, candidates, Level.TARGET); //itself context already coded ok candidates = getCommonCandidatesOfAllTrees(candidates, sourceLevel); candidates = getCommonCandidatesOfAllTrees(candidates, targetLevel); break; default: throw new RuntimeException("Unknown alignment type"); } return candidates; } private static List<Candidate> getCandidatesOfClosestContext(FeatureTree tree, List<Candidate> candidates) { //context = closest List<Level> level; List<Features> features; List<Context> context; switch(tree.getBabyTreeType()) { case SOURCE: //i know nothing about itself context on target level yet, //i don't know everything about myself yet return candidates; case TARGET: //we can only ask what's on source level level = Arrays.asList(Level.SOURCE); break; default: throw new RuntimeException("Unknown alignment type"); } context = Arrays.asList(Context.CLOSEST_SYMBOL); features = Features.getFullFeatureSet(); candidates = enumerateCandidates(candidates, level, context, features); context = Arrays.asList(Context.CLOSEST_VOWEL); features = Features.getVowelFeatures(); candidates = enumerateCandidates(candidates, level, context, features); context = Arrays.asList(Context.CLOSEST_CONSONANT); features = Features.getConsonantFeatures(); candidates = enumerateCandidates(candidates, level, context, features); return candidates; } private static List<Candidate> getCandidatesOfItselfContextOnMyLevel(FeatureTree tree, List<Candidate> candidates, Level level) { List<Level> levelList = new ArrayList<Level>(Arrays.asList(level)); List<Context> contextList = new ArrayList<Context>(Arrays.asList(Context.ITSELF)); List<Features> filteredFeatures; //Type feature is always the first in order List<Features> allFeatureNames = new ArrayList<Features>(Features.getTypeFeature()); if (tree.getTreeType().equals(TreeType.VOWEL)) { //i am a vowel allFeatureNames.addAll(Features.getVowelFeatures()); } else if (tree.getTreeType().equals(TreeType.CONSONANT)) { //i'm a consonant allFeatureNames.addAll(Features.getConsonantFeatures()); } //else i'm a type tree, there is nothing to ask about myself on my level //pick the features before this feature in coding order int firstIndex = 0; int lastIndex = allFeatureNames.indexOf(tree.getFeatureName()); filteredFeatures = new ArrayList<Features>(); filteredFeatures.addAll(allFeatureNames.subList(firstIndex, lastIndex)); candidates = enumerateCandidates(candidates, levelList, contextList, filteredFeatures); return candidates; } private static List<Candidate> getCandidatesOfItselfContextOnOppositeLevel(FeatureTree tree, List<Candidate> candidates) { List<Level> oppositeLevel; List<Context> context; //pick alignment type switch(tree.getBabyTreeType()) { case SOURCE: //i know nothing about itself context on target level yet break; case TARGET: context = new ArrayList<Context>(Arrays.asList(Context.ITSELF)); oppositeLevel = new ArrayList<Level>(Arrays.asList(Level.SOURCE)); //it's ok to ask everything candidates = enumerateCandidates(candidates, oppositeLevel, context, Features.getFullFeatureSet()); break; default: throw new RuntimeException("Unknown alignment type"); } return candidates; } private static List<Candidate> getFutureCandidates(List<Candidate> candidates, List<Level> levels) { List<Context> contexts; List<Features> features; //context = next C contexts = Arrays.asList(Context.NEXT_CONSONANT); features = Features.getConsonantFeatures(); features.add(Features.TYPE); candidates = enumerateCandidates(candidates, levels, contexts, features); //context = next V contexts = Arrays.asList(Context.NEXT_VOWEL); features = Features.getVowelFeatures(); features.add(Features.TYPE); candidates = enumerateCandidates(candidates, levels, contexts, features); //context = prev S contexts = Arrays.asList(Context.NEXT_SYMBOL); features = Features.getFullFeatureSet(); candidates = enumerateCandidates(candidates, levels, contexts, features); return candidates; } private static List<Candidate> getCommonCandidatesOfAllTrees(List<Candidate> candidates, List<Level> levels) { List<Context> contexts; List<Features> features; //context = prev C contexts = Arrays.asList(Context.PREVIOUS_CONSONANT); features = Features.getConsonantFeatures(); features.add(Features.TYPE); //No type feature: is there point to ask what is the type of the previous consonant? candidates = enumerateCandidates(candidates, levels, contexts, features); //context = prev V contexts = Arrays.asList(Context.PREVIOUS_VOWEL); features = Features.getVowelFeatures(); features.add(Features.TYPE); candidates = enumerateCandidates(candidates, levels, contexts, features); //context = prev S contexts = Arrays.asList(Context.PREVIOUS_SYMBOL); features = Features.getFullFeatureSet(); candidates = enumerateCandidates(candidates, levels, contexts, features); //context = prev P contexts = Arrays.asList(Context.PREVIOUS_POSITION); features = Features.getFullFeatureSet(); candidates = enumerateCandidates(candidates, levels, contexts, features); //context = prev VG // contexts = Arrays.asList(Context.PREVIOUS_VOWEL_GROUP); // features = Features.getVowelFeatures(); // features.add(Features.TYPE); // candidates = enumerateCandidates(candidates, levels, contexts, features); return candidates; } private static List<Candidate> enumerateCandidates(List<Candidate> candidates, List<Level> levels, List<Context> contexts, List<Features> features) { Candidate candidate; for (Level l: levels) { for (Context c: contexts) { for (Features f: features) { if (binaryCandidates) { for (char m : f.getFeatureValueNames()) { candidate = new Candidate(l, c, f, m); candidates.add(candidate); } } if (normalCandidates) { candidate = new Candidate(l, c, f); candidates.add(candidate); } } } } return candidates; } }
gpl-3.0
flankerhqd/JAADAS
soot/generated/sablecc/soot/jimple/parser/node/ADeclaration.java
3874
/* This file was generated by SableCC (http://www.sablecc.org/). */ package soot.jimple.parser.node; import soot.jimple.parser.analysis.*; @SuppressWarnings("nls") public final class ADeclaration extends PDeclaration { private PJimpleType _jimpleType_; private PLocalNameList _localNameList_; private TSemicolon _semicolon_; public ADeclaration() { // Constructor } public ADeclaration( @SuppressWarnings("hiding") PJimpleType _jimpleType_, @SuppressWarnings("hiding") PLocalNameList _localNameList_, @SuppressWarnings("hiding") TSemicolon _semicolon_) { // Constructor setJimpleType(_jimpleType_); setLocalNameList(_localNameList_); setSemicolon(_semicolon_); } @Override public Object clone() { return new ADeclaration( cloneNode(this._jimpleType_), cloneNode(this._localNameList_), cloneNode(this._semicolon_)); } public void apply(Switch sw) { ((Analysis) sw).caseADeclaration(this); } public PJimpleType getJimpleType() { return this._jimpleType_; } public void setJimpleType(PJimpleType node) { if(this._jimpleType_ != null) { this._jimpleType_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._jimpleType_ = node; } public PLocalNameList getLocalNameList() { return this._localNameList_; } public void setLocalNameList(PLocalNameList node) { if(this._localNameList_ != null) { this._localNameList_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._localNameList_ = node; } public TSemicolon getSemicolon() { return this._semicolon_; } public void setSemicolon(TSemicolon node) { if(this._semicolon_ != null) { this._semicolon_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._semicolon_ = node; } @Override public String toString() { return "" + toString(this._jimpleType_) + toString(this._localNameList_) + toString(this._semicolon_); } @Override void removeChild(@SuppressWarnings("unused") Node child) { // Remove child if(this._jimpleType_ == child) { this._jimpleType_ = null; return; } if(this._localNameList_ == child) { this._localNameList_ = null; return; } if(this._semicolon_ == child) { this._semicolon_ = null; return; } throw new RuntimeException("Not a child."); } @Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._jimpleType_ == oldChild) { setJimpleType((PJimpleType) newChild); return; } if(this._localNameList_ == oldChild) { setLocalNameList((PLocalNameList) newChild); return; } if(this._semicolon_ == oldChild) { setSemicolon((TSemicolon) newChild); return; } throw new RuntimeException("Not a child."); } }
gpl-3.0
docteurdux/code
dux/src/test/java/dux/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatchTest.java
4563
package dux.org.hibernate.engine.jdbc.batch.internal; import java.lang.reflect.Constructor; import java.sql.PreparedStatement; import org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl; import org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch; import org.hibernate.engine.jdbc.batch.spi.BatchKey; import org.hibernate.engine.jdbc.spi.JdbcCoordinator; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.junit.Before; import org.junit.Test; import com.github.docteurdux.test.AbstractTest; import com.github.docteurdux.test.RunnableWithArgs; import dum.java.sql.DummyPreparedStatement; import dum.org.hibernate.engine.jdbc.batch.spi.DummyBatchKey; import dum.org.hibernate.engine.jdbc.batch.spi.DummyBatchObserver; import dum.org.hibernate.engine.jdbc.spi.DummyJdbcCoordinator; import dum.org.hibernate.engine.jdbc.spi.DummyJdbcServices; import dum.org.hibernate.engine.jdbc.spi.DummyResultSetReturn; import dum.org.hibernate.engine.jdbc.spi.DummyStatementPreparer; import dum.org.hibernate.jdbc.DummyExpectation; import dum.org.hibernate.resource.jdbc.DummyResourceRegistry; import dum.org.hibernate.resource.jdbc.spi.DummyJdbcSessionContext; import dum.org.hibernate.resource.jdbc.spi.DummyJdbcSessionOwner; import dum.org.hibernate.resource.jdbc.spi.DummyLogicalConnectionImplementor; import dum.org.hibernate.service.DummyServiceRegistry; import dus.hibernate.core.HibernateCoreSummaryTest; public class NonBatchingBatchTest extends AbstractTest { private Constructor<NonBatchingBatch> constructor; private DummyBatchKey batchKey; private DummyJdbcCoordinator jdbcCoordinator; private DummyJdbcSessionOwner jdbcSessionOwner; private DummyJdbcServices jdbcServices; private DummyServiceRegistry serviceRegistry; private DummyJdbcSessionContext jdbcSessionContext; private DummyBatchObserver batchObserver; private DummyStatementPreparer statementPreparer; private DummyPreparedStatement preparedStatement; private DummyResultSetReturn resultSetReturn; private int rowCount; private DummyExpectation expectation; private DummyLogicalConnectionImplementor logicalConnectionImplementor; private DummyResourceRegistry resourceRegistry; @Before public void before() { rowCount = 1; requireSources(HibernateCoreSummaryTest.MVNNAME, NonBatchingBatch.class, AbstractBatchImpl.class); constructor = getConstructor(NonBatchingBatch.class, BatchKey.class, JdbcCoordinator.class); expectation = new DummyExpectation(); batchKey = new DummyBatchKey(); batchKey.setExpectation(expectation); jdbcServices = new DummyJdbcServices(); serviceRegistry = new DummyServiceRegistry(); serviceRegistry.setService(JdbcServices.class, jdbcServices); jdbcSessionContext = new DummyJdbcSessionContext(); jdbcSessionContext.setServiceRegistry(serviceRegistry); jdbcSessionOwner = new DummyJdbcSessionOwner(); jdbcSessionOwner.setJdbcSessionContext(jdbcSessionContext); preparedStatement = new DummyPreparedStatement(); statementPreparer = new DummyStatementPreparer(); statementPreparer.setPrepareStatementRWA(new RunnableWithArgs<PreparedStatement>() { @Override public PreparedStatement run(Object... args) { return preparedStatement; } }); resultSetReturn = new DummyResultSetReturn(); resultSetReturn.setExecuteUpdateRWA(new RunnableWithArgs<Integer>() { @Override public Integer run(Object... args) { return rowCount; } }); resourceRegistry = new DummyResourceRegistry(); logicalConnectionImplementor = new DummyLogicalConnectionImplementor(); logicalConnectionImplementor.setResourceRegistry(resourceRegistry); jdbcCoordinator = new DummyJdbcCoordinator(); jdbcCoordinator.setJdbcSessionOwner(jdbcSessionOwner); jdbcCoordinator.setStatementPreparer(statementPreparer); jdbcCoordinator.setResultSetReturn(resultSetReturn); jdbcCoordinator.setLogicalConnectionImplementor(logicalConnectionImplementor); batchObserver = new DummyBatchObserver(); } @Test public void test() { // weird ; behaves as if it were public in BatchBuilderImpl aeq(true, isProtected(constructor)); NonBatchingBatch nbb = instantiate(constructor, batchKey, jdbcCoordinator); nbb.addObserver(batchObserver); nbb.getBatchStatement("sql", false); nbb.addToBatch(); nbb.getBatchStatement("sql", false); nbb.release(); nbb.getBatchStatement("sql", false); nbb.execute(); dumpTestEvents(this); } }
gpl-3.0
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionScheduler.java
8572
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; public class AuctionScheduler implements Runnable { private CraftBayPlugin plugin; private LinkedList<Auction> queue = new LinkedList<Auction>(); private LinkedList<Auction> history = new LinkedList<Auction>(); private Auction current; private FileConfiguration conf; private int nextAuctionId = 0; private LinkedList<ItemDelivery> deliveries = new LinkedList<ItemDelivery>(); private Map<Integer, Auction> idMap = new HashMap<Integer, Auction>(); private BukkitTask task; private File getSaveFile() { File folder = plugin.getDataFolder(); if (!folder.exists()) folder.mkdir(); return new File(folder, "auctions.yml"); } public AuctionScheduler(CraftBayPlugin plugin) { this.plugin = plugin; } public void enable() { load(); task = Bukkit.getScheduler().runTaskTimer(plugin, this::run, 0L, 0L); } public void disable() { if (current != null) current.stop(); save(); task.cancel(); } private void addAuction(Auction auction) { idMap.put(auction.getId(), auction); } private void removeAuction(Auction auction) { idMap.remove(auction.getId()); } public Auction getById(int id) { return idMap.get(id); } public void queueAuction(Auction auction) { auction.setId(nextAuctionId++); addAuction(auction); queue.addFirst(auction); } public boolean unqueueAuction(Auction auction) { return queue.remove(auction); } @Override public void run() { checkDeliveries(); boolean dirty = false; if (current != null) { if (current.getState() == AuctionState.ENDED) { plugin.getAuctionHouse().endAuction(current); historyAuction(current); current = null; dirty = true; } else if (current.getState() == AuctionState.CANCELED) { historyAuction(current); current = null; dirty = true; } else if (current.getState() == AuctionState.QUEUED) { current.start(); dirty = true; } } else { while (current == null && !queue.isEmpty()) { Auction next = queue.removeLast(); if (next.getState() == AuctionState.CANCELED) { historyAuction(next); } else { current = next; current.start(); } dirty = true; } } if (dirty) { save(); } } private void historyAuction(Auction auction) { history.addFirst(auction); int maxHistory = plugin.getConfig().getInt("maxhistory"); while (history.size() > maxHistory) { removeAuction(history.removeLast()); } } public Auction getCurrentAuction() { return current; } public List<Auction> getQueue() { return new ArrayList<Auction>(queue); } public List<Auction> getHistory() { return new ArrayList<Auction>(history); } public List<Auction> getAllAuctions() { List<Auction> result = new ArrayList<Auction>(queue.size() + history.size() + 1); result.addAll(history); result.add(current); result.addAll(queue); return result; } public boolean canQueue() { int maxQueue = plugin.getConfig().getInt("maxqueue"); return queue.size() < maxQueue; } public void queueDelivery(ItemDelivery delivery) { deliveries.add(delivery); } public void checkDeliveries() { long currentDate = System.currentTimeMillis(); for (Iterator<ItemDelivery> it = deliveries.iterator(); it.hasNext();) { ItemDelivery delivery = it.next(); long age = Math.max(0, currentDate - delivery.getCreationDate().getTime()); long days = TimeUnit.MILLISECONDS.toDays(age); if (days > plugin.getConfig().getLong("itemexpiry")) { plugin.getLogger().info(String.format("DROP recipient='%s' item='%s' created='%s'", delivery.getRecipient().getName(), delivery.getItem().toString(), delivery.getCreationDate().toString())); it.remove(); } else if (delivery.getRecipient().isPlayer() && delivery.getRecipient().isOnline()) { delivery.remind(delivery.getRecipient().getPlayer()); } } } public boolean hasDeliveryWaiting(Player player) { for (ItemDelivery delivery : deliveries) { if (delivery.getRecipient().isPlayer(player)) return true; } return false; } public void deliver(Player player) { for (Iterator<ItemDelivery> iter = deliveries.iterator(); iter.hasNext();) { ItemDelivery delivery = iter.next(); if (delivery.getRecipient().isPlayer(player)) { iter.remove(); delivery.deliver(player); return; } } } private void save() { if (plugin.getDebugMode()) plugin.getLogger().info("saving"); conf.set("current", current); conf.set("queue", new ArrayList<Object>(queue)); conf.set("history", new ArrayList<Object>(history)); conf.set("deliveries", new ArrayList<Object>(deliveries)); try { conf.save(getSaveFile()); } catch (IOException ioe) { System.err.println(ioe); ioe.printStackTrace(); } } @SuppressWarnings("unchecked") private void load() { conf = YamlConfiguration.loadConfiguration(getSaveFile()); if (conf.getList("history") != null) history = new LinkedList<Auction>((List<Auction>)conf.getList("history")); else history = new LinkedList<Auction>(); if (conf.getList("queue") != null) queue = new LinkedList<Auction>((List<Auction>)conf.getList("queue")); else queue = new LinkedList<Auction>(); if (conf.get("current") != null) { current = (Auction)conf.get("current"); if (current != null && current.getState() == AuctionState.RUNNING) { current.start(); } } else { current = null; } int i = history.size() - 1; for (Auction auction : history) auction.setId(i--); if (current != null) current.setId(history.size()); i = history.size() + queue.size() - (current == null ? 1 : 0); for (Auction auction : queue) auction.setId(i--); nextAuctionId = history.size() + queue.size() + (current != null ? 1 : 0); for (Auction auction : queue) addAuction(auction); if (current != null) addAuction(current); for (Auction auction : history) addAuction(auction); if (conf.get("deliveries") != null) deliveries = new LinkedList<ItemDelivery>((List<ItemDelivery>)conf.getList("deliveries")); } }
gpl-3.0
putcn/JTileDownloader_TMS
src/org/openstreetmap/fma/jtiledownloader/Constants.java
1350
/* * Copyright 2008, Friedrich Maier * * This file is part of JTileDownloader. * (see http://wiki.openstreetmap.org/index.php/JTileDownloader) * * JTileDownloader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JTileDownloader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy (see file COPYING.txt) of the GNU * General Public License along with JTileDownloader. * If not, see <http://www.gnu.org/licenses/>. */ package org.openstreetmap.fma.jtiledownloader; public class Constants { public static final String VERSION = "0.6.1"; public static final double EARTH_CIRC_POLE = 40.007863 * Math.pow(10, 6); public static final double EARTH_CIRC_EQUATOR = 40.075016 * Math.pow(10, 6); public static final double MIN_LON = -180; public static final double MAX_LON = 180; public static final double MIN_LAT = -85.0511; public static final double MAX_LAT = 85.0511; }
gpl-3.0
FastCoddy/intellij-plugin
src/main/java/org/funivan/intellij/FastCoddy/Productivity/UsageStatistic.java
2105
package org.funivan.intellij.FastCoddy.Productivity; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.Nullable; /** * @author Ivan Shcherbak <alotofall@gmail.com> */ @State( name = "CoddyUsageStatistic", storages = { @Storage("fast-coddy.statistics.xml") } ) public class UsageStatistic implements PersistentStateComponent<UsageStatistic> { public Integer used = 0; public Integer maximumShortCodes = 0; public Integer usedShortCodes = 0; public Integer typedChars = 0; public Integer expandedChars = 0; private long firstStart = 0; public static void used() { FeatureUsageTracker.getInstance().triggerFeatureUsed(TemplatesProductivityFeatureProvider.LIVE_TEMPLATE_INVOKE); UsageStatistic.getSettings().used++; } public static void usedShortCodes(Integer shortCodesNum) { UsageStatistic statistic = UsageStatistic.getSettings(); if (shortCodesNum > statistic.maximumShortCodes) { statistic.maximumShortCodes = shortCodesNum; } statistic.usedShortCodes += shortCodesNum; } public static void typedChars(Integer charsNum) { UsageStatistic.getSettings().typedChars += charsNum; } public static void expandedChars(Integer charsNum) { UsageStatistic.getSettings().expandedChars += charsNum; } @Nullable @Override public UsageStatistic getState() { if (firstStart == 0) { firstStart = System.currentTimeMillis(); } return this; } public static UsageStatistic getSettings() { return ServiceManager.getService(UsageStatistic.class); } @Override public void loadState(UsageStatistic settings) { XmlSerializerUtil.copyBean(settings, this); } }
gpl-3.0
SupaHam/PowerJuice
src/main/java/com/supaham/powerjuice/game/GameListener.java
10108
package com.supaham.powerjuice.game; import com.supaham.powerjuice.PowerJuicePlugin; import com.supaham.powerjuice.events.game.GameStopEvent.Reason; import com.supaham.powerjuice.events.game.GamerMoveEvent; import com.supaham.powerjuice.events.game.gamersession.GamerPointsChangeEvent; import com.supaham.powerjuice.powerup.Powerup; import com.supaham.powerjuice.util.BlockUtil; import com.supaham.powerjuice.util.Language; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.minecart.StorageMinecart; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; public class GameListener implements Listener { private final Game game; private PowerJuicePlugin plugin; public GameListener(@NotNull Game game) { this.game = game; this.plugin = game.getPlugin(); } private GamerSession get(Player player) { return get(player, true); } private GamerSession get(Player player, boolean inGame) { GamerSession session = game.getSession(player); if (session == null) { return null; } return inGame && !session.isPlaying() ? null : session; } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { System.out.println("Joining..."); game.addSession(plugin.getPlayerManager().getPJPlayer(event.getPlayer())).setup(); } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { GamerSession session = get(event.getPlayer(), false); if (session != null) { session.quit(); } } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { if (event.isCancelled()) return; GamerSession session = get(event.getPlayer()); if (session != null) { GamerMoveEvent gamerMoveEvent = new GamerMoveEvent(session, event); Bukkit.getPluginManager().callEvent(gamerMoveEvent); } } @EventHandler(priority = EventPriority.LOWEST) public void onBlockBreak(BlockBreakEvent event) { GamerSession session = get(event.getPlayer()); if (session == null || session.getPJPlayer().isIgnored()) { return; } event.setCancelled(true); } @EventHandler(priority = EventPriority.LOWEST) public void onBlockPlace(BlockPlaceEvent event) { GamerSession session = get(event.getPlayer()); if (session == null || session.getPJPlayer().isIgnored()) { return; } event.setCancelled(true); } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerInteract(PlayerInteractEvent event) { GamerSession session = get(event.getPlayer()); if (session == null || session.getPJPlayer().isIgnored()) { return; } if (event.hasBlock() && BlockUtil.isContainer(event.getClickedBlock().getType())) { event.setCancelled(true); } } @EventHandler public void onGamerBalanceChange(GamerPointsChangeEvent event) { int goal = game.getProperties().getPointsGoal(); if (goal > 0 && event.getNewBalance() >= goal) { new BukkitRunnable() { @Override public void run() { game.getManager().stop(Reason.GOAL_REACHED); } }.runTask(plugin); } } @EventHandler public void powerupPickup(VehicleDestroyEvent event) { if (!(event.getVehicle() instanceof StorageMinecart)) { return; } Entity damager = event.getAttacker(); if (!(damager instanceof Player)) { return; } GamerSession session = get(((Player) damager)); if (session == null) { return; } event.setCancelled(true); givePowerup(event.getVehicle(), (Player) damager); } @EventHandler public void powerupPickup(PlayerInteractEntityEvent event) { if (!event.getRightClicked().getType().equals(EntityType.MINECART_CHEST)) { return; } Player player = event.getPlayer(); GamerSession session = get(player); if (session == null) { return; } event.setCancelled(true); givePowerup(event.getRightClicked(), player); } private void givePowerup(Entity entity, Player player) { GamerSession session = get(player); if (session.getPJPlayer().isIgnored() || session.isSpecatating()) { return; } Location loc = entity.getLocation(); Powerup powerup = game.getPowerupManager().getRandomPowerup(); powerup.give(player); game.getPowerupManager().spawnRandomPowerup(game.getProperties().getPowerupLocations(), entity); entity.remove(); } @EventHandler public void powerupConsume(PlayerItemConsumeEvent event) { Player player = event.getPlayer(); GamerSession session = get(player); if (session == null || session.getPJPlayer().isIgnored()) { return; } if (session.getCurrentPowerup() != null) { event.setCancelled(true); Language.Game.POWERUP_ALREADY_ACTIVE.send(player, session.getCurrentPowerup().getDisplayName()); return; } ItemStack item = event.getItem(); Powerup powerup = game.getPowerupManager().getPowerupByItemStack(item); if (powerup != null) { powerup.addUser(player); session.setCurrentPowerup(powerup); } } @EventHandler public void playerDeath(PlayerDeathEvent event) { GamerSession session = get(event.getEntity()); event.getDrops().clear(); event.setDroppedExp(0); session.die(); if (game.getStorm().getVictims().contains(event.getEntity())) { event.setDeathMessage(event.getEntity().getDisplayName() + " died to the storm."); } } @EventHandler public void playerRespawn(PlayerRespawnEvent event) { GamerSession session = get(event.getPlayer()); if (session == null) { return; } session.spawn(event); } @EventHandler public void onPlayerDamage(EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) { return; } Player player = (Player) event.getEntity(); if (event.getCause().equals(EntityDamageEvent.DamageCause.FALL)) { event.setCancelled(true); } GamerSession session = get(player); if (session != null) { session.launch(); } } @EventHandler public void onPlayerDamage(EntityDamageByEntityEvent event) { if (!(event.getEntity() instanceof Player)) { return; } Player victim = (Player) event.getEntity(); Player damager = event.getDamager() instanceof Player ? (Player) event.getDamager() : null; if (damager == null) { if (!(event.getDamager() instanceof Projectile)) { return; } ProjectileSource shooter = ((Projectile) event.getDamager()).getShooter(); if (shooter instanceof Player) { damager = (Player) shooter; } else { return; } } GamerSession victimSession = get(victim); GamerSession damagerSession = get(damager); if (victimSession == null || damagerSession == null || victim.equals(damager) || !damagerSession.isAlive()) { event.setCancelled(true); } } @EventHandler public void arrowHit(ProjectileHitEvent event) { if (event.getEntity() instanceof Arrow) { event.getEntity().remove(); } } @EventHandler public void playerSneak(PlayerToggleSneakEvent event) { if (!event.isSneaking()) { return; } Player player = event.getPlayer(); GamerSession session = get(player); if (session == null || session.getLastSneakLaunch() > 0) { return; } player.setVelocity(new Vector(0, -2, 0)); player.playSound(player.getLocation().subtract(0, 10, 0), Sound.FIREWORK_LAUNCH, 2F, 0.5F); session.setLastSneakLaunch(game.getProperties().getSneakLaunchCD()); } /* * ================================ * | MISC LISTENERS | * ================================ */ @EventHandler public void onFoodLevelChange(FoodLevelChangeEvent event) { GamerSession session = get(((Player) event.getEntity())); if (session == null) { return; } event.setFoodLevel(19); ((Player) event.getEntity()).setSaturation(20L); } }
gpl-3.0
Sector67/one-time-pad-library
src/org/sector67/otp/encoding/SimpleBase16Encoder.java
3395
/* * Copyright 2014 individual contributors as indicated by the @author * tags * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ package org.sector67.otp.encoding; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; /** * * @author scott.hasse@gmail.com * */ public class SimpleBase16Encoder implements TextEncoder { protected int majorChunkSize = 20; //the size in bytes of major chunks protected int minorChunkSize = 1; //the size in bytes of minor chunks protected String minorChunkSeparator = " "; protected String majorChunkSeparator = "\n"; /* * Sets how many bytes in each major chunk */ public void setMajorChunkSize(int majorChunkSize) { this.majorChunkSize = majorChunkSize; } public void setMinorChunkSize(int minorChunkSize) { this.minorChunkSize = minorChunkSize; } public void setMinorChunkSeparator(String minorChunkSeparator) { this.minorChunkSeparator = minorChunkSeparator; } public void setMajorChunkSeparator(String majorChunkSeparator) { this.majorChunkSeparator = majorChunkSeparator; } @Override public String encode(byte[] input) throws EncodingException { return getChunkedBase16(input); } @Override public byte[] decode(String input) throws EncodingException { byte[] result = null; input = cleanInput(input); try { result = Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw new IllegalArgumentException("The provided input is not valid base16.", e); } return result; } protected String cleanInput(String input) { input = input.replaceAll("[" + minorChunkSeparator + majorChunkSeparator + "]",""); return input; } protected String bytesToBase16(byte[] input) { char[] hex = Hex.encodeHex(input); String result = new String(hex); return result.toUpperCase(); } /* * */ protected String getChunkedBase16(byte[] data) { String base16 = bytesToBase16(data); StringBuffer result = new StringBuffer(); //For each byte in, there are two characters returned int base16StringMajorChunkSize = majorChunkSize * 2; int base16StringMinorChunkSize = minorChunkSize * 2; int ilength = base16.length(); for (int i = 0; i < ilength; i += base16StringMajorChunkSize) { String line = base16.substring(i, Math.min(ilength, i + base16StringMajorChunkSize)); int jlength = line.length(); for (int j = 0; j < jlength; j += base16StringMinorChunkSize) { result.append(line.substring(j, Math.min(jlength, j + base16StringMinorChunkSize))); if (j + base16StringMinorChunkSize < jlength) { result.append(minorChunkSeparator); } } result.append(majorChunkSeparator); } return result.toString(); } }
gpl-3.0
haqduong/spms
src/main/java/edu/hust/k54/persistence/Dienbienluong.java
1457
package edu.hust.k54.persistence; import java.util.Date; public class Dienbienluong implements java.io.Serializable { private Integer iddienbienluong; private Soyeulylich soyeulylich; private Hesoluong hesoluong; private Date tungay; private Date denngay; public Dienbienluong() { } public Dienbienluong(Soyeulylich soyeulylich, Hesoluong hesoluong) { this.soyeulylich = soyeulylich; this.hesoluong = hesoluong; } public Dienbienluong(Soyeulylich soyeulylich, Hesoluong hesoluong, Date tungay, Date denngay) { this.soyeulylich = soyeulylich; this.hesoluong = hesoluong; this.tungay = tungay; this.denngay = denngay; } public Integer getIddienbienluong() { return this.iddienbienluong; } public void setIddienbienluong(Integer iddienbienluong) { this.iddienbienluong = iddienbienluong; } public Soyeulylich getSoyeulylich() { return this.soyeulylich; } public void setSoyeulylich(Soyeulylich soyeulylich) { this.soyeulylich = soyeulylich; } public Hesoluong getHesoluong() { return this.hesoluong; } public void setHesoluong(Hesoluong hesoluong) { this.hesoluong = hesoluong; } public Date getTungay() { return this.tungay; } public void setTungay(Date tungay) { this.tungay = tungay; } public Date getDenngay() { return this.denngay; } public void setDenngay(Date denngay) { this.denngay = denngay; } }
gpl-3.0
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/data/xml/holder/OptionDataHolder.java
921
package l2s.gameserver.data.xml.holder; import l2s.commons.data.xml.AbstractHolder; import l2s.gameserver.templates.OptionDataTemplate; import org.napile.primitive.maps.IntObjectMap; import org.napile.primitive.maps.impl.HashIntObjectMap; /** * @author VISTALL * @date 20:35/19.05.2011 */ public final class OptionDataHolder extends AbstractHolder { private static final OptionDataHolder _instance = new OptionDataHolder(); private IntObjectMap<OptionDataTemplate> _templates = new HashIntObjectMap<OptionDataTemplate>(); public static OptionDataHolder getInstance() { return _instance; } public void addTemplate(OptionDataTemplate template) { _templates.put(template.getId(), template); } public OptionDataTemplate getTemplate(int id) { return _templates.get(id); } @Override public int size() { return _templates.size(); } @Override public void clear() { _templates.clear(); } }
gpl-3.0
clemensbartz/essential-launcher
launcher/src/main/java/de/clemensbartz/android/launcher/util/package-info.java
806
/* * Copyright (C) 2018 Clemens Bartz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Contains utility classes. * * @author Clemens Bartz */ package de.clemensbartz.android.launcher.util;
gpl-3.0
chggr/puzzles
hard/Dijkstra.java
8448
import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; // Task description: Given a map of cities and distances between them, implement // an algorithm to return the shortest path between two given cities. // // Solution: The implementation below uses Dijkstra's algorithm to find the // minimum distance from the start city to every other city in the graph. The // algorithm uses a min-heap as a processing queue and initially adds the // starting city into the queue. While the queue is not empty, we pick up and // process the first item. If the city we are processing has been encountered // before, it means that we have already visited it and thus can continue with // the next item in the queue. If this is the first time we visit the city, it // is guaranteed that the current route will be the shortest path, and this can // be added to the results. If V is the number of vertices (cities) and E is the // number of edges (paths) that connect two vertices, the runtime complexity of // this algorithm is O(V * logV + E * logV). It takes O(logN) time to pop() or // push() in the min-heap PriorityQueue. We need to do V pops and E pushes into // the min-heap. // // A related algorithm that can also be used to find the optimal path towards a // given target in a graph is A*. A* is an informed search or best-first search // algorithm, meaning that it solves the path-finding problem by searching among // all possible paths to the target and considers the ones that (1) incur the // smallest cost and (2) appear to lead more quickly to the target. It creates // a tree of paths with the starting node as root and iteratively expands the // most promising path until the target node is reached. At each iteration, A* // needs to determine which of the partial paths should be expanded. It does so // by minimizing the cost function f(n) = g(n) + h(n), where n is the last node // in each path, g(n) is the cost of the path from start to n and h(n) is a // heuristic that estimates the cost to reach the target node from n. For the // algorithm to find the shortest path, h(n) must be admissible, i.e. it should // never overestimate the actual cost to reach the target. Dijkstra's algorithm // is a special case of A* where no heuristic function is used (i.e. h(n) = 0). // For example, when searching for the shortest route on a map, h(n) could be // the straight-line distance to the goal. public class Dijkstra { // Path from one city to another and its distance. private static final class Path { private final String from; private final String to; private final double distance; public Path(String from, String to, double distance) { this.from = from; this.to = to; this.distance = distance; } public String getFrom() { return from; } public String getTo() { return to; } public double getDistance() { return distance; } } // A map of the area that contains paths between cities. private static final class AreaMap { private final Map<String, List<Path>> outbound = new HashMap<>(); public void addPath(Path path) { outbound.computeIfAbsent(path.getFrom(), (k) -> new ArrayList<>()); outbound.get(path.getFrom()).add(path); } public List<Path> getPathsFrom(String city) { outbound.computeIfAbsent(city, (k) -> new ArrayList<>()); return outbound.get(city); } } // A route between cities and the total distance travelled. private static final class Route implements Comparable<Route> { private final List<String> cities; private final double totalDistance; public Route(List<String> cities, double totalDistance) { this.cities = cities; this.totalDistance = totalDistance; } public List<String> getCities() { return cities; } public double getTotalDistance() { return totalDistance; } public String getLastCity() { return cities.get(cities.size() - 1); } public Route move(String city, double distance) { List<String> newCities = new ArrayList<>(); newCities.addAll(cities); newCities.add(city); double newDistance = totalDistance + distance; return new Route(newCities, newDistance); } public int compareTo(Route other) { double difference = this.totalDistance - other.totalDistance; return difference < 0 ? -1 : difference == 0 ? 0 : 1; } } private static Map<String, Route> optimalRoutes(String from, AreaMap area) { Map<String, Route> routes = new HashMap<>(); Queue<Route> processing = new PriorityQueue<>(); processing.add(new Route(asList(from), 0.0)); while(!processing.isEmpty()) { Route route = processing.poll(); String currentCity = route.getLastCity(); if (routes.containsKey(currentCity)) continue; routes.put(currentCity, route); for (Path path : area.getPathsFrom(route.getLastCity())) { processing.add(route.move(path.getTo(), path.getDistance())); } } return routes; } private static final AreaMap UK = new AreaMap(); static { UK.addPath(new Path("London", "Liverpool", 212)); UK.addPath(new Path("London", "Manchester", 200)); UK.addPath(new Path("Manchester", "Liverpool", 34)); UK.addPath(new Path("Manchester", "Leeds", 44)); UK.addPath(new Path("Leeds", "Sheffield", 36)); UK.addPath(new Path("Manchester", "Sheffield", 37)); UK.addPath(new Path("London", "Birmingham", 126)); UK.addPath(new Path("Birmingham", "Liverpool", 99)); UK.addPath(new Path("Birmingham", "Cardiff", 118)); UK.addPath(new Path("Oxford", "Cardiff", 106)); UK.addPath(new Path("London", "Oxford", 59)); } private static boolean equal(Route route, double distance, String... cities) { if (route == null) return false; if (route.getTotalDistance() != distance) return false; List<String> routeCities = route.getCities(); if (routeCities.size() != cities.length) return false; for (int i = 0; i < cities.length; i++) { if (!cities[i].equals(routeCities.get(i))) return false; } return true; } private static boolean testEmptyArea() { Map<String, Route> routes = optimalRoutes("London", new AreaMap()); return 1 == routes.size() && equal(routes.get("London"), 0.0, "London"); } private static boolean testNoRoutes() { Map<String, Route> routes = optimalRoutes("Cardiff", UK); return 1 == routes.size() && equal(routes.get("Cardiff"), 0.0, "Cardiff"); } private static boolean testRoutes() { Map<String, Route> routes = optimalRoutes("London", UK); return 8 == routes.size() && equal(routes.get("London"), 0.0, "London") && equal(routes.get("Liverpool"), 212.0, "London", "Liverpool") && equal(routes.get("Cardiff"), 165.0, "London", "Oxford", "Cardiff") && equal(routes.get("Leeds"), 244.0, "London", "Manchester", "Leeds") && equal(routes.get("Manchester"), 200.0, "London", "Manchester") && equal(routes.get("Sheffield"), 237.0, "London", "Manchester", "Sheffield") && equal(routes.get("Oxford"), 59.0, "London", "Oxford") && equal(routes.get("Birmingham"), 126.0, "London", "Birmingham"); } public static void main(String[] args) { int counter = 0; if (!testEmptyArea()) { System.out.println("Empty area test failed!"); counter++; } if (!testNoRoutes()) { System.out.println("No routes test failed!"); counter++; } if (!testRoutes()) { System.out.println("Routes test failed!"); counter++; } System.out.println(counter + " tests failed."); } }
gpl-3.0
nurv/lirec
libs/ion/Meta/src/ion/Meta/Event.java
2294
/* ION Framework - Synchronized Collections Unit Test Classes Copyright(C) 2009 GAIPS / INESC-ID Lisboa This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Authors: Pedro Cuba, Marco Vala, Guilherme Raimundo, Rui Prada, Carlos Martinho Revision History: --- 09/04/2009 Pedro Cuba <pedro.cuba@tagus.ist.utl.pt> First version. --- */ package ion.Meta; import java.util.HashSet; public abstract class Event implements IEvent { private SimulationTime raiseTime; private HashSet<Element> targets = new HashSet<Element>(); private final Class<?> type; private Event baseEvent; private HashSet<Element> trail; public Event() { this.type = this.getClass(); this.baseEvent = null; } public SimulationTime getRaiseTime() { if (this.baseEvent == null) { return this.raiseTime.duplicate(); } else { return this.baseEvent.raiseTime.duplicate(); } } void setRaiseTime(SimulationTime raiseTime) { if (this.baseEvent == null && this.raiseTime == null) { this.raiseTime = raiseTime.duplicate(); } } Iterable<Class<?>> getTypes() { return TypeCache.instance.getParents(this.type); } HashSet<Element> getTrail() { if (this.baseEvent == null) { if (this.trail == null) { this.trail = new HashSet<Element>(); } return this.trail; } else { return this.baseEvent.trail; } } HashSet<Element> getTargets() { return this.targets; } }
gpl-3.0
prajapati-parth/quick-ping
android/app/src/main/java/com/quickping/MainApplication.java
957
package com.quickping; import android.app.Application; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
gpl-3.0
bmatern-nmdp/MiringValidator
src/main/java/org/nmdp/miring/MiringValidator.java
3994
/* MiringValidator Semantic Validator for MIRING compliant HML Copyright (c) 2015 National Marrow Donor Program (NMDP) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. > http://www.gnu.org/licenses/lgpl.html */ package org.nmdp.miring; import java.util.HashMap; import org.nmdp.miring.ValidationResult.Severity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used to validate an XML file against a MIRING checklist. Both tier 1 and tier 2 are included in the validation. */ public class MiringValidator { Logger logger = LoggerFactory.getLogger(MiringValidator.class); String xml; String report; ValidationResult[] tier1ValidationErrors; ValidationResult[] tier2ValidationErrors; Sample[] sampleIDs; /** * Constructor for a MiringValidator object * * @param xml a String containing the xml text */ public MiringValidator(String xml) { this.xml = xml; this.report = null; } /** * Validate the xml text against MIRING checklist. This method performs validation for both Tiers 1 and 2. * * @return a String containing MIRING Results Report */ public String validate() { if(xml==null || xml.length() == 0) { logger.error("XML is null or length 0."); return ReportGenerator.generateReport(new ValidationResult[]{new ValidationResult("XML is null or length 0.",Severity.FATAL)}, null, null,null,null); } HashMap<String,String> properties = Utilities.getPropertiesFromRootHml(xml); //Tier 1 logger.debug("Attempting Tier 1 Validation"); tier1ValidationErrors = SchemaValidator.validate(xml, "/org/nmdp/miring/schema/MiringTier1.xsd"); sampleIDs = SchemaValidator.samples.toArray(new Sample[SchemaValidator.samples.size()]); //Tier 2 //If tier 1 has fatal errors, we should not continue to tier 2. //Actually no. We should just do the tier 2, there are probably good info in there. //I don't want to miss out on the T2 errors, they are valuable. //if(!Utilities.hasFatalErrors(tier1ValidationErrors)) { logger.debug("Attempting Tier 2 validation"); tier2ValidationErrors = SchematronValidator.validate(xml, new String[] {"/org/nmdp/miring/schematron/MiringAll.sch"}); //Tier 3 is outside scope for now. Okay. /*if(!Utilities.hasFatalErrors(tier2ValidationErrors))) { //tier3(); }*/ } //else //{ // logger.error("Did not perform tier 2 validation, fatal errors in tier 1."); //} //Make a report. String hmlIdRoot = Utilities.getHMLIDRoot(xml); String hmlIdExt = Utilities.getHMLIDExtension(xml); report = ReportGenerator.generateReport(Utilities.combineArrays(tier1ValidationErrors, tier2ValidationErrors), hmlIdRoot, hmlIdExt, properties, sampleIDs); return report; } public String getXml() { return xml; } public void setXml(String xml) { this.xml = xml; } public String getReport() { return report; } }
gpl-3.0
marvin-we/steem-java-api-wrapper
core/src/main/java/eu/bittrade/libs/steemj/protocol/operations/DelegateVestingSharesOperation.java
8182
/* * This file is part of SteemJ (formerly known as 'Steem-Java-Api-Wrapper') * * SteemJ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SteemJ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SteemJ. If not, see <http://www.gnu.org/licenses/>. */ package eu.bittrade.libs.steemj.protocol.operations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.InvalidParameterException; import java.util.List; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import eu.bittrade.libs.steemj.configuration.SteemJConfig; import eu.bittrade.libs.steemj.enums.OperationType; import eu.bittrade.libs.steemj.enums.PrivateKeyType; import eu.bittrade.libs.steemj.enums.ValidationType; import eu.bittrade.libs.steemj.exceptions.SteemInvalidTransactionException; import eu.bittrade.libs.steemj.interfaces.SignatureObject; import eu.bittrade.libs.steemj.protocol.AccountName; import eu.bittrade.libs.steemj.protocol.LegacyAsset; import eu.bittrade.libs.steemj.util.SteemJUtils; /** * This class represents the Steem "delegate_vesting_shares_operation" object. * * @author <a href="http://steemit.com/@dez1337">dez1337</a> */ public class DelegateVestingSharesOperation extends Operation { @JsonProperty("delegator") private AccountName delegator; @JsonProperty("delegatee") private AccountName delegatee; @JsonProperty("vesting_shares") private LegacyAsset vestingShares; /** * Create a new delegate vesting shares operation. * * Delegate vesting shares from one account to the other. The vesting shares * are still owned by the original account, but content voting rights and * bandwidth allocation are transferred to the receiving account. This sets * the delegation to `vesting_shares`, increasing it or decreasing it as * needed. (i.e. a delegation of 0 removes the delegation) * * When a delegation is removed the shares are placed in limbo for a week to * prevent a satoshi of VESTS from voting on the same content twice. * * @param delegator * The account that delegates the <code>vestingShares</code> (see * {@link #setDelegator(AccountName)}). * @param delegatee * The account to send the <code>vestingShares</code> to (see * {@link #setDelegatee(AccountName)}). * @param vestingShares * The amount to deletage (see * {@link #setVestingShares(LegacyAsset)}). * @throws InvalidParameterException * If one of the arguments does not fulfill the requirements. */ @JsonCreator public DelegateVestingSharesOperation(@JsonProperty("delegator") AccountName delegator, @JsonProperty("delegatee") AccountName delegatee, @JsonProperty("vesting_shares") LegacyAsset vestingShares) { super(false); this.setDelegator(delegator); this.setDelegatee(delegatee); this.setVestingShares(vestingShares); } /** * Get the account name of the account who delegated the vesting shares. * * @return The account name of the delegator. */ public AccountName getDelegator() { return delegator; } /** * Set the account name of the account who delegated the vesting shares. * <b>Notice:</b> The private active key of this account needs to be stored * in the key storage. * * @param delegator * The account name of the delegator. * @throws InvalidParameterException * If the <code>delegator</code> account is null or equal to the * {@link #getDelegatee()} account. */ public void setDelegator(AccountName delegator) { this.delegator = SteemJUtils.setIfNotNull(delegator, "The delegatee account can't be null."); } /** * Get the account name of the account which received the vesting shares. * * @return The account name of the delegatee. */ public AccountName getDelegatee() { return delegatee; } /** * Set the account name of the account which received the vesting shares. * * @param delegatee * The account name of the delegatee. * @throws InvalidParameterException * If the <code>delegatee</code> account is null or equal to the * {@link #getDelegator()} account. */ public void setDelegatee(AccountName delegatee) { this.delegatee = SteemJUtils.setIfNotNull(delegatee, "The delegatee account can't be null."); } /** * Get the amount of vesting shares delegated. * * @return The amount of vesting shares delegated. */ public LegacyAsset getVestingShares() { return vestingShares; } /** * Set the amount of vesting shares delegated. * * @param vestingShares * The amount of vesting shares delegated. * @throws InvalidParameterException * If the provided <code>vestingShares</code> is null, the asset * symbol is not VESTS or the amount is negative. */ public void setVestingShares(LegacyAsset vestingShares) { this.vestingShares = SteemJUtils.setIfNotNull(vestingShares, "The vesting shares to delegate can't be null."); } @Override public byte[] toByteArray() throws SteemInvalidTransactionException { try (ByteArrayOutputStream serializedDelegateVestingSharesOperation = new ByteArrayOutputStream()) { serializedDelegateVestingSharesOperation.write(SteemJUtils .transformIntToVarIntByteArray(OperationType.DELEGATE_VESTING_SHARES_OPERATION.getOrderId())); serializedDelegateVestingSharesOperation.write(this.getDelegator().toByteArray()); serializedDelegateVestingSharesOperation.write(this.getDelegatee().toByteArray()); serializedDelegateVestingSharesOperation.write(this.getVestingShares().toByteArray()); return serializedDelegateVestingSharesOperation.toByteArray(); } catch (IOException e) { throw new SteemInvalidTransactionException( "A problem occured while transforming the operation into a byte array.", e); } } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public Map<SignatureObject, PrivateKeyType> getRequiredAuthorities( Map<SignatureObject, PrivateKeyType> requiredAuthoritiesBase) { return mergeRequiredAuthorities(requiredAuthoritiesBase, this.getDelegator(), PrivateKeyType.ACTIVE); } @Override public void validate(List<ValidationType> validationsToSkip) { if (!validationsToSkip.contains(ValidationType.SKIP_VALIDATION)) { if (!validationsToSkip.contains(ValidationType.SKIP_ASSET_VALIDATION)) { if (!vestingShares.getSymbol().equals(SteemJConfig.getInstance().getVestsSymbol())) { throw new InvalidParameterException("Can only delegate VESTS."); } else if (vestingShares.getAmount() <= 0) { throw new InvalidParameterException("Can't delegate a negative amount of VESTS."); } } if (this.getDelegator().equals(this.getDelegatee())) { throw new InvalidParameterException("The delegatee account can't be equal to the delegator account."); } } } }
gpl-3.0
v12technology/fluxtion-examples
reference-utils/src/main/java/com/fluxtion/learning/utils/diamond/generated/GreaterThanDecorator_1.java
1445
package com.fluxtion.learning.utils.diamond.generated; import com.fluxtion.api.annotations.Initialise; import com.fluxtion.api.annotations.OnEvent; import com.fluxtion.extension.declarative.api.Wrapper; import com.fluxtion.runtime.plugin.events.NumericSignal; import com.fluxtion.learning.utils.diamond.generated.NumericSignalHandler; /** * generated Test wrapper. * * target class : com.fluxtion.extension.declarative.funclib.api.filter.BinaryPredicates.GreaterThan * target method : isGreaterThan * * @author Greg Higgins */ public class GreaterThanDecorator_1 implements Wrapper<NumericSignal>{ //source operand inputs public NumericSignalHandler filterSubject; public com.fluxtion.learning.utils.diamond.generated.NumericSignalHandler source_NumericSignalHandler_0; private com.fluxtion.extension.declarative.funclib.api.filter.BinaryPredicates.GreaterThan f; @Initialise public void init(){ f = new com.fluxtion.extension.declarative.funclib.api.filter.BinaryPredicates.GreaterThan(); } @OnEvent public boolean onEvent(){ return f.isGreaterThan((double)((com.fluxtion.runtime.plugin.events.NumericSignal)source_NumericSignalHandler_0.event()).value(), (double)5.0); } @Override public NumericSignal event() { return filterSubject.event(); } @Override public Class<NumericSignal> eventClass() { return NumericSignal.class; } }
gpl-3.0
idega/org.jboss.jbpm
src/java/com/idega/jbpm/bundle/ProcessBundleManager.java
4397
package com.idega.jbpm.bundle; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.jbpm.JbpmContext; import org.jbpm.JbpmException; import org.jbpm.graph.def.ProcessDefinition; import org.jbpm.taskmgmt.def.Task; import org.jbpm.taskmgmt.def.TaskMgmtDefinition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.idega.idegaweb.IWMainApplication; import com.idega.jbpm.BPMContext; import com.idega.jbpm.JbpmCallback; import com.idega.jbpm.data.ProcessManagerBind; import com.idega.jbpm.data.dao.BPMDAO; import com.idega.jbpm.exe.BPMFactory; import com.idega.jbpm.view.ViewResource; import com.idega.jbpm.view.ViewToTask; import com.idega.util.StringUtil; /** * @author <a href="mailto:civilis@idega.com">Vytautas Čivilis</a> * @version $Revision: 1.18 $ Last modified: $Date: 2009/02/26 08:55:03 $ by $Author: civilis $ */ @Scope("prototype") @Service @Transactional public class ProcessBundleManager { @Autowired private BPMDAO bpmBindsDAO; @Autowired private BPMContext idegaJbpmContext; @Autowired private BPMFactory bpmFactory; @Autowired private ViewToTask viewToTask; /** * @param processBundle * bundle to create process bundle from. i.e. all the resources, like process * definition and views * @param processDefinitionName * - optional * @return process definition id, of the created bundle * @throws IOException */ public long createBundle(final ProcessBundle processBundle, final IWMainApplication iwma) throws IOException { final String processManagerType = processBundle.getProcessManagerType(); if (StringUtil.isEmpty(processManagerType)) throw new IllegalArgumentException("No process mmanager type in process bundle provided: " + processBundle.getClass().getName()); Long processDefinitionId = getBPMContext().execute(new JbpmCallback() { public Object doInJbpm(JbpmContext context) throws JbpmException { ProcessDefinition pd = null; try { pd = processBundle.getProcessDefinition(); context.getGraphSession().deployProcessDefinition(pd); TaskMgmtDefinition taskMgmtDef = pd.getTaskMgmtDefinition(); @SuppressWarnings("unchecked") Map<String, Task> tasksMap = taskMgmtDef.getTasks(); final String processName = pd.getName(); if (tasksMap != null) { @SuppressWarnings("unchecked") Collection<Task> tasks = pd.getTaskMgmtDefinition().getTasks().values(); for (Task task : tasks) { List<ViewResource> viewResources = processBundle.getViewResources(task.getName()); if (viewResources != null) { for (ViewResource viewResource : viewResources) { viewResource.setProcessName(processName); viewResource.store(iwma); getViewToTask().bind(viewResource.getViewId(), viewResource.getViewType(), task, viewResource.getOrder()); } } else { Logger.getLogger(getClass().getName()).log(Level.WARNING, "No view resources resolved for task: " + task.getId()); } } } if (getBPMDAO().getProcessManagerBind(processName) == null) { ProcessManagerBind pmb = new ProcessManagerBind(); pmb.setManagersType(processManagerType); pmb.setProcessName(processName); getBPMDAO().persist(pmb); } processBundle.configure(pd); return pd.getId(); } catch (IOException e) { throw new RuntimeException(e); } catch (Exception e) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Exception while storing views and binding with tasks", e); // TODO: rollback here if hibernate doesn't do it? throw new RuntimeException(e); } } }); // TODO: catch RuntimeException with cause of IOException (perhaps make // some wrapper), and throw the original IOException here return processDefinitionId; } BPMContext getBPMContext() { return idegaJbpmContext; } BPMDAO getBPMDAO() { return bpmBindsDAO; } ViewToTask getViewToTask() { return viewToTask; } BPMFactory getBpmFactory() { return bpmFactory; } }
gpl-3.0
erichsueh/CMPUT301F16T03-D01
app/src/main/java/com/example/ehsueh/appygolucky/MapSearchActivity.java
10636
package com.example.ehsueh.appygolucky; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment; import com.google.android.gms.location.places.ui.PlaceSelectionListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import java.io.IOException; import java.text.DecimalFormat; import java.util.List; import java.util.Scanner; //This activity will return a latlng object based on what point the user //picked on. public class MapSearchActivity extends AppCompatActivity implements OnMapReadyCallback { private GoogleMap mMap; private UiSettings mUiSettings; private Marker currentMarker; private Context context; private UserController uc; //set up googlemap @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_search); uc = new UserController(getApplicationContext()); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); context = this; } /** * Set up all the listener for buttons and map markers */ private void setButtonListeners(){ final Button setLocation = (Button)findViewById(R.id.setLocationButton); final PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.search_place_fragment); autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { LatLng location = place.getLatLng(); if(currentMarker != null){ currentMarker.remove(); } //this will move the camera to the start point mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,12)); currentMarker = mMap.addMarker(new MarkerOptions() .position(location) .title(place.getAddress().toString()) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); currentMarker.showInfoWindow(); } @Override public void onError(Status status) { AlertDialog markerWarning = new AlertDialog.Builder(context).create(); markerWarning.setMessage("Something went wrong in trying to search address."); markerWarning.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); markerWarning.show(); } }); //this is the button for pass back the latlng object setLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Do not want to spawn a warning if the end marker is not null if (currentMarker == null) { AlertDialog markerWarning = new AlertDialog.Builder(context).create(); markerWarning.setMessage(getString(R.string.select_place)); markerWarning.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); markerWarning.show(); } //this is when we know user is set on this marker, and it returns //the location of it. else { LatLng search_location = currentMarker.getPosition(); Intent resultIntent = new Intent(); resultIntent.putExtra("search",search_location); setResult(Activity.RESULT_OK,resultIntent); finish(); } } }); //Listener for the map so we know when the user clicks mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng latLng) { if (currentMarker == null) { currentMarker = mMap.addMarker(new MarkerOptions() .position(latLng) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))); currentMarker.setTitle(latLng.toString()); currentMarker.showInfoWindow(); //check if phone have connection if (isNetworkAvailable()) { try { Geocoder geoCoder = new Geocoder(context); List<Address> matches = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); String address = ""; if (!matches.isEmpty()) { address = matches.get(0).getAddressLine(0) + ' ' + matches.get(0).getLocality(); } currentMarker.setTitle(address); currentMarker.showInfoWindow(); } catch (IOException e) { e.printStackTrace(); } } } else if (currentMarker != null) { currentMarker.remove(); currentMarker = mMap.addMarker(new MarkerOptions() .position(latLng) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))); currentMarker.setTitle(latLng.toString()); currentMarker.showInfoWindow(); if (isNetworkAvailable()) { try { Geocoder geoCoder = new Geocoder(context); List<Address> matches = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); String address = ""; if (!matches.isEmpty()) { address = matches.get(0).getAddressLine(0) + ' ' + matches.get(0).getLocality(); } currentMarker.setTitle(address); currentMarker.showInfoWindow(); } catch (IOException e) { e.printStackTrace(); } } } } }); } /** * When the map is initialized this is called by default */ public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mUiSettings = mMap.getUiSettings(); //Set the initial spot to edmonton for now LatLng edmonton = new LatLng(53.5444, -113.4909); mMap.animateCamera(CameraUpdateFactory.zoomIn()); mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); mUiSettings.setZoomControlsEnabled(true); mUiSettings.setCompassEnabled(true); mUiSettings.setTiltGesturesEnabled(true); mMap.getUiSettings().setMapToolbarEnabled(false); CameraPosition cameraPosition = new CameraPosition.Builder() .target(edmonton) // Sets the center of the map to location user .zoom(10) .bearing(0) .tilt(0) .build(); ensureLocationPermissions(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); setButtonListeners(); } /** * A quick permission check to ensure that we location services enabled */ private void ensureLocationPermissions(){ //Check if we have the right permissions to use location Boolean i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; if (i) { mMap.setMyLocationEnabled(true); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0); mMap.setMyLocationEnabled(true); } } //this is a method to check if network is available, it returns true if there is internet, false otherwise public boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
gpl-3.0
rejmar/Java
Concurrency/Challenge/src/pl/marjusz/BankAccount.java
2692
package pl.marjusz; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class BankAccount { private double balance; private String accountNumber; private Lock lock; public BankAccount(double balance, String accountNumber) { this.balance = balance; this.accountNumber = accountNumber; this.lock = new ReentrantLock(); } public String getAccountNumber() { return accountNumber; } public void printAccountNumber(){ System.out.println(accountNumber); } // public synchronized void deposit(double amount){ // balance += amount; // System.out.println("You have deposited " + amount + ". Now your balance is: " + balance); // } // // public synchronized void withdraw(double amount){ // balance -= amount; // System.out.println("You have withdraw " + amount + ". Now your balance is: " + balance); // } public boolean withdraw(double amount) { try{ if (lock.tryLock(50,TimeUnit.MILLISECONDS)) { try { // Simulate database access Thread.sleep(100); } catch (InterruptedException e) { } balance -= amount; System.out.printf("%s: Withdrew %f\n", Thread.currentThread().getName(), amount); return true; } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return false; } public boolean deposit(double amount) { try{ if (lock.tryLock(50,TimeUnit.MILLISECONDS)) { try { // Simulate database access Thread.sleep(100); } catch (InterruptedException e) { } balance += amount; System.out.printf("%s: Deposited %f\n", Thread.currentThread().getName(), amount); return true; }} catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } return false; } public boolean transfer(BankAccount destinationAccount, double amount) { if (withdraw(amount)) { if (destinationAccount.deposit(amount)) { return true; } else { System.out.printf("%s: Destination account busy. Refunding money\n", Thread.currentThread().getName()); deposit(amount); } } return false; } }
gpl-3.0
redfish64/TinyTravelTracker
app/src/main/java/com/rareventure/gps2/GpsTrailerService.java
19452
/** Copyright 2015 Tim Engler, Rareventure LLC This file is part of Tiny Travel Tracker. Tiny Travel Tracker is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Tiny Travel Tracker is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Tiny Travel Tracker. If not, see <http://www.gnu.org/licenses/>. */ package com.rareventure.gps2; import org.acra.ACRA; import org.acra.ErrorReporter; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.LocationManager; import android.os.BatteryManager; import android.os.Binder; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.RemoteCallbackList; import android.provider.Settings; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import com.rareventure.gps2.GTG.Requirement; import com.rareventure.gps2.IGpsTrailerService; import com.rareventure.gps2.IGpsTrailerServiceCallback; import com.rareventure.gps2.R; import com.rareventure.android.AndroidPreferenceSet; import com.rareventure.android.Util; import com.rareventure.android.database.DbDatastoreAccessor; import com.rareventure.gps2.GTG.GTGEvent; import com.rareventure.gps2.GTG.GTGEventListener; import com.rareventure.gps2.GTG.SetupState; import com.rareventure.gps2.bootup.GpsTrailerReceiver; import com.rareventure.gps2.database.GpsLocationCache; import com.rareventure.gps2.database.GpsLocationRow; import com.rareventure.gps2.database.TAssert; import com.rareventure.gps2.reviewer.SettingsActivity; import com.rareventure.gps2.reviewer.wizard.WelcomePage; import com.rareventure.util.DebugLogFile; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import pl.tajchert.nammu.Nammu; public class GpsTrailerService extends Service { public static final String TAG = "GpsTrailerService"; final RemoteCallbackList<IGpsTrailerServiceCallback> mCallbacks = new RemoteCallbackList<IGpsTrailerServiceCallback>(); /** * The IRemoteInterface is defined through IDL */ private final IGpsTrailerService.Stub mBinder = new IGpsTrailerService.Stub() { public void registerCallback(IGpsTrailerServiceCallback cb) { if (cb != null) mCallbacks.register(cb); } public void unregisterCallback(IGpsTrailerServiceCallback cb) { if (cb != null) mCallbacks.unregister(cb); } }; private Handler mHandler; public class LocalBinder extends Binder { // private static final String DESCRIPTOR = "com.rareventure.tapmusic.ITapServiceCallback"; public LocalBinder() { // this.attachInterface(this, DESCRIPTOR); } GpsTrailerService getService() { return GpsTrailerService.this; } } private GpsTrailerManager gpsManager; private BroadcastReceiver batteryReceiver; @Override public int onStartCommand(Intent intent, int flags, int startId) { /* ttt_installer:remove_line */Log.d(GTG.TAG, "Starting on intent " + intent); //if we were already running and had a gpsManager, notify that we woke up if (gpsManager != null) gpsManager.notifyWoken(); mHandler = new Handler(); GTG.service = this; //we want our service to restart if stopped because of memory constraints or whatever else return Service.START_STICKY; } public GTGEventListener gtgEventListener = new GTGEventListener() { @Override public boolean onGTGEvent(GTGEvent event) { // Log.d(GpsTrailerService.TAG,"onGTGEvent: "+event); //note the we return true, in the if statements below, indicating we // handled the error events and //to shut them off, so that when we restart, we will check again. //(we share our process with GpsTrailer, so, even if //we stop self, the event would still be turned on otherwise.) if (event == GTGEvent.ERROR_GPS_DISABLED) { updateNotification(FLAG_GPS_ENABLED, false); stopSelf(); return true; } if (event == GTGEvent.ERROR_GPS_NO_PERMISSION) { updateNotification(FLAG_ERROR_NO_GPS_PERMISSION, true); updateNotification(FLAG_GPS_ENABLED, false); stopSelf(); return true; } if (event == GTGEvent.ERROR_SDCARD_NOT_MOUNTED) { updateNotification(FLAG_ERROR_SDCARD_NOT_MOUNTED, true); stopSelf(); return true; } else if (event == GTGEvent.ERROR_LOW_FREE_SPACE) { updateNotification(FLAG_ERROR_LOW_FREE_SPACE, true); stopSelf(); return true; } else if (event == GTGEvent.ERROR_SERVICE_INTERNAL_ERROR) { updateNotification(FLAG_ERROR_INTERNAL, true); stopSelf(); return true; } else if (event == GTGEvent.ERROR_LOW_BATTERY) { updateNotification(FLAG_BATTERY_LOW, true); stopSelf(); return true; } else if (event == GTGEvent.TRIAL_PERIOD_EXPIRED) { updateNotification(FLAG_TRIAL_EXPIRED, true); stopSelf(); return true; } else if (event == GTGEvent.DOING_RESTORE) { updateNotification(FLAG_IN_RESTORE, true); stopSelf(); return true; } else if (event == GTGEvent.ERROR_UNLICENSED) { //co: we initially don't want to do anything if the user is unlicensed, // just find out how much piracy is a problem // we don't show a notification if we quit due to the app being unlicensed // stopSelf(); } return false; } @Override public void offGTGEvent(GTGEvent event) { if (event == GTGEvent.ERROR_GPS_DISABLED) { updateNotification(FLAG_GPS_ENABLED, true); } } }; private static final int FLAG_GPS_ENABLED = 1; private static final int FLAG_BATTERY_LOW = 2; private static final int FLAG_FINISHED_STARTUP = 4; private static final int FLAG_ERROR_INTERNAL = 8; private static final int FLAG_ERROR_SDCARD_NOT_MOUNTED = 16; private static final int FLAG_ERROR_LOW_FREE_SPACE = 32; private static final int FLAG_COLLECT_ENABLED = 64; private static final int FLAG_ERROR_DB_PROBLEM = 128; private static final int FLAG_TRIAL_EXPIRED = 256; private static final int FLAG_IN_RESTORE = 512; private static final int FLAG_ERROR_NO_GPS_PERMISSION= 1024; private int notificationFlags = 0; private static class NotificationSetting { int iconId; int msgId; boolean sticky; int onFlags, offFlags; Intent intent; boolean isOngoing; public NotificationSetting(int iconId, int msgId, boolean sticky, int onFlags, int offFlags, Intent intent, boolean isOngoing) { super(); this.iconId = iconId; this.msgId = msgId; this.sticky = sticky; this.onFlags = onFlags; this.offFlags = offFlags; this.intent = intent; this.isOngoing = isOngoing; } /** * @return true if all of the this.onFlags are on and all of the this.offFlags are off */ public boolean matches(int notificationFlags) { return ((onFlags & notificationFlags) == onFlags) && ((Integer.MAX_VALUE - offFlags) | notificationFlags) == (Integer.MAX_VALUE - offFlags); } @Override public String toString() { return "NotificationSetting [iconId=" + iconId + ", msgId=" + msgId + ", sticky=" + sticky + ", onFlags=" + onFlags + ", offFlags=" + offFlags + "]"; } } /** * Note, ordered by priority */ public static NotificationSetting[] NOTIFICATIONS = new NotificationSetting[] { //note, in the following, if FLAG_COLLECT_ENABLED is *off*, we //shut off the notification icon new NotificationSetting(-1, -1, false, 0, FLAG_COLLECT_ENABLED, null, false), new NotificationSetting(-1, -1, false, FLAG_IN_RESTORE, 0, null, false), new NotificationSetting(-1, -1, false, FLAG_TRIAL_EXPIRED, 0, null, false), new NotificationSetting(R.drawable.red_error, R.string.service_error_internal_error, true, FLAG_ERROR_INTERNAL, 0, null, false), new NotificationSetting(R.drawable.red_error, R.string.service_error_sdcard_not_mounted, true, FLAG_ERROR_SDCARD_NOT_MOUNTED, 0, null, false), new NotificationSetting(R.drawable.red_error, R.string.service_error_db_problem, true, FLAG_ERROR_DB_PROBLEM, 0, null, false), new NotificationSetting(R.drawable.red_error, R.string.service_error_low_free_space, true, FLAG_ERROR_LOW_FREE_SPACE, 0, null, false), new NotificationSetting(-1, -1, false, FLAG_BATTERY_LOW, 0, null, false), new NotificationSetting(R.drawable.red_error, R.string.service_gps_must_grant_permission, true, FLAG_ERROR_NO_GPS_PERMISSION, 0,null , true), new NotificationSetting(R.drawable.red_error, R.string.service_gps_not_enabled, true, 0, FLAG_GPS_ENABLED, new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS) , true), new NotificationSetting(R.drawable.green, R.string.service_active, false, FLAG_GPS_ENABLED | FLAG_FINISHED_STARTUP | FLAG_COLLECT_ENABLED, 0, null, true) }; private NotificationSetting currentNotificationSetting = null; /** * Updates the notification based on the current status of the system */ private void updateNotification(int flags, boolean isOn) { if (isOn) notificationFlags |= flags; else notificationFlags &= (Integer.MAX_VALUE ^ flags); NotificationSetting oldNotSetting = currentNotificationSetting; //choose first matching notification setting for (NotificationSetting ns : NOTIFICATIONS) { if (ns.matches(notificationFlags)) { currentNotificationSetting = ns; break; } } /* ttt_installer:remove_line */Log.d(GpsTrailerService.TAG, "Flags is " + notificationFlags + ", current notset is " + currentNotificationSetting); if (currentNotificationSetting != oldNotSetting) { showCurrentNotification(); } } @Override public void onCreate() { Log.d(TAG, "GPS Service Startup"); //android.os.Debug.waitForDebugger(); //FODO 1 IXME DISABLE! Nammu.init(this); //reset all flags notificationFlags = 0; updateNotification(FLAG_GPS_ENABLED, true); GTG.addGTGEventListener(gtgEventListener); //read isCollectData first from shared prefs and if its false, quit immediately //we don't want to notify the user that we ran for any reason if this is false // (for example the db was corrupted) GTG.prefSet.loadAndroidPreferencesFromSharedPrefs(this); //co: we initially don't want to do anything if the user is unlicensed, // just find out how much piracy is a problem if (!GTG.prefs.isCollectData ) //|| GTGEvent.ERROR_UNLICENSED.isOn) { turnOffNotification(); stopSelf(); return; } GTG.initRwtm.registerWritingThread(); try { try { GTG.requireInitialSetup(this, true); GTG.requirePrefsLoaded(this); if(!GTG.requireNotInRestore()) { updateNotification(FLAG_IN_RESTORE, true); stopSelf(); return; } Intent i = GTG.requireNotTrialWhenPremiumIsAvailable(this); if (i != null) { turnOffNotification(); stopSelf(); return; } if (!GTG.requireNotTrialExpired()) { updateNotification(FLAG_TRIAL_EXPIRED, true); stopSelf(); return; } if (!GTG.requireSdcardPresent(this)) { updateNotification(FLAG_ERROR_SDCARD_NOT_MOUNTED, true); stopSelf(); return; } if (!GTG.requireSystemInstalled(this)) { stopSelf(); return; } if (GTG.requireDbReady() != GTG.REQUIRE_DB_READY_OK) { updateNotification(FLAG_ERROR_DB_PROBLEM, true); stopSelf(); return; } GTG.requireEncrypt(); } finally { GTG.initRwtm.unregisterWritingThread(); } updateNotification(FLAG_COLLECT_ENABLED, true); //co because we don't want gps2data files in the root directory of sdcard. they take up too much space // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // File dataFile = new File(Environment.getExternalStorageDirectory(), "gps2data"+sdf.format(new Date())+".txt"); File dataFile = null; gpsManager = new GpsTrailerManager(dataFile, this, TAG, this.getMainLooper()); // gpsManager = new GpsTrailerManager(null, this, TAG, // this.getMainLooper()); //note that there is no way to receive the current status of the battery //However, the battery receiver will get a notification as soon as its registered // to the current status of the battery batteryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { float batteryLeft = ((float) intent.getIntExtra( BatteryManager.EXTRA_LEVEL, -1)) / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); /* ttt_installer:remove_line */Log.d(GTG.TAG, "Received battery info, batteryLeft: "+ batteryLeft); int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN); if (batteryLeft < GTG.prefs.minBatteryPerc && (status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_UNKNOWN)) { updateNotification(FLAG_BATTERY_LOW, true); GTG.alert(GTGEvent.ERROR_LOW_BATTERY); } else updateNotification(FLAG_BATTERY_LOW, false); //we wait until now to finish startup //because otherwise if the battery is low //and we are awoken for some other event, we would otherwise show our icon for //a brief period before we get the battery is low event updateNotification(FLAG_FINISHED_STARTUP, true); //just a hack, a reasonable place to check if the trial version has expired checkTrialExpired(); } }; IntentFilter batteryLevelFilter = new IntentFilter( Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryReceiver, batteryLevelFilter); gpsManager.start(); //hack to try and keep our service from shutting down and never restarting JobScheduler jobScheduler = (JobScheduler)getApplicationContext() .getSystemService(JOB_SCHEDULER_SERVICE); ComponentName componentName = new ComponentName(this, JobSchedulerRestarterService.class); JobInfo jobInfoObj = new JobInfo.Builder(1, componentName) .setPeriodic(600*1000).setPersisted(true).build(); jobScheduler.schedule(jobInfoObj); } catch (Exception e) { shutdownWithException(e); ACRA.getErrorReporter().handleException(e); } } private boolean checkTrialExpired() { if (GTG.calcDaysBeforeTrialExpired() == 0) { Requirement.NOT_TRIAL_EXPIRED.reset(); //this will stop self GTG.alert(GTGEvent.TRIAL_PERIOD_EXPIRED); return true; } return false; } private void shutdownWithException(Exception e) { Log.e(GTG.TAG, "Exception running gps service", e); updateNotification(FLAG_ERROR_INTERNAL, true); stopSelf(); } /** * Show a notification while this service is running. */ private void showCurrentNotification() { // Log.d(TAG, "Showing current notification"); String CHANNEL_ID = "gpstrailer_channel"; if (Build.VERSION.SDK_INT >= 26) { NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Tiny Travel Tracker", NotificationManager.IMPORTANCE_DEFAULT); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel); } if (currentNotificationSetting.msgId == -1 && currentNotificationSetting.iconId == -1) { if (Build.VERSION.SDK_INT >= 26) { //we still need to create an icon, even though we are shutting down //or android will kill our app NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Tiny Travel Tracker", NotificationManager.IMPORTANCE_DEFAULT); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("") .setContentText("").build(); startForeground(1, notification); } return; } CharSequence text = getText(currentNotificationSetting.msgId); // Set the icon, scrolling text and timestamp NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); builder.setSmallIcon(currentNotificationSetting.iconId); builder.setOngoing(currentNotificationSetting.isOngoing); builder.setAutoCancel(!currentNotificationSetting.isOngoing); builder.setContentText(text); builder.setContentTitle("Tiny Travel Tracker"); // The PendingIntent to launch our activity if the user selects this notification // TODO 2.5 make settings lite for notification bar only. Set it's task affinity // different from the main app so hitting back doesn't cause "enter password" to be asked Intent intent = new Intent(this, SettingsActivity.class); PendingIntent contentIntent = PendingIntent .getActivity( this, 0, currentNotificationSetting.intent != null ? currentNotificationSetting.intent : intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(contentIntent); Notification notification = builder.build(); startForeground(1, notification); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "GPS Service Shutdown"); GTG.removeGTGEventListener(gtgEventListener); if (currentNotificationSetting != null && !currentNotificationSetting.sticky) { NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.cancel(GTG.FROG_NOTIFICATION_ID); } if (gpsManager != null) gpsManager.shutdown(); if (batteryReceiver != null) unregisterReceiver(batteryReceiver); if (GTG.prefs.isCollectData ) //|| GTGEvent.ERROR_UNLICENSED.isOn) { Log.i("EXIT", "ondestroy!"); //hack to restart the service if the os decides to kill us. Intent broadcastIntent = new Intent(this, GpsTrailerReceiver.class); sendBroadcast(broadcastIntent); } DebugLogFile.log("onDestroy called, restart finished"); } @Override public IBinder onBind(Intent intent) { return mBinder; } public void turnOffNotification() { NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.cancel(GTG.FROG_NOTIFICATION_ID); } public void shutdown() { Util.runOnHandlerSynchronously(mHandler, new Runnable() { @Override public void run() { stopSelf(); } }); } @Override public void onTaskRemoved(Intent rootIntent) { DebugLogFile.log("onTaskRemoved called, trying to restart"); ContextCompat.startForegroundService(this,new Intent(this, GpsTrailerService.class)); DebugLogFile.log("onTaskRemoved called, restart finished"); } }
gpl-3.0
dksaputra/community
graph-matching/src/main/java/org/neo4j/graphmatching/PatternMatch.java
4085
/** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphmatching; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; /** * Represents one match found by the {@link PatternMatcher}. The match is * itself a graph which looks like the pattern fed to the {@link PatternMatcher} */ @Deprecated public class PatternMatch { private Map<PatternNode,PatternElement> elements = new HashMap<PatternNode, PatternElement>(); private Map<PatternRelationship,Relationship> relElements = new HashMap<PatternRelationship,Relationship>(); PatternMatch( Map<PatternNode,PatternElement> elements, Map<PatternRelationship,Relationship> relElements ) { this.elements = elements; this.relElements = relElements; } /** * @param node the {@link PatternNode} to get the {@link Node} for. * @return the actual {@link Node} for this particular match, represented * by {@code node} in the pattern */ public Node getNodeFor( PatternNode node ) { return elements.containsKey( node ) ? elements.get( node ).getNode() : null; } /** * @param rel the {@link PatternRelationship} to get the * {@link Relationship} for. * @return the actual {@link Relationship} for this particular match, * represented by {@code rel} in the pattern */ public Relationship getRelationshipFor( PatternRelationship rel ) { return relElements.containsKey( rel ) ? relElements.get( rel ) : null; } /** * Get the matched elements in this match. * * @return an iterable over the matched elements in this match instance. */ public Iterable<PatternElement> getElements() { return elements.values(); } /** * Used to merge two matches. An example is to merge in an "optional" * subgraph match into a match. * @param matches the matches to merge together. * @return the merged matches as one match. */ public static PatternMatch merge( Iterable<PatternMatch> matches ) { Map<PatternNode, PatternElement> matchMap = new HashMap<PatternNode, PatternElement>(); Map<PatternRelationship, Relationship> relElements = new HashMap<PatternRelationship, Relationship>(); for ( PatternMatch match : matches ) { for ( PatternNode node : match.elements.keySet() ) { boolean exists = false; for ( PatternNode existingNode : matchMap.keySet() ) { if ( node.getLabel().equals( existingNode.getLabel() ) ) { exists = true; break; } } if ( !exists ) { matchMap.put( node, match.elements.get( node ) ); relElements.put( match.elements.get( node ).getFromPatternRelationship(), match.elements.get( node ).getFromRelationship() ); } } } PatternMatch mergedMatch = new PatternMatch( matchMap, relElements ); return mergedMatch; } /** * Used to merge matches. An example is to merge in an "optional" subgraph * match into a match. * * @param matches the matches to merge together. * @return the merged matches as one match. */ public static PatternMatch merge( PatternMatch... matches ) { return merge( Arrays.asList( matches ) ); } }
gpl-3.0
exbuddha/Mupeli
src/music/Scale.java
31719
package music; import java.lang.annotation.Annotation; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.type.NullType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeVisitor; import structs.DictionaryMap; import structs.Type; /** * {@code Scale} represents a musical scale. * <p> * Notes: * <ul> * <li>If a scale has a null {@code root}, it is considered to be a scale template, containing only scale intervals, and can only be used for the specific purpose of creating defined scales. * <li>A scale can't have null or empty {@code intervals} array. * <li>A scale can't contain a perfect unison interval. * <li>Scale intervals must cover an entire octave; no less and no more. * <li>A Scale must be either ascending or descending for all comparison functionality to work correctly, or ascending and descending, in rare cases, for which some comparisons might still fail. * For example, for an ascending and descending scale, the functionality for determining if that scale is diatonic, has an interval sequence equal to a diatonic scale, or has a note sequence equal to a diatonic scale will fail. * For these specific sets of functionality to work correctly, the ascending and descending scale must be sorted into its equivalent ascending scale prior to comparison. * <li>Scale interval adjustments are not accounted for in any scale comparison functionality. * If this is a requirement, the scales must be normalized prior to comparison. * <li>Scale {@code intervals} array is not cloned at creation time. * In order to create a deep copy of a scale, the entire array must be cloned. * <li>Scale {@code adjustments} array can be null or empty. * <li>Adjustment values cannot be bigger than an ascending interval or smaller than a descending interval. * In other words, an interval adjustment is not meant to reverse the direction of the interval itself. * This is true for all intervals in a scale, meaning that an interval adjustment should never reverse the direction of the scale growth as a whole, or expressions below must be true for every valid {@code i}: * <p> * <pre> * {@code Math.abs(adjustments[i]) < Math.abs(interval[i].getCents()) * Math.abs(adjustments[i]) < Math.abs(interval[i + 1].getCents())} * </pre> * </ul> */ public class Scale extends Interval implements Cloneable, Iterable<Scale.Note>, Type<Scale> { /** Chromatic scale. */ public static final Scale CHROMATIC = new Scale( null, new Interval[] { MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND, // S MINOR_SECOND // S }); /** Major scale. */ public static final Scale MAJOR = new Scale( null, new Interval[] { MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND // S }); /** Dorian scale. */ public static final Scale DORIAN = new Scale( null, new Interval[] { MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND // T }); /** Phrygian scale. */ public static final Scale PHRYGIAN = new Scale( null, new Interval[] { MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND // T }); /** Lydian scale. */ public static final Scale LYDIAN = new Scale( null, new Interval[] { MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND // S }); /** Mixolydian scale. */ public static final Scale MIXOLYDIAN = new Scale( null, new Interval[] { MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND // T }); /** Minor scale. */ public static final Scale MINOR = new Scale( null, new Interval[] { MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND // T }); /** Locrian scale. */ public static final Scale LOCRIAN = new Scale( null, new Interval[] { MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_SECOND, // S MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND // T }); /** Whole tone scale. */ public static final Scale WHOLE_TONE = new Scale( null, new Interval[] { MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND, // T MAJOR_SECOND // T }); /** Major pentatonic scale. */ public static final Scale MAJOR_PENTATONIC = new Scale( null, new Interval[] { MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_THIRD, // T + S MAJOR_SECOND, // T MINOR_THIRD // T + S }); /** Minor pentatonic scale. */ public static final Scale MINOR_PENTATONIC = new Scale( null, new Interval[] { MINOR_THIRD, // T + S MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_THIRD, // T + S MAJOR_SECOND // T }); /** Egyptian scale. */ public static final Scale EGYPTIAN = new Scale( null, new Interval[] { MAJOR_SECOND, // T MINOR_THIRD, // T + S MAJOR_SECOND, // T MINOR_THIRD, // T + S MAJOR_SECOND // T }); /** Blues major scale. */ public static final Scale BLUES_MAJOR = new Scale( null, new Interval[] { MAJOR_SECOND, // T MINOR_THIRD, // T + S MAJOR_SECOND, // T MAJOR_SECOND, // T MINOR_THIRD // T + S }); /** Blues minor scale. */ public static final Scale BLUES_MINOR = new Scale( null, new Interval[] { MINOR_THIRD, // T + S MAJOR_SECOND, // T MINOR_THIRD, // T + S MAJOR_SECOND, // T MAJOR_SECOND // T }); /** Map of scales in music. */ public static final DictionaryMap<Scale> MAP; /** Null scale. */ public static final Scale NULL; static { MAP = new DictionaryMap<>(); MAP.add("Chromatic", CHROMATIC); MAP.add("Major", MAJOR); MAP.add("Dorian", DORIAN); MAP.add("Phrygian", PHRYGIAN); MAP.add("Lydian", LYDIAN); MAP.add("Mixolydian", MIXOLYDIAN); MAP.add("Minor", MINOR); MAP.add("Locrian", LOCRIAN); MAP.add("Whole tone", WHOLE_TONE); MAP.add("Major pentatonic", MAJOR_PENTATONIC); MAP.add("Minor pentatonic", MINOR_PENTATONIC); MAP.add("Egyptian", EGYPTIAN); MAP.add("Blues major", BLUES_MAJOR); MAP.add("Blues minor", BLUES_MINOR); NULL = new Scale.Null(null, null, null, null) { @Override public <R, P> R accept(TypeVisitor<R, P> visitor, P param) { return null; } @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) { return null; } @Override public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) { return null; } @Override public List<? extends AnnotationMirror> getAnnotationMirrors() { return null; } @Override public TypeKind getKind() { return null; } @Override public boolean hasEqualIntervals(Scale scale) { return false; } }; } /** The scale symbol. */ protected final String symbol; /** The root note. */ protected final Note root; /** The scale intervals. */ protected final Interval[] intervals; /** The scale interval adjustments. */ protected Number[] adjustments; /** * Creates a scale with the specified symbol, root note, intervals, and interval adjustments; or throws an {@code IllegalArgumentException} if the {@code intervals} array is null or empty. * * @param symbol the scale symbol. * @param root the root note. * @param intervals the intervals array. * @param adjustments the interval adjustments array. * @throws IllegalArgumentException if the {@code intervals} array is null or empty. */ public Scale( final String symbol, final Note root, final Interval[] intervals, final Number[] adjustments ) { super(1200); if (intervals == null || intervals.length == 0) throw new IllegalArgumentException("Scale intervals array cannot be null or empty."); this.symbol = symbol; this.root = root; this.intervals = intervals; if (adjustments == null) this.adjustments = null; else { this.adjustments = new Number[adjustments.length]; for (byte i = (byte) 0; i < adjustments.length; i++) this.adjustments[i] = adjustments[i] == null ? (byte) 0 : adjustments[i]; } } /** * Creates a scale with the specified root note, intervals, and interval adjustments; or throws an {@code IllegalArgumentException} if the {@code intervals} array is null or empty. * * @param root the root note. * @param intervals the intervals array. * @param adjustments the interval adjustments array. * @throws IllegalArgumentException if the {@code intervals} array is null or empty. */ public Scale( final Note root, final Interval[] intervals, final Number[] adjustments ) { this(null, root, intervals, adjustments); } /** * Creates a scale with the specified root note and intervals, or throws an {@code IllegalArgumentException} if the {@code intervals} array is null or empty. * * @param root the root note. * @param intervals the intervals array. * @throws IllegalArgumentException if the {@code intervals} array is null or empty. */ public Scale( final Note root, final Interval[] intervals ) { this(root, intervals, null); } /** * Creates a scale with the specified root note similar to the specified scale, or throws an {@code IllegalArgumentException} if the {@code intervals} array is null or empty. * * @param root the root note. * @param scale the scale. * @throws IllegalArgumentException if the {@code intervals} array is null or empty. */ public Scale( final Note root, final Scale scale ) { this(root, scale.intervals); } /** * Adjusts and returns a new scale, equal to the scale, with interval adjustments added to scale notes. * The returned scale has a null {@code adjustments} array. * * @return the normalized scale. */ public Scale adjust() { return null; } /** * Returns true if the specified scale has the same root note, ignoring pitch, and the same intervals as this scale, and false otherwise. * <p> * If one of the scales has a null root, only the intervals will be compared. * * @param scale the scale. * @return true if the scales are the same ignoring pitch of the root notes, and false otherwise. */ public boolean equalsIgnorePitch( final Scale scale ) { return ( root == null || scale.root == null || root.equalsIgnorePitch(scale.root) ) && hasEqualIntervals(scale); } /** * Returns true if the specified scale has the same root note, ignoring octave and pitch, and the same intervals, and false otherwise. * <p> * If one of the scales has a null root, only the intervals will be compared. * * @param scale the scale. * @return true if the scales are the same ignoring pitch and octave of the root notes, and false otherwise. */ public boolean equalsIgnorePitchAndOctave( final Scale scale ) { return ( root == null || scale.root == null || root.equalsIgnorePitchAndOctave(scale.root) ) && hasEqualIntervals(scale); } /** * Returns true if the specified scale has the same intervals appearing in the same order as this scale, and false otherwise. * * @param scale the scale. * @return true if the scales have the same intervals, and false otherwise. */ public boolean hasEqualIntervals( final Scale scale ) { if (scale == null) return false; boolean equal = intervals.length == scale.intervals.length; for (byte i = 0; equal && i < intervals.length; i++) equal = intervals[i].compareTo(scale.intervals[i]) == 0; return equal; } /** * Returns true if the specified scale has the same interval sequence, ignoring the root, as this scale, and false otherwise. * <p> * This method can be used to verify if the specified scale is a mode of this scale. * * @param scale the scale. * @return true if the scales have the same mode, and false otherwise. */ public boolean hasEqualIntervalSequence( final Scale scale ) throws NullPointerException { if (scale == null) return false; if (intervals.length == scale.intervals.length) { boolean equal = false; for (byte i = (byte) 0; !equal && i < intervals.length; i++) equal = hasEqualIntervalSequence(scale, i); return equal; } else return false; } /** * Returns true if the specified scale has the same interval sequence as this scale, starting from this scale's interval at index {@code i}, and false otherwise. * * @param scale the scale. * @param i the starting interval index of this scale. * @return true if the scales have the same interval sequence, starting from the specified interval index of this scale, and false otherwise. */ private boolean hasEqualIntervalSequence( final Scale scale, int i ) { if (scale == null) return false; boolean match = true; for (int j = 0; match && j < scale.intervals.length; j++) { match = intervals[i].equals(scale.intervals[j]); i++; if (i == intervals.length) i = 0; } return match; } /** * Returns true if the specified scale has the same note sequence and root, ignoring octave and pitch, as this scale, and false otherwise. * <p> * For example, for the C major and the A minor scales this method returns true. * * @param scale the scale. * @return true if the scales have the same note sequence and root, ignoring octave and pitch, and false otherwise. */ public boolean hasEqualNoteSequence( final Scale scale ) { if (intervals.length == scale.intervals.length) { boolean equal = false; byte i = (byte) 0; for (final Note note : this) { if (note.equalsIgnorePitchAndOctave(scale.root) && i < intervals.length) equal = hasEqualIntervalSequence(scale, i); if (equal) break; i++; } return equal; } else return false; } /** * Returns true if the given scale name maps to an existing scale in {@code Scale.MAP} and the result scale has equal intervals as this scale, and false otherwise. * * @param name the scale name. * @return true if the scale has equal intervals as this scale, and false otherwise. */ public boolean is( final String name ) { return MAP.get(name, NULL).hasEqualIntervals(this); } /** * Returns true if the scale is an ascending scale, and false otherwise. * * @return true if the scale is ascending, and false otherwise. */ public boolean isAscending() { double length = 0D; for (final Interval interval : intervals) { if (interval.getCents() < 0) return false; length += interval.getCents(); } return length > 0; } /** * Returns true if the scale is a chromatic scale, and false otherwise. * <p> * In music theory, the chromatic scale is a twelve-note musical scale composed of eleven adjacent pitches, each separated by a semitone, and a repeated octave. * * @return true if the scale is chromatic, and false otherwise. */ public boolean isChromatic() { if (intervals.length != 12) return false; for (Interval interval : intervals) if (!interval.equals(MINOR_SECOND)) return false; return true; } /** * Returns true if the scale is a descending scale, and false otherwise. * * @return true if the scale is descending, and false otherwise. */ public boolean isDescending() { double length = 0D; for (Interval interval : intervals) { if (interval.getCents() > 0) return false; length += interval.getCents(); } return length < 0; } /** * Returns true if the scale is a diatonic scale, and false otherwise. * <p> * <b>Wikipedia:</b> In music theory, a diatonic scale (or heptatonia prima) is an eight-note musical scale composed of seven pitches and a repeated octave. * The diatonic scale includes five whole steps and two half steps for each octave, in which the two half steps are separated from each other by either two or three whole steps, depending on their position in the scale. * This pattern ensures that, in a diatonic scale spanning more than one octave, all the half steps are maximally separated from each other. (i.e. separated by at least two whole steps) * * @return true if the scale is diatonic, and false otherwise. */ public boolean isDiatonic() { if (length() == 12 && intervals.length == 7) { int firstHalfStepIndex = -1; int secondHalfStepIndex = -1; for (byte i = 0; i < intervals.length; i++) { if (intervals[i].equals(MINOR_SECOND)) { if (firstHalfStepIndex < 0) firstHalfStepIndex = i; else if (secondHalfStepIndex < 0) secondHalfStepIndex = i; else return false; } } final int distanceBetweenHalfSteps = secondHalfStepIndex - firstHalfStepIndex - 1; return ( distanceBetweenHalfSteps == 2 || distanceBetweenHalfSteps == 3 ) && firstHalfStepIndex + 6 - secondHalfStepIndex == 5 - distanceBetweenHalfSteps; } else return false; } /** * Returns the length of the scale in semitones. * If a scale covers an entire octave then length of that scale is 12. * * @return the length of the scale in semitones. */ public int length() { int length = intervals[0].getSemitones(); for (byte i = 1; i < intervals.length; i++) length += intervals[i].getSemitones(); return length; } /** * Returns the number of notes in the scale. * * @return the number of notes in the scale. */ public int size() { return intervals.length + 1; } /** * Creates and returns a deep copy of this scale. * * @return a deep copy of this scale. */ @Override public Scale clone() { final Interval[] intervals = new Interval[this.intervals.length]; for (byte i = 0; i < this.intervals.length; i++) intervals[i] = this.intervals[i].clone(); return new Scale(root, intervals, adjustments); } /** * Returns true if the specified object is a scale, has equal root note, and intervals as this scale, and false otherwise. * <p> * If the scale has null root, it is ignored in the comparison. * * @param obj the object. * @return true if the scale is exactly the same as the specified object, and false otherwise. */ @Override public boolean equals(final Object obj) { if (obj instanceof Scale) { final Scale scale = (Scale) obj; return ( root == null || scale.root == null || root.equals(scale.root) ) && hasEqualIntervals(scale); } else return false; } /** * Returns true if the specified scale has equal intervals as this scale. * <p> * This method internally calls {@code hasEqualIntervals(Scale)}. * * @param type the scale. * @return true if the specified scale has equal intervals as this scale. */ @Override public boolean is(final Type<Scale> type) { return type == null ? false : type instanceof Scale && hasEqualIntervals((Scale) type); } /** * Returns an iterator over the notes in the scale. * <p> * The number of returned notes is exactly one plus the number of the intervals in the scale. * * @return the iterator over scale notes. */ @Override public Iterator<Note> iterator() { return new Iterator<Note>() { private Note note; private int step = -1; @Override public final boolean hasNext() { return step < Scale.this.intervals.length; } @Override public final Note next() { step++; if (step == 0) note = root; else if (step - 1 < intervals.length) { note = Note.withNumber(note.getNumber() + intervals[step - 1].getSemitones()); if (adjustments != null) note.setAdjustment(adjustments[step - 1]); } else throw new NoSuchElementException("There are no more notes in the scale."); return note; } }; } /** * Returns the scale interval adjustments array. * * @return the interval adjustments array. */ public Number[] getAdjustments() { return adjustments; } /** * Returns the scale intervals array. * * @return the intervals array. */ public Interval[] getIntervals() { return intervals; } /** * Returns the root of the scale. * * @return the root of the scale. */ public Note getRoot() { return root; } /** * Sets the scale interval adjustments array. * * @param adjustments the interval adjustments array. */ public void setAdjustments( final Number[] adjustments ) { this.adjustments = adjustments; } /** * {@code Note} represents the musical scale note with a certain octave, pitch, and accidental. * <p> * Notes: * <ul> * <li>Double-accidentals are supported. * </ul> */ public static class Note extends music.Note { /** The adjusted note octave. */ protected byte adjOctave; /** The adjusted note pitch. */ protected Pitch adjPitch; /** The adjusted note accidental. */ protected Accidental adjAccidental; /** * Creates a scale note with the specified octave, pitch, and accidental; or throws an {@code IllegalArgumentException} if pitch is null; or throws a {@code RuntimeException} type if octave cannot be casted to {@code byte}. * * @param octave the octave. * @param pitch the pitch. * @param accidental the accidental. * @throws IllegalArgumentException if pitch is null. */ public Note( final Number octave, final Pitch pitch, final music.Note.Accidental accidental ) { super(octave, pitch, accidental); adjust(); } /** * Creates a natural scale note with the specified octave and pitch; or throws an {@code IllegalArgumentException} if pitch is null; or throws a {@code RuntimeException} type if octave cannot be casted to {@code byte}. * * @param octave the octave. * @param pitch the pitch. * @throws IllegalArgumentException if pitch is null. */ public Note( final Number octave, final Pitch pitch ) { super(octave, pitch); adjust(); } /** * Returns a new scale note for the specified MIDI note number, or throws an {@code IllegalArgumentException} if number is less than 0. * * @param number the note number. * @return the note. * @throws IllegalArgumentException if the note number is less than 0. */ public static Note withNumber( final int number ) { if (number < 0) throw new IllegalArgumentException("Scale note number cannot be less than 0."); // TODO - It might be more efficient to override withNumber() in this class final music.Note note = music.Note.withNumber(number); return new Note(note.octave, note.pitch, note.accidental); } /** * Sets adjusted values for the scale note. */ @Override protected void adjust() { adjOctave = octave; adjPitch = pitch; adjAccidental = (Accidental) accidental; Accidental.adjust(this, adjAccidental); // TODO - Investigate what adjustments are required for scale notes } @Override public void invert() {} /** * {@code Accidental} represents a scale note accidental. */ public static class Accidental extends music.Note.Accidental { /** The double-flat accidental. */ public static final Accidental DOUBLE_FLAT = new Accidental("bb", (byte) -2, (byte) -200); /** The double-sharp accidental. */ public static final Accidental DOUBLE_SHARP = new Accidental("##", (byte) 2, (byte) 200); /** * Create a scale note accidental. * * @param symbol the symbol. * @param semitones the semitones. * @param cents the cents. */ protected Accidental( final String symbol, final byte semitones, final byte cents ) { super(symbol, semitones, cents); } /** * Adjusts the scale note based on the value of the scale note accidental. * * @param note the scale note. * @param accidental the scale note accidental. */ public static void adjust( final Note note, final Accidental accidental ) { if (accidental == DOUBLE_FLAT || accidental == DOUBLE_SHARP) { // TODO - Adjust note } } /** * Adjusts the scale note for the specified scale. * * @param note the scale note. * @param scale the scale. */ public static void adjust( final Note note, final Scale scale ) {} /** * Returns the accidental for the specified semitones, or throws an {@code IllegalArgumentException} if the semitones value is out of range. * * @param semitones the semitones. * @return the accidental. */ public static music.Note.Accidental withSemitones( final Number semitones ) { switch ((byte) semitones) { case -2: return DOUBLE_FLAT; case -1: return FLAT; case 0: return NATURAL; case 1: return SHARP; case 2: return DOUBLE_SHARP; default: throw new IllegalArgumentException("Accidental semitones must be between -2 and 2."); } } } } /** * {@code Null} classifies the null scale and all derivatives of scale that cannot be characterized by traditional definitions. */ protected static abstract class Null extends Scale implements NullType { /** * Creates a null scale type. * * @param symbol the symbol. * @param root the root. * @param intervals the intervals. * @param adjustments the interval adjustments. */ protected Null( final String symbol, final Note root, final Interval[] intervals, final Number[] adjustments ) { super(symbol == null ? "null" : symbol, root, intervals == null ? new Interval[] { null } : intervals, adjustments); } } }
gpl-3.0
Dramentiaras/LD31
src/com/goudagames/ld31/gui/GuiObject.java
322
package com.goudagames.ld31.gui; public class GuiObject { public float x, y, width, height; public GuiObject(float x, float y, float width, float height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void update(float delta) { } public void render() { } }
gpl-3.0
gasgastrial/RealClock
RealClock.java
1537
import java.util.logging.Logger; /* Copyright (C) 2011 gasgastrial This file is part of RealClock. RealClock is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RealClock is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with RealClock. If not, see <http://www.gnu.org/licenses/>. */ public class RealClock extends Plugin { private Logger log = Logger.getLogger("Minecraft"); public static String name = "RealClock"; public static String version = "1.0.1"; private RealClocklistener listener; public void disable() { log.info(name + " version " + version + " disabled."); } public void enable() { log.info(name + " version " + version + " enabled."); } public void initialize() { log.info(name + " version " + version + " initialized."); listener = new RealClocklistener(); etc.getLoader().addListener(PluginLoader.Hook.SIGN_CHANGE, listener, this, PluginListener.Priority.MEDIUM); etc.getLoader().addListener(PluginLoader.Hook.SIGN_SHOW, listener, this, PluginListener.Priority.MEDIUM); } }
gpl-3.0
gerrykoun/simbug
simbug-server/source/main/java/gr/aua/simbug/dao/impl/GameSessionRoundPlayerVariableDAOImpl.java
525
package gr.aua.simbug.dao.impl; import gr.aua.simbug.dao.GameSessionRoundPlayerVariableDAO; import gr.aua.simbug.model.DbGameSessionRoundPlayerVariable; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; public class GameSessionRoundPlayerVariableDAOImpl extends HibernateDaoSupport implements GameSessionRoundPlayerVariableDAO { @Override public void save(DbGameSessionRoundPlayerVariable dbGameSessionRoundPlayerVariable) { getHibernateTemplate().save(dbGameSessionRoundPlayerVariable); } }
gpl-3.0
golo120/MyProject
j8583-code/j8583/src/main/java/com/solab/iso8583/parse/AlphaNumericFieldParseInfo.java
2223
/* j8583 A Java implementation of the ISO8583 protocol Copyright (C) 2011 Enrique Zamudio Lopez This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ package com.solab.iso8583.parse; import java.io.UnsupportedEncodingException; import java.text.ParseException; import com.solab.iso8583.CustomField; import com.solab.iso8583.IsoType; import com.solab.iso8583.IsoValue; /** This is the common abstract superclass to parse ALPHA and NUMERIC field types. * * @author Enrique Zamudio */ public abstract class AlphaNumericFieldParseInfo extends FieldParseInfo { public AlphaNumericFieldParseInfo(IsoType t, int len) { super(t, len); } public IsoValue<?> parse(byte[] buf, int pos, CustomField<?> custom) throws ParseException, UnsupportedEncodingException { if (pos < 0) { throw new ParseException(String.format("Invalid ALPHA/NUM position %d", pos), pos); } else if (pos+length > buf.length) { throw new ParseException(String.format("Insufficient data for %s field of length %d, pos %d", type, length, pos), pos); } String _v = new String(buf, pos, length, getCharacterEncoding()); if (_v.length() != length) { _v = new String(buf, pos, buf.length-pos, getCharacterEncoding()).substring(0, length); } if (custom == null) { return new IsoValue<String>(type, _v, length, null); } else { @SuppressWarnings({"unchecked", "rawtypes"}) IsoValue<?> v = new IsoValue(type, custom.decodeField(_v), length, custom); if (v.getValue() == null) { return new IsoValue<String>(type, _v, length, null); } return v; } } }
gpl-3.0