text
stringlengths
10
2.72M
import java.util.*; import java.io.*; import java.awt.*; public class MapDataDrawer { private int[][] grid; int rows; int columns; int minValue; int maxValue; boolean displayIsOn; // Enable/disable drawing // Constructor public MapDataDrawer(String fileName) { Scanner reader = null; // create a reader try { reader = new Scanner( new FileInputStream( fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } // Read the first two numbers in the file, which should respectively be the number of rows and columns rows = reader.nextInt(); columns = reader.nextInt(); // initialize grid grid = new int[rows][columns]; //read the data from the file into the grid for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { grid[ i][j] = reader.nextInt(); } } minValue = findMinValueInGrid(); maxValue = findMaxValueInGrid(); displayIsOn = true; // default is drawing is enabled. System.out.println("Successfully read file " + fileName); }//end MapDataDrawer() /** * @return the min value in the entire grid */ public int findMinValueInGrid() { minValue = Integer.MAX_VALUE; // Step through all array elements for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if( grid[i][j] < minValue) { minValue = grid[i][j]; } }//end for( int j }//end for( int i return minValue; }//end findMinValueInGrid() /** * @return the max value in the entire grid */ public int findMaxValueInGrid() { maxValue = Integer.MIN_VALUE; // Step through all array elements for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if( grid[i][j] > maxValue) { maxValue = grid[i][j]; } }//end for( int j }//end for( int i return maxValue; }//end findMaxValueInGrid() /** * @param col the column of the grid to check * @return the index of the row with the lowest value in the given col for the grid */ public int findIndexOfMinimumValueInColumn(int col) { int minimumInColValue = Integer.MAX_VALUE; int indexOfMinimumValue = 0; // Step through all row elements for this column for (int i = 0; i < rows; i++) { if( grid[i][col] < minimumInColValue) { minimumInColValue = grid[i][col]; indexOfMinimumValue = i; } }//end for( int j return indexOfMinimumValue; }//end findIndexOfMinimumValueInColumn() /** * Draws the grid using the given Graphics object. * Colors should be grayscale values 0-255, scaled based on min/max values in grid */ public void drawMap(Graphics g) { // Since we have the minValue and the maxValue, compute the scale factor double scaleFactor = 255.0 / (maxValue - minValue); // Draw each small rectangle // Step through all array elements for (int i = 0; i < rows; i++) { if( i==1) { System.out.println("Pause."); } for (int j = 0; j < columns; j++) { int c = (int)( (grid[i][j] - minValue) * scaleFactor); //calculated grayscale value // Make negative values blue (water) if( grid[i][j] > 0) { g.setColor(new Color(c, c, c)); } else { g.setColor(new Color(c, c, 255)); } // Our data is stored row,col, but the graphics drawing expects col,row, so reverse them here if( displayIsOn) { g.fillRect(j,i,1,1); } }//end for( int j }//end for( int i }//end drawMap() // Find the smallest elevation change of the 3 neighbors to the right and return it. // If there is a tie, choose one at random. private int findRowWithSmallestChange( int x, int y, int z, Random randGenerator) // random number generator that has had seed applied { int returnValue = -1; if( x<y && x<z) returnValue = -1; // new row is up one else if( y<x && y<z) returnValue = 0; // new row is the same else if( z<x && z<y) returnValue = 1; // new row is down one else { // There is a tie between at least two of them, so choose new row change (-1,0,+1) at random if( x==y) returnValue = (randGenerator.nextDouble() > 0.5) ? -1 : 0; else if( x==z) returnValue = (randGenerator.nextDouble() > 0.5) ? -1 : 1; else if( y==z) returnValue = (randGenerator.nextDouble() > 0.5) ? 0 : 1; else { // Sanity check. Should never get here System.out.println("Logic error in finding row with smallest change. Exiting program."); System.exit( -1); } } return returnValue; }//end findRowWithSmallestChange() /** * Find a path from West-to-East starting at given row. * Choose a foward step out of 3 possible forward locations, using greedy method described in assignment. * * @return the total change in elevation traveled from West-to-East */ public int drawGreedyPathStartingAt(Graphics g, int row, int column) { int totalVerticalChange = 0; Random randGenerator = new Random( 1); // Seed the random number generator, for predictable results // On each iteration make a step either directly right, or right-and-up or right-and-down while( column < (columns-1)) { // Ensure row is always at least 1 away from the upper boundary (0) and the lower, so that // checking the neighbors always works if( row == 0) row++; // change it to 1 to avoid arrray references attempting to go before the top row if( row == (rows-1)) row--; // decrement by one to avoid array references going past the last row // Since our data is in row,col order but graphics are in col,row order, swap them when graphing if( displayIsOn) { g.fillRect(column, row,1,1); } // Find new location. New row will either be the same (0), up (-1) or down (+1) int rowChange = findRowWithSmallestChange( Math.abs(grid[row][column] - grid[ row-1][column+1]), // right and up one Math.abs(grid[row][column] - grid[ row ][column+1]), // straight across to the right Math.abs(grid[row][column] - grid[ row+1][column+1]), // right and down one randGenerator); // random number generator, that has seed applied // Add to the total Vertical Change so far totalVerticalChange += Math.abs( grid[row][column] - grid[row + rowChange][column+1] ); row += rowChange; column++; // Advance to next column } // Graph the last (right-most) column // Since our data is in row,col order but graphics are in col,row order, swap them when graphing if( displayIsOn) { g.fillRect(column, row,1,1); } return totalVerticalChange; }//end drawGreedyPathStartingAt() /** * Find a REVERSE path from East-to-West starting at given row and column. * Choose a foward step out of 3 possible forward locations, using greedy method described in assignment. * * @return the total change in elevation traveled in REVERSE, from East-to-Wests */ public int drawGreedyREVERSEPathStartingAt(Graphics g, int row, int column) { int totalVerticalChange = 0; Random randGenerator = new Random( 1); // Seed the random number generator, for predictable results // On each iteration make a step either directly left, or left-and-up or left-and-down while( column > 0) { // Ensure row is always at least 1 away from the upper boundary (0) and the lower, so that // checking the neighbors always works if( row == 0) row++; // change it to 1 to avoid arrray references attempting to go before the top row if( row == (rows-1)) row--; // decrement by one to avoid array references going past the last row // Since our data is in row,col order but graphics are in col,row order, swap them when graphing if( displayIsOn) { g.fillRect(column, row, 1, 1); } // Find new location. New row will either be the same (0), up (-1) or down (+1) int rowChange = findRowWithSmallestChange( Math.abs(grid[row][column] - grid[ row-1][column-1]), // left and up one Math.abs(grid[row][column] - grid[ row ][column-1]), // straight across to the left Math.abs(grid[row][column] - grid[ row+1][column-1]), // left and down one randGenerator); // random number generator, that has seed applied // Add to the total Vertical Change so far totalVerticalChange += Math.abs( grid[row][column] - grid[row + rowChange][column-1] ); row += rowChange; column--; // Advance to next column } // Graph the last (left-most) column // Since our data is in row,col order but graphics are in col,row order, swap them when graphing if( displayIsOn) { g.fillRect(column, row,1,1); } return totalVerticalChange; }//end drawGreedyREVERSEPathStartingAt() /** * Draw lowest row in each column, as a hint for future heuristics */ public void drawLowestElevationInEachColumn(Graphics g) { int lowestValue = 0; int lowestValueRow = 0; // for each column for (int col = 0; col < columns; col++) { lowestValue = Integer.MAX_VALUE; lowestValueRow = -1; // for each row for( int row = 0; row < rows; row++) { if (grid[row][col] < lowestValue) { lowestValue = grid[row][col]; lowestValueRow = row; } } // We now have the lowest elevation in this column, so graph it. // Since our data is in row,col order but graphics are in col,row order, swap them when graphing if( displayIsOn) { g.fillRect(col, lowestValueRow, 1, 1); } } }//end drawLowestElevationInEachColumn() /** * @return the index of the starting row for the lowest-elevation-change path in the entire grid. */ public int indexOfLowestElevPath(Graphics g) { return( findIndexOfMinimumValueInColumn( 0)); } // "Get" methods public int getRows() { return rows; } public int getCols() { return columns; } // "Set" methods public void setDisplayIsOnTo( boolean value) { displayIsOn = value; } }//end class MapDataDrawer
package com.flutterwave.raveutils.di; import com.flutterwave.raveandroid.rave_logger.di.EventLoggerModule; import com.flutterwave.raveandroid.rave_remote.di.RemoteModule; import com.flutterwave.raveutils.verification.AVSVBVFragment; import com.flutterwave.raveutils.verification.OTPFragment; import com.flutterwave.raveutils.verification.PinFragment; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = {RemoteModule.class, EventLoggerModule.class}) public interface VerificationComponent { void inject(AVSVBVFragment avsvbvFragment); void inject(OTPFragment otpFragment); void inject(PinFragment pinFragment); WebComponent plus(WebModule webModule); }
package com.hhub.bookhub.Services; public class APIService { private static String base_url = "http://huynhvanhaua.000webhostapp.com/server/bookhub/"; public static Service getService(){ return APIRetrofitClient.getClient(base_url).create(Service.class); } }
package com.mideas.old; public class Calcul { public static void isDad(int a) { if(a%2 == 0) { System.out.println("Le nombre est paire"); } else { System.out.println("Le nombre n'est pas paire"); } } public static void pow(int b) { for(int i=1;i<6;i++) { System.out.println("La puissance "+i+" du nombre "+b+" est "+(int)Math.pow(b, i)); if(Math.pow(b, i)%2 ==0) { System.out.println("Le nombre "+b+" est paire"); } } } }
package com.dict.hm.dictionary.ui; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.dict.hm.dictionary.R; import com.dict.hm.dictionary.ui.dialog.AlertDialogFragment; import com.dict.hm.dictionary.ui.dialog.EditDialog; import com.dict.hm.dictionary.ui.dialog.NotificationDialog; import com.dict.hm.dictionary.ui.dialog.ProgressDialog; import java.io.File; /** * Created by hm on 15-3-18. */ public abstract class BaseManagerActivity extends AppCompatActivity implements FileListFragment.FileSelectedListener, AlertDialogFragment.ConfirmDialogListener, EditDialog.EditDialogListener { public static final String FRAGMENT_TAG = "top"; ActionBar actionBar; Toolbar toolbar; ListView listView; TextView empty; FloatingActionButton fab; FileListFragment fileListFragment; File selectedFile; String title = null; int action = -1; static final int ADD = 0; static final int DEL = 1; String notification = null; boolean isStop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manager); toolbar = (Toolbar) findViewById(R.id.manager_toolbar); listView = (ListView) findViewById(R.id.manager_listView); empty = (TextView) findViewById(R.id.emptyView); fab = (FloatingActionButton) findViewById(R.id.manager_fab); setSupportActionBar(toolbar); listView.setEmptyView(empty); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(null); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (!dismissFragment()) { finish(); } return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (fileListFragment != null ) { if (fileListFragment.onBackPressed()) { return; } else { dismissFragment(); return; } } if (dismissFragment()) { return; } super.onBackPressed(); } @Override protected void onStop() { super.onStop(); isStop = true; } @Override protected void onStart() { super.onStart(); isStop = false; if (notification != null) { setNotification(notification); } } protected void showFragment(Fragment fragment) { getFragmentManager().beginTransaction() .add(R.id.manager_frame, fragment, FRAGMENT_TAG) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .commit(); listView.setVisibility(View.INVISIBLE); empty.setVisibility(View.INVISIBLE); // if (actionBar != null) { // actionBar.setHomeButtonEnabled(true); // actionBar.setDisplayHomeAsUpEnabled(true); // } } protected boolean dismissFragment() { Fragment fragment = getFragmentManager().findFragmentByTag(FRAGMENT_TAG); if (fragment == null) { return false; } getFragmentManager().beginTransaction() .remove(fragment) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE) .commit(); listView.setVisibility(View.VISIBLE); if (listView.getAdapter().isEmpty()) { empty.setVisibility(View.VISIBLE); } // if (actionBar != null) { // actionBar.setHomeButtonEnabled(false); // actionBar.setDisplayHomeAsUpEnabled(false); // } // toolbar.setTitle(title); fileListFragment = null; return true; } /** * after onStop() call this method (fragment's commit() method) will cause IllegalStateException. * * @param text */ public void setNotification(String text) { if (isStop) { notification = text; return; } else { notification = null; } NotificationDialog dialog = NotificationDialog.newInstance(text); dialog.show(getFragmentManager(), null); if (fab.getVisibility() == View.VISIBLE) { final float y = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, getResources().getDisplayMetrics()); fab.animate().translationYBy(-y); dialog.setFab(fab, y); } } public void setProgressDialog(int progress) { if (dialog != null && dialog.isAdded()) { dialog.setProgressBar(progress); } } public void dismissProgressDialog() { if (dialog != null) { dialog.dismissAllowingStateLoss(); } } public void initProgressDialog(String msg, int max) { dialog = ProgressDialog.newInstance(msg, max); dialog.show(getFragmentManager(), null); } ProgressDialog dialog; }
package com.tencent.mm.plugin.gallery.view; import com.tencent.mm.plugin.gallery.view.MultiGestureImageView.f; class MultiGestureImageView$f$1 implements Runnable { final /* synthetic */ f jFn; MultiGestureImageView$f$1(f fVar) { this.jFn = fVar; } public final void run() { float g; this.jFn.jFl.getImageMatrix().getValues(this.jFn.jFk); float scale = this.jFn.jFl.getScale() * ((float) this.jFn.jFl.getImageWidth()); float imageHeight = ((float) this.jFn.jFl.getImageHeight()) * this.jFn.jFl.getScale(); float f = this.jFn.jFk[2]; float f2 = this.jFn.jFk[5]; float f3 = this.jFn.jFk[2] + scale; float f4 = this.jFn.jFk[5] + imageHeight; float f5 = 0.0f; float i = (float) MultiGestureImageView.i(this.jFn.jFj); float f6 = 0.0f; float g2 = (float) MultiGestureImageView.g(this.jFn.jFj); if (imageHeight < ((float) MultiGestureImageView.i(this.jFn.jFj))) { f5 = (((float) MultiGestureImageView.i(this.jFn.jFj)) / 2.0f) - (imageHeight / 2.0f); imageHeight = (((float) MultiGestureImageView.i(this.jFn.jFj)) / 2.0f) + (imageHeight / 2.0f); } else { imageHeight = i; } i = f5 - f2; imageHeight -= f4; if (i >= 0.0f) { if (imageHeight > 0.0f) { i = imageHeight; } else { i = 0.0f; } } if (scale < ((float) MultiGestureImageView.g(this.jFn.jFj))) { g = (((float) MultiGestureImageView.g(this.jFn.jFj)) / 2.0f) + (scale / 2.0f); f6 = (((float) MultiGestureImageView.g(this.jFn.jFj)) / 2.0f) - (scale / 2.0f); } else { g = g2; } imageHeight = f6 - f; g -= f3; if (imageHeight >= 0.0f) { if (g > 0.0f) { imageHeight = g; } else { imageHeight = 0.0f; } } if (Math.abs(imageHeight) > 5.0f || Math.abs(i) > 5.0f) { if (imageHeight >= 0.0f) { imageHeight = ((float) (((double) Math.abs(imageHeight)) - Math.pow(Math.sqrt((double) Math.abs(imageHeight)) - 1.0d, 2.0d))) * 2.0f; } else { imageHeight = (-((float) (((double) Math.abs(imageHeight)) - Math.pow(Math.sqrt((double) Math.abs(imageHeight)) - 1.0d, 2.0d)))) * 2.0f; } if (i >= 0.0f) { i = ((float) (((double) Math.abs(i)) - Math.pow(Math.sqrt((double) Math.abs(i)) - 1.0d, 2.0d))) * 2.0f; } else { i = (-((float) (((double) Math.abs(i)) - Math.pow(Math.sqrt((double) Math.abs(i)) - 1.0d, 2.0d)))) * 2.0f; } } else { this.jFn.bwt = true; } this.jFn.jFl.V(imageHeight, i); } }
package cd.com.a.dao; import java.util.List; import cd.com.a.model.memberDto; import cd.com.a.model.orderDetailParam; import cd.com.a.model.productSaleDto; import cd.com.a.model.saleingOptionParam; public interface orderDao { public memberDto getDefultAddress(int mem_seq); public boolean crete_productOrder(productSaleDto saleList); public void create_SaleGroup(int mem_seq); public int getSaleGroup(int mem_seq); public boolean kakaoUpdate(productSaleDto saleDto); public productSaleDto getNowSaleing(int mem_seq); public List<productSaleDto> getNowSaleingList(int saleing_group); public boolean FailOrder(int saleing_group); public List<Integer>myOrderList_group(int mem_seq); public List<orderDetailParam>myOrderDetail(int saleing_group); public boolean orderOptionProcess(saleingOptionParam param); }
package neural_net; import ga.Gene; import java.util.ArrayList; import java.util.List; /** * Network class that contains entire structure of neural network. */ public class Network { private List<Layer> layers; private StructuralInfo structuralInfo; /** * Initializes a new Neural Network using given structural information. * * @param structuralInfo The object containing all structural information required to build a neural network. */ public Network(StructuralInfo structuralInfo) { this.structuralInfo = structuralInfo; } /** * Method to build a neural network. Each layer is constructed * from the structural info object, and then the connections * between layers are established. */ public void constructNetwork() { layers = new ArrayList<>(); // build input layer Layer input = new InputLayer(structuralInfo.getNumInputs()); layers.add(0, input); // build all hidden layers from structural info for (int hiddenLayerNum = 0; hiddenLayerNum < structuralInfo.getHiddenLayerInformation().length; hiddenLayerNum++) { Layer hiddenLayer = new HiddenLayer(structuralInfo.getHiddenLayerInformation()[hiddenLayerNum]); layers.add(hiddenLayerNum + 1, hiddenLayer); } // build output layer Layer outputLayer = new OutputLayer(structuralInfo.getNumOutputs()); layers.add(outputLayer); // build all connections between layers buildConnections(); } /** * Method to build connections between layers. All layers are * looped through, and all neurons from consecutive layers are * created as Connection objects, which are stored in Layer. * */ private void buildConnections() { // loop through all layers, minus the output layer for (int layerNum = 0; layerNum < layers.size() - 1; layerNum++) { Layer currentLayer = layers.get(layerNum); Layer nextLayer = layers.get(layerNum + 1); // loop through all neurons in the current layer for (int neuronNum = 0; neuronNum < currentLayer.getNeurons().size(); neuronNum++) { Neuron neuron = currentLayer.getNeurons().get(neuronNum); List<Connection> outGoingConnections = new ArrayList<>(); // loop through all neurons in the next layer, adding // them to a connection list. // The layer will eventually hold the connection list // as a hash map with the neuron being the key. for (int nextNeuronNum = 0; nextNeuronNum < nextLayer.getNeurons().size(); nextNeuronNum++) { outGoingConnections.add(new Connection(neuron, nextLayer.getNeurons().get(nextNeuronNum))); } // adds the list of connections stemming from a // neuron. currentLayer.addKeyValuePair(neuron, outGoingConnections); } } } /** * Sets every weight in the network given a list of genes. * This is used as a coupling point between a network and * a genetic algorithm that may be used to train it. * * @param genes The list of genes that correspond to weights in the network. */ public void setWeights(List<Gene> genes){ int count = 0; try { // loop through all layers until the output is reached for (int layerIndex = 0; layerIndex < layers.size() - 1; layerIndex++) { Layer layer = layers.get(layerIndex); // loop through all neurons in the current layer for (Neuron neuron : layer.getNeurons()) { // loop through all outgoing connections for the current neuron for (Connection connection : layer.getOutGoingConnections().get(neuron)) { // set the weight of the connection to the next gene in the list connection.setWeight(genes.get(count).getValue()); count++; } } } // check that there are enough genes } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); System.out.println("Too few genes"); // check that there aren't too many genes } finally { if (count != genes.size()) { System.out.println("Too many genes"); } } } /** * @return The total number of weights (connections) in the neural network. */ public int size() { int size = 0; // loop through all layers until the output is reached for (int layerIndex = 0; layerIndex < layers.size() - 1; layerIndex++) { Layer layer = layers.get(layerIndex); // loop through all neurons in the current layer for (Neuron neuron : layer.getNeurons()) { // add the amount of connections for the current neuron to the count of all connections if (layer.getOutGoingConnections() != null) size += layer.getOutGoingConnections().get(neuron).size(); } } return size; } /** * @return The list of layer objects contained for the network. */ public List<Layer> getLayers() { return layers; } /** * Sets the layers that will be used by the network. * * @param layers The list of layer objects to be used by the network. */ public void setLayers(List<Layer> layers) { this.layers = layers; } }
package jp.abyss.sysparticle.api; import org.bukkit.Location; import org.bukkit.util.Vector; import java.util.Objects; public class RelativeLocation implements Cloneable { private double x; private double y; private double z; public RelativeLocation() { x = y = z = 0; } public RelativeLocation(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double getX() { return x; } public RelativeLocation setX(double x) { this.x = x; return this; } public double getY() { return y; } public RelativeLocation setY(double y) { this.y = y; return this; } public double getZ() { return z; } public RelativeLocation setZ(double z) { this.z = z; return this; } public Location getAbsoluteLocation(Location origin) { return origin.add(x, y, z); } public RelativeLocation addVector(Vector vector) { setX(x + vector.getX()); setY(y + vector.getY()); setZ(z + vector.getZ()); return this; } public RelativeLocation addRelativeLocation(RelativeLocation relativeLocation) { setX(x + relativeLocation.getX()); setX(y + relativeLocation.getY()); setZ(z + relativeLocation.getZ()); return this; } public RelativeLocation clone() { try { return ((RelativeLocation) super.clone()).setX(this.x).setY(this.y).setZ(this.z); } catch (CloneNotSupportedException e) { throw new Error(e); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RelativeLocation that = (RelativeLocation) o; return Double.compare(that.x, x) == 0 && Double.compare(that.y, y) == 0 && Double.compare(that.z, z) == 0; } @Override public int hashCode() { return Objects.hash(x, y, z); } }
package com.example.cash_you.ui.categories; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import com.example.cash_you.R; import com.example.cash_you.models.Category; import com.github.mikephil.charting.charts.PieChart; public class CategoriesFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = (View) inflater.inflate(R.layout.fragment_categories, container, false); // Create default categories - Food, Eating out, Fare, Purchases Category foodCategory = new Category("Food"); final TextView foodName = (TextView) view.findViewById(R.id.foodName); final TextView foodBalance = (TextView) view.findViewById(R.id.foodBalance); foodName.setText(foodCategory.GetName()); foodBalance.setText(foodCategory.GetCurrentBalance()); Category eatingOutCategory = new Category("Eating out"); final TextView eatingOutName = (TextView) view.findViewById(R.id.eatingOutName); final TextView eatingOutBalance = (TextView) view.findViewById(R.id.eatingOutBalance); eatingOutName.setText(eatingOutCategory.GetName()); eatingOutBalance.setText(eatingOutCategory.GetCurrentBalance()); Category fareCategory = new Category("Fare"); final TextView fareName = (TextView) view.findViewById(R.id.fareName); final TextView fareBalance = (TextView) view.findViewById(R.id.fareBalance); fareName.setText(fareCategory.GetName()); fareBalance.setText(fareCategory.GetCurrentBalance()); Category purchasesCategory = new Category("Purchases"); final TextView purchasesName = (TextView) view.findViewById(R.id.purchasesName); final TextView purchasesBalance = (TextView) view.findViewById(R.id.purchasesBalance); purchasesName.setText(purchasesCategory.GetName()); purchasesBalance.setText(purchasesCategory.GetCurrentBalance()); PieChart chart = (PieChart) view.findViewById(R.id.outcome_chart); Chart outcomeChart = new Chart(chart); outcomeChart.addData(50, ContextCompat.getColor(getActivity(), R.color.foodColor)); outcomeChart.addData(40, ContextCompat.getColor(getActivity(), R.color.eatingOutColor)); outcomeChart.addData(30, ContextCompat.getColor(getActivity(), R.color.fareColor)); outcomeChart.addData(20, ContextCompat.getColor(getActivity(), R.color.purchasesColor)); return view; } }
/** */ package com.rockwellcollins.atc.limp.util; import com.rockwellcollins.atc.limp.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see com.rockwellcollins.atc.limp.LimpPackage * @generated */ public class LimpSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static LimpPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LimpSwitch() { if (modelPackage == null) { modelPackage = LimpPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case LimpPackage.SPECIFICATION: { Specification specification = (Specification)theEObject; T result = caseSpecification(specification); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.DECLARATION: { Declaration declaration = (Declaration)theEObject; T result = caseDeclaration(declaration); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.COMMENT: { Comment comment = (Comment)theEObject; T result = caseComment(comment); if (result == null) result = caseDeclaration(comment); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.IMPORT: { Import import_ = (Import)theEObject; T result = caseImport(import_); if (result == null) result = caseDeclaration(import_); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.EXTERNAL_FUNCTION: { ExternalFunction externalFunction = (ExternalFunction)theEObject; T result = caseExternalFunction(externalFunction); if (result == null) result = caseDeclaration(externalFunction); if (result == null) result = caseFunctionRef(externalFunction); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.EXTERNAL_PROCEDURE: { ExternalProcedure externalProcedure = (ExternalProcedure)theEObject; T result = caseExternalProcedure(externalProcedure); if (result == null) result = caseDeclaration(externalProcedure); if (result == null) result = caseFunctionRef(externalProcedure); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.LOCAL_FUNCTION: { LocalFunction localFunction = (LocalFunction)theEObject; T result = caseLocalFunction(localFunction); if (result == null) result = caseDeclaration(localFunction); if (result == null) result = caseFunctionRef(localFunction); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.LOCAL_PROCEDURE: { LocalProcedure localProcedure = (LocalProcedure)theEObject; T result = caseLocalProcedure(localProcedure); if (result == null) result = caseDeclaration(localProcedure); if (result == null) result = caseFunctionRef(localProcedure); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.TYPE_DECLARATION: { TypeDeclaration typeDeclaration = (TypeDeclaration)theEObject; T result = caseTypeDeclaration(typeDeclaration); if (result == null) result = caseDeclaration(typeDeclaration); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.VAR_BLOCK: { VarBlock varBlock = (VarBlock)theEObject; T result = caseVarBlock(varBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ENUM_TYPE_DEF: { EnumTypeDef enumTypeDef = (EnumTypeDef)theEObject; T result = caseEnumTypeDef(enumTypeDef); if (result == null) result = caseTypeDeclaration(enumTypeDef); if (result == null) result = caseDeclaration(enumTypeDef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ENUM_VALUE: { EnumValue enumValue = (EnumValue)theEObject; T result = caseEnumValue(enumValue); if (result == null) result = caseVariableRef(enumValue); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_TYPE_DEF: { RecordTypeDef recordTypeDef = (RecordTypeDef)theEObject; T result = caseRecordTypeDef(recordTypeDef); if (result == null) result = caseTypeDeclaration(recordTypeDef); if (result == null) result = caseDeclaration(recordTypeDef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ARRAY_TYPE_DEF: { ArrayTypeDef arrayTypeDef = (ArrayTypeDef)theEObject; T result = caseArrayTypeDef(arrayTypeDef); if (result == null) result = caseTypeDeclaration(arrayTypeDef); if (result == null) result = caseDeclaration(arrayTypeDef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ABSTRACT_TYPE_DEF: { AbstractTypeDef abstractTypeDef = (AbstractTypeDef)theEObject; T result = caseAbstractTypeDef(abstractTypeDef); if (result == null) result = caseTypeDeclaration(abstractTypeDef); if (result == null) result = caseDeclaration(abstractTypeDef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_FIELD_TYPE: { RecordFieldType recordFieldType = (RecordFieldType)theEObject; T result = caseRecordFieldType(recordFieldType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.CONSTANT_DECLARATION: { ConstantDeclaration constantDeclaration = (ConstantDeclaration)theEObject; T result = caseConstantDeclaration(constantDeclaration); if (result == null) result = caseDeclaration(constantDeclaration); if (result == null) result = caseVariableRef(constantDeclaration); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.GLOBAL_DECLARATION: { GlobalDeclaration globalDeclaration = (GlobalDeclaration)theEObject; T result = caseGlobalDeclaration(globalDeclaration); if (result == null) result = caseDeclaration(globalDeclaration); if (result == null) result = caseVariableRef(globalDeclaration); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.VARIABLE_REF: { VariableRef variableRef = (VariableRef)theEObject; T result = caseVariableRef(variableRef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.INPUT_ARG_LIST: { InputArgList inputArgList = (InputArgList)theEObject; T result = caseInputArgList(inputArgList); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.INPUT_ARG: { InputArg inputArg = (InputArg)theEObject; T result = caseInputArg(inputArg); if (result == null) result = caseVariableRef(inputArg); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.LOCAL_ARG: { LocalArg localArg = (LocalArg)theEObject; T result = caseLocalArg(localArg); if (result == null) result = caseVariableRef(localArg); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.OUTPUT_ARG_LIST: { OutputArgList outputArgList = (OutputArgList)theEObject; T result = caseOutputArgList(outputArgList); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.OUTPUT_ARG: { OutputArg outputArg = (OutputArg)theEObject; T result = caseOutputArg(outputArg); if (result == null) result = caseVariableRef(outputArg); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.TYPE: { Type type = (Type)theEObject; T result = caseType(type); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ATTRIBUTE_BLOCK: { AttributeBlock attributeBlock = (AttributeBlock)theEObject; T result = caseAttributeBlock(attributeBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ATTRIBUTE: { Attribute attribute = (Attribute)theEObject; T result = caseAttribute(attribute); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.PRECONDITION: { Precondition precondition = (Precondition)theEObject; T result = casePrecondition(precondition); if (result == null) result = caseAttribute(precondition); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.POSTCONDITION: { Postcondition postcondition = (Postcondition)theEObject; T result = casePostcondition(postcondition); if (result == null) result = caseAttribute(postcondition); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.DEFINE_USE_REF: { DefineUseRef defineUseRef = (DefineUseRef)theEObject; T result = caseDefineUseRef(defineUseRef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.DEFINE: { Define define = (Define)theEObject; T result = caseDefine(define); if (result == null) result = caseAttribute(define); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.USES: { Uses uses = (Uses)theEObject; T result = caseUses(uses); if (result == null) result = caseAttribute(uses); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.STATEMENT_BLOCK: { StatementBlock statementBlock = (StatementBlock)theEObject; T result = caseStatementBlock(statementBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.STATEMENT: { Statement statement = (Statement)theEObject; T result = caseStatement(statement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.VOID_STATEMENT: { VoidStatement voidStatement = (VoidStatement)theEObject; T result = caseVoidStatement(voidStatement); if (result == null) result = caseStatement(voidStatement); if (result == null) result = caseEquation(voidStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ASSIGNMENT_STATEMENT: { AssignmentStatement assignmentStatement = (AssignmentStatement)theEObject; T result = caseAssignmentStatement(assignmentStatement); if (result == null) result = caseStatement(assignmentStatement); if (result == null) result = caseEquation(assignmentStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.IF_THEN_ELSE_STATEMENT: { IfThenElseStatement ifThenElseStatement = (IfThenElseStatement)theEObject; T result = caseIfThenElseStatement(ifThenElseStatement); if (result == null) result = caseStatement(ifThenElseStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ELSE: { Else else_ = (Else)theEObject; T result = caseElse(else_); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.WHILE_STATEMENT: { WhileStatement whileStatement = (WhileStatement)theEObject; T result = caseWhileStatement(whileStatement); if (result == null) result = caseStatement(whileStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.FOR_STATEMENT: { ForStatement forStatement = (ForStatement)theEObject; T result = caseForStatement(forStatement); if (result == null) result = caseStatement(forStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.LABEL_STATEMENT: { LabelStatement labelStatement = (LabelStatement)theEObject; T result = caseLabelStatement(labelStatement); if (result == null) result = caseStatement(labelStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.GOTO_STATEMENT: { GotoStatement gotoStatement = (GotoStatement)theEObject; T result = caseGotoStatement(gotoStatement); if (result == null) result = caseStatement(gotoStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.EQUATION_BLOCK: { EquationBlock equationBlock = (EquationBlock)theEObject; T result = caseEquationBlock(equationBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.EQUATION: { Equation equation = (Equation)theEObject; T result = caseEquation(equation); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ID_LIST: { IdList idList = (IdList)theEObject; T result = caseIdList(idList); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.EXPR: { Expr expr = (Expr)theEObject; T result = caseExpr(expr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.FUNCTION_REF: { FunctionRef functionRef = (FunctionRef)theEObject; T result = caseFunctionRef(functionRef); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ARRAY_EXPR: { ArrayExpr arrayExpr = (ArrayExpr)theEObject; T result = caseArrayExpr(arrayExpr); if (result == null) result = caseExpr(arrayExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_EXPR: { RecordExpr recordExpr = (RecordExpr)theEObject; T result = caseRecordExpr(recordExpr); if (result == null) result = caseExpr(recordExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_FIELD_EXPR: { RecordFieldExpr recordFieldExpr = (RecordFieldExpr)theEObject; T result = caseRecordFieldExpr(recordFieldExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.EXPR_LIST: { ExprList exprList = (ExprList)theEObject; T result = caseExprList(exprList); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.TYPE_ALIAS: { TypeAlias typeAlias = (TypeAlias)theEObject; T result = caseTypeAlias(typeAlias); if (result == null) result = caseTypeDeclaration(typeAlias); if (result == null) result = caseDeclaration(typeAlias); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.SOME_VAR_BLOCK: { SomeVarBlock someVarBlock = (SomeVarBlock)theEObject; T result = caseSomeVarBlock(someVarBlock); if (result == null) result = caseVarBlock(someVarBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.NO_VAR_BLOCK: { NoVarBlock noVarBlock = (NoVarBlock)theEObject; T result = caseNoVarBlock(noVarBlock); if (result == null) result = caseVarBlock(noVarBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.VOID_TYPE: { VoidType voidType = (VoidType)theEObject; T result = caseVoidType(voidType); if (result == null) result = caseType(voidType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.BOOL_TYPE: { BoolType boolType = (BoolType)theEObject; T result = caseBoolType(boolType); if (result == null) result = caseType(boolType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.INTEGER_TYPE: { IntegerType integerType = (IntegerType)theEObject; T result = caseIntegerType(integerType); if (result == null) result = caseType(integerType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.REAL_TYPE: { RealType realType = (RealType)theEObject; T result = caseRealType(realType); if (result == null) result = caseType(realType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.STRING_TYPE: { StringType stringType = (StringType)theEObject; T result = caseStringType(stringType); if (result == null) result = caseType(stringType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ENUM_TYPE: { EnumType enumType = (EnumType)theEObject; T result = caseEnumType(enumType); if (result == null) result = caseType(enumType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_TYPE: { RecordType recordType = (RecordType)theEObject; T result = caseRecordType(recordType); if (result == null) result = caseType(recordType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ARRAY_TYPE: { ArrayType arrayType = (ArrayType)theEObject; T result = caseArrayType(arrayType); if (result == null) result = caseType(arrayType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ABSTRACT_TYPE: { AbstractType abstractType = (AbstractType)theEObject; T result = caseAbstractType(abstractType); if (result == null) result = caseType(abstractType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.NAMED_TYPE: { NamedType namedType = (NamedType)theEObject; T result = caseNamedType(namedType); if (result == null) result = caseType(namedType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.SOME_ATTRIBUTE_BLOCK: { SomeAttributeBlock someAttributeBlock = (SomeAttributeBlock)theEObject; T result = caseSomeAttributeBlock(someAttributeBlock); if (result == null) result = caseAttributeBlock(someAttributeBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.NO_ATTRIBUTE_BLOCK: { NoAttributeBlock noAttributeBlock = (NoAttributeBlock)theEObject; T result = caseNoAttributeBlock(noAttributeBlock); if (result == null) result = caseAttributeBlock(noAttributeBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.BREAK_STATEMENT: { BreakStatement breakStatement = (BreakStatement)theEObject; T result = caseBreakStatement(breakStatement); if (result == null) result = caseStatement(breakStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.CONTINUE_STATEMENT: { ContinueStatement continueStatement = (ContinueStatement)theEObject; T result = caseContinueStatement(continueStatement); if (result == null) result = caseStatement(continueStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RETURN_STATEMENT: { ReturnStatement returnStatement = (ReturnStatement)theEObject; T result = caseReturnStatement(returnStatement); if (result == null) result = caseStatement(returnStatement); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ELSE_BLOCK: { ElseBlock elseBlock = (ElseBlock)theEObject; T result = caseElseBlock(elseBlock); if (result == null) result = caseElse(elseBlock); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ELSE_IF: { ElseIf elseIf = (ElseIf)theEObject; T result = caseElseIf(elseIf); if (result == null) result = caseElse(elseIf); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.NO_ELSE: { NoElse noElse = (NoElse)theEObject; T result = caseNoElse(noElse); if (result == null) result = caseElse(noElse); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.IF_THEN_ELSE_EXPR: { IfThenElseExpr ifThenElseExpr = (IfThenElseExpr)theEObject; T result = caseIfThenElseExpr(ifThenElseExpr); if (result == null) result = caseExpr(ifThenElseExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.CHOICE_EXPR: { ChoiceExpr choiceExpr = (ChoiceExpr)theEObject; T result = caseChoiceExpr(choiceExpr); if (result == null) result = caseExpr(choiceExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.BINARY_EXPR: { BinaryExpr binaryExpr = (BinaryExpr)theEObject; T result = caseBinaryExpr(binaryExpr); if (result == null) result = caseExpr(binaryExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.UNARY_NEGATION_EXPR: { UnaryNegationExpr unaryNegationExpr = (UnaryNegationExpr)theEObject; T result = caseUnaryNegationExpr(unaryNegationExpr); if (result == null) result = caseExpr(unaryNegationExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.UNARY_MINUS_EXPR: { UnaryMinusExpr unaryMinusExpr = (UnaryMinusExpr)theEObject; T result = caseUnaryMinusExpr(unaryMinusExpr); if (result == null) result = caseExpr(unaryMinusExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_ACCESS_EXPR: { RecordAccessExpr recordAccessExpr = (RecordAccessExpr)theEObject; T result = caseRecordAccessExpr(recordAccessExpr); if (result == null) result = caseExpr(recordAccessExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.RECORD_UPDATE_EXPR: { RecordUpdateExpr recordUpdateExpr = (RecordUpdateExpr)theEObject; T result = caseRecordUpdateExpr(recordUpdateExpr); if (result == null) result = caseExpr(recordUpdateExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ARRAY_ACCESS_EXPR: { ArrayAccessExpr arrayAccessExpr = (ArrayAccessExpr)theEObject; T result = caseArrayAccessExpr(arrayAccessExpr); if (result == null) result = caseExpr(arrayAccessExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ARRAY_UPDATE_EXPR: { ArrayUpdateExpr arrayUpdateExpr = (ArrayUpdateExpr)theEObject; T result = caseArrayUpdateExpr(arrayUpdateExpr); if (result == null) result = caseExpr(arrayUpdateExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.BOOLEAN_LITERAL_EXPR: { BooleanLiteralExpr booleanLiteralExpr = (BooleanLiteralExpr)theEObject; T result = caseBooleanLiteralExpr(booleanLiteralExpr); if (result == null) result = caseExpr(booleanLiteralExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.INTEGER_LITERAL_EXPR: { IntegerLiteralExpr integerLiteralExpr = (IntegerLiteralExpr)theEObject; T result = caseIntegerLiteralExpr(integerLiteralExpr); if (result == null) result = caseExpr(integerLiteralExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.INTEGER_WILD_CARD_EXPR: { IntegerWildCardExpr integerWildCardExpr = (IntegerWildCardExpr)theEObject; T result = caseIntegerWildCardExpr(integerWildCardExpr); if (result == null) result = caseExpr(integerWildCardExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.REAL_LITERAL_EXPR: { RealLiteralExpr realLiteralExpr = (RealLiteralExpr)theEObject; T result = caseRealLiteralExpr(realLiteralExpr); if (result == null) result = caseExpr(realLiteralExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.STRING_LITERAL_EXPR: { StringLiteralExpr stringLiteralExpr = (StringLiteralExpr)theEObject; T result = caseStringLiteralExpr(stringLiteralExpr); if (result == null) result = caseExpr(stringLiteralExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.INIT_EXPR: { InitExpr initExpr = (InitExpr)theEObject; T result = caseInitExpr(initExpr); if (result == null) result = caseExpr(initExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.SECOND_INIT: { SecondInit secondInit = (SecondInit)theEObject; T result = caseSecondInit(secondInit); if (result == null) result = caseExpr(secondInit); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.ID_EXPR: { IdExpr idExpr = (IdExpr)theEObject; T result = caseIdExpr(idExpr); if (result == null) result = caseExpr(idExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.FCN_CALL_EXPR: { FcnCallExpr fcnCallExpr = (FcnCallExpr)theEObject; T result = caseFcnCallExpr(fcnCallExpr); if (result == null) result = caseExpr(fcnCallExpr); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.TUPLE_TYPE: { TupleType tupleType = (TupleType)theEObject; T result = caseTupleType(tupleType); if (result == null) result = caseType(tupleType); if (result == null) result = defaultCase(theEObject); return result; } case LimpPackage.FRESH_VARIABLE: { FreshVariable freshVariable = (FreshVariable)theEObject; T result = caseFreshVariable(freshVariable); if (result == null) result = caseExpr(freshVariable); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Specification</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Specification</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSpecification(Specification object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Declaration</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Declaration</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDeclaration(Declaration object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Comment</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Comment</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseComment(Comment object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Import</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Import</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseImport(Import object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>External Function</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>External Function</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExternalFunction(ExternalFunction object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>External Procedure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>External Procedure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExternalProcedure(ExternalProcedure object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Local Function</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Local Function</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLocalFunction(LocalFunction object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Local Procedure</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Local Procedure</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLocalProcedure(LocalProcedure object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Type Declaration</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Type Declaration</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTypeDeclaration(TypeDeclaration object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Var Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Var Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseVarBlock(VarBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Enum Type Def</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Enum Type Def</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEnumTypeDef(EnumTypeDef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Enum Value</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Enum Value</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEnumValue(EnumValue object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Type Def</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Type Def</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordTypeDef(RecordTypeDef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Array Type Def</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Array Type Def</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseArrayTypeDef(ArrayTypeDef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Abstract Type Def</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Abstract Type Def</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAbstractTypeDef(AbstractTypeDef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Field Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Field Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordFieldType(RecordFieldType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Constant Declaration</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Constant Declaration</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseConstantDeclaration(ConstantDeclaration object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Global Declaration</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Global Declaration</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseGlobalDeclaration(GlobalDeclaration object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Variable Ref</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Variable Ref</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseVariableRef(VariableRef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Input Arg List</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Input Arg List</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInputArgList(InputArgList object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Input Arg</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Input Arg</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInputArg(InputArg object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Local Arg</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Local Arg</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLocalArg(LocalArg object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Output Arg List</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Output Arg List</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOutputArgList(OutputArgList object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Output Arg</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Output Arg</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOutputArg(OutputArg object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseType(Type object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Attribute Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Attribute Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAttributeBlock(AttributeBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Attribute</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Attribute</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAttribute(Attribute object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Precondition</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Precondition</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePrecondition(Precondition object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Postcondition</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Postcondition</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePostcondition(Postcondition object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Define Use Ref</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Define Use Ref</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDefineUseRef(DefineUseRef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Define</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Define</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDefine(Define object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Uses</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Uses</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseUses(Uses object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Statement Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Statement Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStatementBlock(StatementBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStatement(Statement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Void Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Void Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseVoidStatement(VoidStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Assignment Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Assignment Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAssignmentStatement(AssignmentStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>If Then Else Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>If Then Else Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIfThenElseStatement(IfThenElseStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Else</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Else</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseElse(Else object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>While Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>While Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWhileStatement(WhileStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>For Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>For Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseForStatement(ForStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Label Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Label Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLabelStatement(LabelStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Goto Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Goto Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseGotoStatement(GotoStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Equation Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Equation Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEquationBlock(EquationBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Equation</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Equation</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEquation(Equation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Id List</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Id List</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIdList(IdList object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExpr(Expr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Function Ref</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Function Ref</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionRef(FunctionRef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Array Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Array Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseArrayExpr(ArrayExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordExpr(RecordExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Field Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Field Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordFieldExpr(RecordFieldExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Expr List</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Expr List</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExprList(ExprList object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Type Alias</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Type Alias</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTypeAlias(TypeAlias object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Some Var Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Some Var Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSomeVarBlock(SomeVarBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>No Var Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>No Var Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNoVarBlock(NoVarBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Void Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Void Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseVoidType(VoidType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Bool Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Bool Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBoolType(BoolType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Integer Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Integer Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIntegerType(IntegerType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Real Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Real Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRealType(RealType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>String Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>String Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStringType(StringType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Enum Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Enum Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEnumType(EnumType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordType(RecordType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Array Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Array Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseArrayType(ArrayType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Abstract Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Abstract Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAbstractType(AbstractType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Named Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Named Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNamedType(NamedType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Some Attribute Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Some Attribute Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSomeAttributeBlock(SomeAttributeBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>No Attribute Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>No Attribute Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNoAttributeBlock(NoAttributeBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Break Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Break Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBreakStatement(BreakStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Continue Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Continue Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseContinueStatement(ContinueStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Return Statement</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Return Statement</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseReturnStatement(ReturnStatement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Else Block</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Else Block</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseElseBlock(ElseBlock object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Else If</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Else If</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseElseIf(ElseIf object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>No Else</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>No Else</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNoElse(NoElse object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>If Then Else Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>If Then Else Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIfThenElseExpr(IfThenElseExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Choice Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Choice Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseChoiceExpr(ChoiceExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Binary Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Binary Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBinaryExpr(BinaryExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Unary Negation Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Unary Negation Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseUnaryNegationExpr(UnaryNegationExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Unary Minus Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Unary Minus Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseUnaryMinusExpr(UnaryMinusExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Access Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Access Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordAccessExpr(RecordAccessExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Record Update Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Record Update Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRecordUpdateExpr(RecordUpdateExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Array Access Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Array Access Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseArrayAccessExpr(ArrayAccessExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Array Update Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Array Update Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseArrayUpdateExpr(ArrayUpdateExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Boolean Literal Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Boolean Literal Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBooleanLiteralExpr(BooleanLiteralExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Integer Literal Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Integer Literal Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIntegerLiteralExpr(IntegerLiteralExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Integer Wild Card Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Integer Wild Card Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIntegerWildCardExpr(IntegerWildCardExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Real Literal Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Real Literal Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRealLiteralExpr(RealLiteralExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>String Literal Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>String Literal Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStringLiteralExpr(StringLiteralExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Init Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Init Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInitExpr(InitExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Second Init</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Second Init</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSecondInit(SecondInit object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Id Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Id Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseIdExpr(IdExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Fcn Call Expr</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Fcn Call Expr</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFcnCallExpr(FcnCallExpr object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Tuple Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Tuple Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTupleType(TupleType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Fresh Variable</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Fresh Variable</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFreshVariable(FreshVariable object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //LimpSwitch
package br.com.scd.demo.api.topic; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.scd.demo.api.topic.dto.TopicRequest; import br.com.scd.demo.api.topic.dto.TopicResponse; import br.com.scd.demo.api.topic.dto.TopicResponseFactory; import br.com.scd.demo.api.topic.dto.TopicResultResponse; import br.com.scd.demo.api.topic.dto.TopicResultResponseFactory; import br.com.scd.demo.topic.Topic; import br.com.scd.demo.topic.TopicForInsert; import br.com.scd.demo.topic.TopicForInsertFactory; import br.com.scd.demo.topic.TopicResult; import br.com.scd.demo.topic.TopicService; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; @Slf4j @RestController @RequestMapping("/topics") public class TopicApi { @Autowired private TopicService topicService; @PostMapping @ApiOperation("Cadastrar pauta de votação.") public ResponseEntity<TopicResponse> save(@RequestBody @Valid TopicRequest request) { log.info("Cadastrando pauta de votação: {}", request); TopicForInsert topicForInsert = TopicForInsertFactory.getInstance(request); Topic topic = topicService.save(topicForInsert); TopicResponse response = TopicResponseFactory.getInstance(topic); log.info("Cadastrada pauta de votação: {}", response); return ResponseEntity.ok(response); } @GetMapping("/result/{topicId}") @ApiOperation("Resultado de votos de uma pauta.") public ResponseEntity<TopicResultResponse> getTopicResult(@PathVariable Long topicId) { log.info("Verificando o resultado da pauta de votação id: {}", topicId); TopicResult topicResult = topicService.findByIdWithSessionResult(topicId); TopicResultResponse topicResultResponse = TopicResultResponseFactory.getInstance(topicResult); log.info("Resultado da pauta de votação: {}", topicResultResponse); return ResponseEntity.ok(topicResultResponse); } }
package com.handsomedong.dynamic.datasource.spring.boot.autoconfigure; import com.handsomedong.dynamic.datasource.spring.boot.autoconfigure.properties.DataSourceConfig; import com.handsomedong.dynamic.datasource.spring.boot.autoconfigure.properties.DruidDefaultProperty; import com.handsomedong.dynamic.datasource.spring.boot.autoconfigure.properties.HikariDefaultProperty; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Created by HandsomeDong on 2021/9/29 0:56 * 多数据源配置 */ @Data @ConfigurationProperties(prefix = "spring.dynamic.datasource") public class DynamicDataSourceProperties { /** * 默认数据源名称 */ private String defaultDatasourceKey = "default"; /** * jdbc驱动类 */ private String defaultDriverClassName = "com.mysql.jdbc.Driver"; /** * druid数据源默认配置项 */ private DruidDefaultProperty druidDefaultProperty = new DruidDefaultProperty(); /** * hikari数据源默认配置项 */ private HikariDefaultProperty hikariDefaultProperty = new HikariDefaultProperty(); /** * 所有数据源配置 */ private DataSourceConfig dynamicDataSource = new DataSourceConfig(); }
package com.ajou.visualization.model; public class SimilarityPerson { private String MjMwMzEyLTE4MjkyMTQg; private String MjkxMTIwLTIwMzY1MTQg; private String MjkwMjI2LTEwNTg0MTcg; private String MzAwMTI0LTIwMDU3MTYg; private String MzcwMTA1LTI1NTE0MTMg; private String MzcwNDAxLTExNDk0MTUg; private String MzExMTExLTIwMzc5MjEg; private String MzIwNjA3LTIwNDIxMjgg; private String MzIxMjI5LTIxNjkzMTUg; private String MzkwNTAxLTEwNzQzNDEg; private String MzMwMjI1LTIwMDA3MTEg; private String MzMxMTA3LTIwNjkwMTAg; private String MzQwMjIxLTI3Nzc4MTEg; private String MzUwMjE1LTIwMTkyMjgg; private String MzYwMzA4LTIwNzQ0MTcg; private String NDcwMzE1LTIxMDYyMjgg; private String NDEwODI1LTE3OTgxMTEg; private String NDExMjE1LTE0NjY3Mjkg; private String NDEwMTIwLTExNjIzMTgg; private String MzYwMTIwLTIwMzczMTkg; private String MzUxMjA1LTI1NTI3MTcg; private String MzIwOTE4LTExNjMwMTMg; private String MzAwNjIyLTIwNTExMjUg; private String MzAwNjIxLTEwMTc0MTMg; private String MjUwMjAxLTEwMjU0MTQg; private String MjkwOTI1LTI3MDE2MTgg; private String MjkwODE3LTEwNjk1MTEg; private String MjcwODE1LTEwNjM2MTEg; private String MjgwNjA2LTIwNjM2MTAg; private String MzYwNTIxLTEwNDE5MTQg; private String NDAxMDE1LTEyMzE3MTEg; private String NTAwMzIyLTI4MDc4Mjcg; private String NDIxMjEyLTIwMjM1MTgg; private String MzYxMDAxLTE1NDI5MjYg; private String MzUxMjAyLTIwNDIyMTcg; private String MzIwNzAxLTIwNDI0MTUg; private String MzIwNjEyLTEwNDc3MTEg; private String MzgwNDI1LTIwMTc3MTcg; private String MzgwMjA0LTIyMjk4MTYg; private String MzEwOTI0LTIwMzYxMTEg; private String MzAwODA3LTEwMDU4MTAg; private String MzAwNzMwLTE0NzA2MTgg; private String MjkwNDE3LTIzNTc1MTQg; private String MjkwMTAxLTIwMzc0Mjkg; private String MjgxMjMwLTExMTEwMTEg; private String MjkwMjI2LTIwMzcyMjkg; private String MzYwOTE1LTI4OTQ0MTQg; private String NDAwOTIwLTEwMjM1MjUg; private String NDEwNjAyLTExMDA3MTUg; private String NDgwNzA5LTI4MTQ2MTMg; private String NDMwOTAyLTEwMTEyMTgg; private String NDMxMTEwLTIxMTk4MTkg; private String NTQwODA4LTE5MzA0MTgg; private String NDkxMjE1LTIwNTYyMzgg; private String NDMwMzIzLTEwNDI3MTEg; private String MzYxMjAyLTIxMDg3MTkg; private String MzUwMTAxLTIwMDAzMTEg; private String MjkwNDA5LTEwMzc4Mjcg; private String NDcxMTE2LTIwNTI0MTQg; private String MzMxMjAyLTIwNjY5MTIg; private String MzEwODI4LTI5MjcyMTEg; private String MzAxMDI4LTI0ODExMTcg; private String NDEwODEzLTI0NzE2MTEg; public SimilarityPerson(){} public String getMjMwMzEyLTE4MjkyMTQg() { return MjMwMzEyLTE4MjkyMTQg; } public void setMjMwMzEyLTE4MjkyMTQg(String mjMwMzEyLTE4MjkyMTQg) { MjMwMzEyLTE4MjkyMTQg = mjMwMzEyLTE4MjkyMTQg; } public String getMjkxMTIwLTIwMzY1MTQg() { return MjkxMTIwLTIwMzY1MTQg; } public void setMjkxMTIwLTIwMzY1MTQg(String mjkxMTIwLTIwMzY1MTQg) { MjkxMTIwLTIwMzY1MTQg = mjkxMTIwLTIwMzY1MTQg; } public String getMjkwMjI2LTEwNTg0MTcg() { return MjkwMjI2LTEwNTg0MTcg; } public void setMjkwMjI2LTEwNTg0MTcg(String mjkwMjI2LTEwNTg0MTcg) { MjkwMjI2LTEwNTg0MTcg = mjkwMjI2LTEwNTg0MTcg; } public String getMzAwMTI0LTIwMDU3MTYg() { return MzAwMTI0LTIwMDU3MTYg; } public void setMzAwMTI0LTIwMDU3MTYg(String mzAwMTI0LTIwMDU3MTYg) { MzAwMTI0LTIwMDU3MTYg = mzAwMTI0LTIwMDU3MTYg; } public String getMzcwMTA1LTI1NTE0MTMg() { return MzcwMTA1LTI1NTE0MTMg; } public void setMzcwMTA1LTI1NTE0MTMg(String mzcwMTA1LTI1NTE0MTMg) { MzcwMTA1LTI1NTE0MTMg = mzcwMTA1LTI1NTE0MTMg; } public String getMzcwNDAxLTExNDk0MTUg() { return MzcwNDAxLTExNDk0MTUg; } public void setMzcwNDAxLTExNDk0MTUg(String mzcwNDAxLTExNDk0MTUg) { MzcwNDAxLTExNDk0MTUg = mzcwNDAxLTExNDk0MTUg; } public String getMzExMTExLTIwMzc5MjEg() { return MzExMTExLTIwMzc5MjEg; } public void setMzExMTExLTIwMzc5MjEg(String mzExMTExLTIwMzc5MjEg) { MzExMTExLTIwMzc5MjEg = mzExMTExLTIwMzc5MjEg; } public String getMzIwNjA3LTIwNDIxMjgg() { return MzIwNjA3LTIwNDIxMjgg; } public void setMzIwNjA3LTIwNDIxMjgg(String mzIwNjA3LTIwNDIxMjgg) { MzIwNjA3LTIwNDIxMjgg = mzIwNjA3LTIwNDIxMjgg; } public String getMzIxMjI5LTIxNjkzMTUg() { return MzIxMjI5LTIxNjkzMTUg; } public void setMzIxMjI5LTIxNjkzMTUg(String mzIxMjI5LTIxNjkzMTUg) { MzIxMjI5LTIxNjkzMTUg = mzIxMjI5LTIxNjkzMTUg; } public String getMzkwNTAxLTEwNzQzNDEg() { return MzkwNTAxLTEwNzQzNDEg; } public void setMzkwNTAxLTEwNzQzNDEg(String mzkwNTAxLTEwNzQzNDEg) { MzkwNTAxLTEwNzQzNDEg = mzkwNTAxLTEwNzQzNDEg; } public String getMzMwMjI1LTIwMDA3MTEg() { return MzMwMjI1LTIwMDA3MTEg; } public void setMzMwMjI1LTIwMDA3MTEg(String mzMwMjI1LTIwMDA3MTEg) { MzMwMjI1LTIwMDA3MTEg = mzMwMjI1LTIwMDA3MTEg; } public String getMzMxMTA3LTIwNjkwMTAg() { return MzMxMTA3LTIwNjkwMTAg; } public void setMzMxMTA3LTIwNjkwMTAg(String mzMxMTA3LTIwNjkwMTAg) { MzMxMTA3LTIwNjkwMTAg = mzMxMTA3LTIwNjkwMTAg; } public String getMzQwMjIxLTI3Nzc4MTEg() { return MzQwMjIxLTI3Nzc4MTEg; } public void setMzQwMjIxLTI3Nzc4MTEg(String mzQwMjIxLTI3Nzc4MTEg) { MzQwMjIxLTI3Nzc4MTEg = mzQwMjIxLTI3Nzc4MTEg; } public String getMzUwMjE1LTIwMTkyMjgg() { return MzUwMjE1LTIwMTkyMjgg; } public void setMzUwMjE1LTIwMTkyMjgg(String mzUwMjE1LTIwMTkyMjgg) { MzUwMjE1LTIwMTkyMjgg = mzUwMjE1LTIwMTkyMjgg; } public String getMzYwMzA4LTIwNzQ0MTcg() { return MzYwMzA4LTIwNzQ0MTcg; } public void setMzYwMzA4LTIwNzQ0MTcg(String mzYwMzA4LTIwNzQ0MTcg) { MzYwMzA4LTIwNzQ0MTcg = mzYwMzA4LTIwNzQ0MTcg; } public String getNDcwMzE1LTIxMDYyMjgg() { return NDcwMzE1LTIxMDYyMjgg; } public void setNDcwMzE1LTIxMDYyMjgg(String nDcwMzE1LTIxMDYyMjgg) { NDcwMzE1LTIxMDYyMjgg = nDcwMzE1LTIxMDYyMjgg; } public String getNDEwODI1LTE3OTgxMTEg() { return NDEwODI1LTE3OTgxMTEg; } public void setNDEwODI1LTE3OTgxMTEg(String nDEwODI1LTE3OTgxMTEg) { NDEwODI1LTE3OTgxMTEg = nDEwODI1LTE3OTgxMTEg; } public String getNDExMjE1LTE0NjY3Mjkg() { return NDExMjE1LTE0NjY3Mjkg; } public void setNDExMjE1LTE0NjY3Mjkg(String nDExMjE1LTE0NjY3Mjkg) { NDExMjE1LTE0NjY3Mjkg = nDExMjE1LTE0NjY3Mjkg; } public String getNDEwMTIwLTExNjIzMTgg() { return NDEwMTIwLTExNjIzMTgg; } public void setNDEwMTIwLTExNjIzMTgg(String nDEwMTIwLTExNjIzMTgg) { NDEwMTIwLTExNjIzMTgg = nDEwMTIwLTExNjIzMTgg; } public String getMzYwMTIwLTIwMzczMTkg() { return MzYwMTIwLTIwMzczMTkg; } public void setMzYwMTIwLTIwMzczMTkg(String mzYwMTIwLTIwMzczMTkg) { MzYwMTIwLTIwMzczMTkg = mzYwMTIwLTIwMzczMTkg; } public String getMzUxMjA1LTI1NTI3MTcg() { return MzUxMjA1LTI1NTI3MTcg; } public void setMzUxMjA1LTI1NTI3MTcg(String mzUxMjA1LTI1NTI3MTcg) { MzUxMjA1LTI1NTI3MTcg = mzUxMjA1LTI1NTI3MTcg; } public String getMzIwOTE4LTExNjMwMTMg() { return MzIwOTE4LTExNjMwMTMg; } public void setMzIwOTE4LTExNjMwMTMg(String mzIwOTE4LTExNjMwMTMg) { MzIwOTE4LTExNjMwMTMg = mzIwOTE4LTExNjMwMTMg; } public String getMzAwNjIyLTIwNTExMjUg() { return MzAwNjIyLTIwNTExMjUg; } public void setMzAwNjIyLTIwNTExMjUg(String mzAwNjIyLTIwNTExMjUg) { MzAwNjIyLTIwNTExMjUg = mzAwNjIyLTIwNTExMjUg; } public String getMzAwNjIxLTEwMTc0MTMg() { return MzAwNjIxLTEwMTc0MTMg; } public void setMzAwNjIxLTEwMTc0MTMg(String mzAwNjIxLTEwMTc0MTMg) { MzAwNjIxLTEwMTc0MTMg = mzAwNjIxLTEwMTc0MTMg; } public String getMjUwMjAxLTEwMjU0MTQg() { return MjUwMjAxLTEwMjU0MTQg; } public void setMjUwMjAxLTEwMjU0MTQg(String mjUwMjAxLTEwMjU0MTQg) { MjUwMjAxLTEwMjU0MTQg = mjUwMjAxLTEwMjU0MTQg; } public String getMjkwOTI1LTI3MDE2MTgg() { return MjkwOTI1LTI3MDE2MTgg; } public void setMjkwOTI1LTI3MDE2MTgg(String mjkwOTI1LTI3MDE2MTgg) { MjkwOTI1LTI3MDE2MTgg = mjkwOTI1LTI3MDE2MTgg; } public String getMjkwODE3LTEwNjk1MTEg() { return MjkwODE3LTEwNjk1MTEg; } public void setMjkwODE3LTEwNjk1MTEg(String mjkwODE3LTEwNjk1MTEg) { MjkwODE3LTEwNjk1MTEg = mjkwODE3LTEwNjk1MTEg; } public String getMjcwODE1LTEwNjM2MTEg() { return MjcwODE1LTEwNjM2MTEg; } public void setMjcwODE1LTEwNjM2MTEg(String mjcwODE1LTEwNjM2MTEg) { MjcwODE1LTEwNjM2MTEg = mjcwODE1LTEwNjM2MTEg; } public String getMjgwNjA2LTIwNjM2MTAg() { return MjgwNjA2LTIwNjM2MTAg; } public void setMjgwNjA2LTIwNjM2MTAg(String mjgwNjA2LTIwNjM2MTAg) { MjgwNjA2LTIwNjM2MTAg = mjgwNjA2LTIwNjM2MTAg; } public String getMzYwNTIxLTEwNDE5MTQg() { return MzYwNTIxLTEwNDE5MTQg; } public void setMzYwNTIxLTEwNDE5MTQg(String mzYwNTIxLTEwNDE5MTQg) { MzYwNTIxLTEwNDE5MTQg = mzYwNTIxLTEwNDE5MTQg; } public String getNDAxMDE1LTEyMzE3MTEg() { return NDAxMDE1LTEyMzE3MTEg; } public void setNDAxMDE1LTEyMzE3MTEg(String nDAxMDE1LTEyMzE3MTEg) { NDAxMDE1LTEyMzE3MTEg = nDAxMDE1LTEyMzE3MTEg; } public String getNTAwMzIyLTI4MDc4Mjcg() { return NTAwMzIyLTI4MDc4Mjcg; } public void setNTAwMzIyLTI4MDc4Mjcg(String nTAwMzIyLTI4MDc4Mjcg) { NTAwMzIyLTI4MDc4Mjcg = nTAwMzIyLTI4MDc4Mjcg; } public String getNDIxMjEyLTIwMjM1MTgg() { return NDIxMjEyLTIwMjM1MTgg; } public void setNDIxMjEyLTIwMjM1MTgg(String nDIxMjEyLTIwMjM1MTgg) { NDIxMjEyLTIwMjM1MTgg = nDIxMjEyLTIwMjM1MTgg; } public String getMzYxMDAxLTE1NDI5MjYg() { return MzYxMDAxLTE1NDI5MjYg; } public void setMzYxMDAxLTE1NDI5MjYg(String mzYxMDAxLTE1NDI5MjYg) { MzYxMDAxLTE1NDI5MjYg = mzYxMDAxLTE1NDI5MjYg; } public String getMzUxMjAyLTIwNDIyMTcg() { return MzUxMjAyLTIwNDIyMTcg; } public void setMzUxMjAyLTIwNDIyMTcg(String mzUxMjAyLTIwNDIyMTcg) { MzUxMjAyLTIwNDIyMTcg = mzUxMjAyLTIwNDIyMTcg; } public String getMzIwNzAxLTIwNDI0MTUg() { return MzIwNzAxLTIwNDI0MTUg; } public void setMzIwNzAxLTIwNDI0MTUg(String mzIwNzAxLTIwNDI0MTUg) { MzIwNzAxLTIwNDI0MTUg = mzIwNzAxLTIwNDI0MTUg; } public String getMzIwNjEyLTEwNDc3MTEg() { return MzIwNjEyLTEwNDc3MTEg; } public void setMzIwNjEyLTEwNDc3MTEg(String mzIwNjEyLTEwNDc3MTEg) { MzIwNjEyLTEwNDc3MTEg = mzIwNjEyLTEwNDc3MTEg; } public String getMzgwNDI1LTIwMTc3MTcg() { return MzgwNDI1LTIwMTc3MTcg; } public void setMzgwNDI1LTIwMTc3MTcg(String mzgwNDI1LTIwMTc3MTcg) { MzgwNDI1LTIwMTc3MTcg = mzgwNDI1LTIwMTc3MTcg; } public String getMzgwMjA0LTIyMjk4MTYg() { return MzgwMjA0LTIyMjk4MTYg; } public void setMzgwMjA0LTIyMjk4MTYg(String mzgwMjA0LTIyMjk4MTYg) { MzgwMjA0LTIyMjk4MTYg = mzgwMjA0LTIyMjk4MTYg; } public String getMzEwOTI0LTIwMzYxMTEg() { return MzEwOTI0LTIwMzYxMTEg; } public void setMzEwOTI0LTIwMzYxMTEg(String mzEwOTI0LTIwMzYxMTEg) { MzEwOTI0LTIwMzYxMTEg = mzEwOTI0LTIwMzYxMTEg; } public String getMzAwODA3LTEwMDU4MTAg() { return MzAwODA3LTEwMDU4MTAg; } public void setMzAwODA3LTEwMDU4MTAg(String mzAwODA3LTEwMDU4MTAg) { MzAwODA3LTEwMDU4MTAg = mzAwODA3LTEwMDU4MTAg; } public String getMzAwNzMwLTE0NzA2MTgg() { return MzAwNzMwLTE0NzA2MTgg; } public void setMzAwNzMwLTE0NzA2MTgg(String mzAwNzMwLTE0NzA2MTgg) { MzAwNzMwLTE0NzA2MTgg = mzAwNzMwLTE0NzA2MTgg; } public String getMjkwNDE3LTIzNTc1MTQg() { return MjkwNDE3LTIzNTc1MTQg; } public void setMjkwNDE3LTIzNTc1MTQg(String mjkwNDE3LTIzNTc1MTQg) { MjkwNDE3LTIzNTc1MTQg = mjkwNDE3LTIzNTc1MTQg; } public String getMjkwMTAxLTIwMzc0Mjkg() { return MjkwMTAxLTIwMzc0Mjkg; } public void setMjkwMTAxLTIwMzc0Mjkg(String mjkwMTAxLTIwMzc0Mjkg) { MjkwMTAxLTIwMzc0Mjkg = mjkwMTAxLTIwMzc0Mjkg; } public String getMjgxMjMwLTExMTEwMTEg() { return MjgxMjMwLTExMTEwMTEg; } public void setMjgxMjMwLTExMTEwMTEg(String mjgxMjMwLTExMTEwMTEg) { MjgxMjMwLTExMTEwMTEg = mjgxMjMwLTExMTEwMTEg; } public String getMjkwMjI2LTIwMzcyMjkg() { return MjkwMjI2LTIwMzcyMjkg; } public void setMjkwMjI2LTIwMzcyMjkg(String mjkwMjI2LTIwMzcyMjkg) { MjkwMjI2LTIwMzcyMjkg = mjkwMjI2LTIwMzcyMjkg; } public String getMzYwOTE1LTI4OTQ0MTQg() { return MzYwOTE1LTI4OTQ0MTQg; } public void setMzYwOTE1LTI4OTQ0MTQg(String mzYwOTE1LTI4OTQ0MTQg) { MzYwOTE1LTI4OTQ0MTQg = mzYwOTE1LTI4OTQ0MTQg; } public String getNDAwOTIwLTEwMjM1MjUg() { return NDAwOTIwLTEwMjM1MjUg; } public void setNDAwOTIwLTEwMjM1MjUg(String nDAwOTIwLTEwMjM1MjUg) { NDAwOTIwLTEwMjM1MjUg = nDAwOTIwLTEwMjM1MjUg; } public String getNDEwNjAyLTExMDA3MTUg() { return NDEwNjAyLTExMDA3MTUg; } public void setNDEwNjAyLTExMDA3MTUg(String nDEwNjAyLTExMDA3MTUg) { NDEwNjAyLTExMDA3MTUg = nDEwNjAyLTExMDA3MTUg; } public String getNDgwNzA5LTI4MTQ2MTMg() { return NDgwNzA5LTI4MTQ2MTMg; } public void setNDgwNzA5LTI4MTQ2MTMg(String nDgwNzA5LTI4MTQ2MTMg) { NDgwNzA5LTI4MTQ2MTMg = nDgwNzA5LTI4MTQ2MTMg; } public String getNDMwOTAyLTEwMTEyMTgg() { return NDMwOTAyLTEwMTEyMTgg; } public void setNDMwOTAyLTEwMTEyMTgg(String nDMwOTAyLTEwMTEyMTgg) { NDMwOTAyLTEwMTEyMTgg = nDMwOTAyLTEwMTEyMTgg; } public String getNDMxMTEwLTIxMTk4MTkg() { return NDMxMTEwLTIxMTk4MTkg; } public void setNDMxMTEwLTIxMTk4MTkg(String nDMxMTEwLTIxMTk4MTkg) { NDMxMTEwLTIxMTk4MTkg = nDMxMTEwLTIxMTk4MTkg; } public String getNTQwODA4LTE5MzA0MTgg() { return NTQwODA4LTE5MzA0MTgg; } public void setNTQwODA4LTE5MzA0MTgg(String nTQwODA4LTE5MzA0MTgg) { NTQwODA4LTE5MzA0MTgg = nTQwODA4LTE5MzA0MTgg; } public String getNDkxMjE1LTIwNTYyMzgg() { return NDkxMjE1LTIwNTYyMzgg; } public void setNDkxMjE1LTIwNTYyMzgg(String nDkxMjE1LTIwNTYyMzgg) { NDkxMjE1LTIwNTYyMzgg = nDkxMjE1LTIwNTYyMzgg; } public String getNDMwMzIzLTEwNDI3MTEg() { return NDMwMzIzLTEwNDI3MTEg; } public void setNDMwMzIzLTEwNDI3MTEg(String nDMwMzIzLTEwNDI3MTEg) { NDMwMzIzLTEwNDI3MTEg = nDMwMzIzLTEwNDI3MTEg; } public String getMzYxMjAyLTIxMDg3MTkg() { return MzYxMjAyLTIxMDg3MTkg; } public void setMzYxMjAyLTIxMDg3MTkg(String mzYxMjAyLTIxMDg3MTkg) { MzYxMjAyLTIxMDg3MTkg = mzYxMjAyLTIxMDg3MTkg; } public String getMzUwMTAxLTIwMDAzMTEg() { return MzUwMTAxLTIwMDAzMTEg; } public void setMzUwMTAxLTIwMDAzMTEg(String mzUwMTAxLTIwMDAzMTEg) { MzUwMTAxLTIwMDAzMTEg = mzUwMTAxLTIwMDAzMTEg; } public String getMjkwNDA5LTEwMzc4Mjcg() { return MjkwNDA5LTEwMzc4Mjcg; } public void setMjkwNDA5LTEwMzc4Mjcg(String mjkwNDA5LTEwMzc4Mjcg) { MjkwNDA5LTEwMzc4Mjcg = mjkwNDA5LTEwMzc4Mjcg; } public String getNDcxMTE2LTIwNTI0MTQg() { return NDcxMTE2LTIwNTI0MTQg; } public void setNDcxMTE2LTIwNTI0MTQg(String nDcxMTE2LTIwNTI0MTQg) { NDcxMTE2LTIwNTI0MTQg = nDcxMTE2LTIwNTI0MTQg; } public String getMzMxMjAyLTIwNjY5MTIg() { return MzMxMjAyLTIwNjY5MTIg; } public void setMzMxMjAyLTIwNjY5MTIg(String mzMxMjAyLTIwNjY5MTIg) { MzMxMjAyLTIwNjY5MTIg = mzMxMjAyLTIwNjY5MTIg; } public String getMzEwODI4LTI5MjcyMTEg() { return MzEwODI4LTI5MjcyMTEg; } public void setMzEwODI4LTI5MjcyMTEg(String mzEwODI4LTI5MjcyMTEg) { MzEwODI4LTI5MjcyMTEg = mzEwODI4LTI5MjcyMTEg; } public String getMzAxMDI4LTI0ODExMTcg() { return MzAxMDI4LTI0ODExMTcg; } public void setMzAxMDI4LTI0ODExMTcg(String mzAxMDI4LTI0ODExMTcg) { MzAxMDI4LTI0ODExMTcg = mzAxMDI4LTI0ODExMTcg; } public String getNDEwODEzLTI0NzE2MTEg() { return NDEwODEzLTI0NzE2MTEg; } public void setNDEwODEzLTI0NzE2MTEg(String nDEwODEzLTI0NzE2MTEg) { NDEwODEzLTI0NzE2MTEg = nDEwODEzLTI0NzE2MTEg; } }
package org.newdawn.slick.tests; import org.newdawn.slick.AngelCodeFont; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Font; import org.newdawn.slick.Game; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class PureFontTest extends BasicGame { private Font font; private Image image; private static AppGameContainer container; public PureFontTest() { super("Hiero Font Test"); } public void init(GameContainer container) throws SlickException { this.image = new Image("testdata/sky.jpg"); this.font = (Font)new AngelCodeFont("testdata/hiero.fnt", "testdata/hiero.png"); } public void render(GameContainer container, Graphics g) { this.image.draw(0.0F, 0.0F, 800.0F, 600.0F); this.font.drawString(100.0F, 32.0F, "On top of old smokey, all"); this.font.drawString(100.0F, 80.0F, "covered with sand.."); } public void update(GameContainer container, int delta) throws SlickException {} public void keyPressed(int key, char c) { if (key == 1) System.exit(0); } public static void main(String[] argv) { try { container = new AppGameContainer((Game)new PureFontTest()); container.setDisplayMode(800, 600, false); container.start(); } catch (SlickException e) { e.printStackTrace(); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\PureFontTest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.rcwang.seal.translation; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.rcwang.seal.eval.EvalResult; import com.rcwang.seal.eval.Evaluator; import com.rcwang.seal.expand.Entity; import com.rcwang.seal.expand.EntityList; import com.rcwang.seal.expand.GoogleSets; import com.rcwang.seal.expand.Seal; import com.rcwang.seal.expand.SeedSelector; import com.rcwang.seal.expand.SetExpander; import com.rcwang.seal.expand.SeedSelector.SeedingPolicy; import com.rcwang.seal.rank.Ranker.Feature; import com.rcwang.seal.translation.Proximator.Proxistat; import com.rcwang.seal.util.GlobalVar; import com.rcwang.seal.util.Helper; import com.rcwang.seal.util.StringEditDistance; public class BilingualSeal { public static Logger log = Logger.getLogger(BilingualSeal.class); public static GlobalVar gv = GlobalVar.getGlobalVar(); public static int DEFAULT_NUM_EXPANSIONS = 10; public static int DEFAULT_NUM_TOP_TRANS = 3; public static double DEFAULT_SIM_THRESHOLD = 0.80; public static double DEFAULT_PCT_TOP_ENTITIES = 0.50; public static boolean DEFAULT_USE_TRANSLATION = true; private List<EvalResult> evalResultList; private EntityList historicalSeeds; private Evaluator sourceEval; private String sourceLangID; private String targetLangID; private int numExpansions; private int numTopTrans; private double simThreshold; private double pctTopEntities; private boolean useTranslation; public static void main(String args[]) { List<String> seeds = new ArrayList<String>(); // seeds.add("小美人魚"); // seeds.add("美女與野獸"); seeds.add("匹茲堡海盜"); seeds.add("紐約洋基"); SeedSelector selector = new SeedSelector(SeedingPolicy.ISS_UNSUPERVISED); selector.setNumSeeds(1, 1); selector.setFeature(Feature.GWW); selector.setTrueSeeds(seeds); BilingualSeal bs = new BilingualSeal(); bs.setLangID("zh-TW", "en"); bs.expand(new Seal(), selector); } public BilingualSeal() { historicalSeeds = new EntityList(); evalResultList = new ArrayList<EvalResult>(); setNumExpansions(DEFAULT_NUM_EXPANSIONS); setUseTranslation(DEFAULT_USE_TRANSLATION); setPctTopEntities(DEFAULT_PCT_TOP_ENTITIES); setSimThreshold(DEFAULT_SIM_THRESHOLD); setNumTopTrans(DEFAULT_NUM_TOP_TRANS); } public EntityList expand(SetExpander sourceExpander, SeedSelector sourceSelector) { if (sourceExpander == null || sourceSelector == null) { return null; } else if (targetLangID == null || sourceLangID == null) { log.fatal("Source and target languages are not set!"); return null; } // configure source expander if (sourceExpander instanceof Seal) { ((Seal) sourceExpander).setLangID(sourceLangID); ((Seal) sourceExpander).setFeature(sourceSelector.getFeature()); } // create target expander SetExpander targetExpander = toTargetExpander(sourceExpander); if (targetExpander == null) return null; if (targetExpander instanceof Seal) { ((Seal) targetExpander).setLangID(targetLangID); ((Seal) targetExpander).setFeature(sourceSelector.getFeature()); } // create translators (source <=> target) Proximator s2tTranslator = new Proximator(targetLangID); Proximator t2sTranslator = new Proximator(sourceLangID); s2tTranslator.setReverseProximator(t2sTranslator); t2sTranslator.setReverseProximator(s2tTranslator); // create target evaluator Evaluator targetEval = toTargetEval(sourceEval); SeedSelector targetSelector = new SeedSelector(sourceSelector); targetSelector.setTrueSeeds(targetEval.getFirstMentions()); targetSelector.setRandomSeed(sourceSelector.getRandomSeed() + 1024); EntityList prevEntities = null; EntityList currEntities = null; EntityList possibleSeeds = null; for (int i = 0; i < numExpansions; i++) { // select the appropriate object based on the current iteration String langID = (i%2 == 0) ? sourceLangID : targetLangID; Evaluator evaluator = (i%2 == 0) ? sourceEval : targetEval; SetExpander expander = (i%2 == 0) ? sourceExpander : targetExpander; SeedSelector selector = (i%2 == 0) ? sourceSelector : targetSelector; Proximator translator = (i%2 == 0) ? s2tTranslator : t2sTranslator; System.out.println(); String msg = "[" + langID + "." + (selector.getIterCounter()+1) + "] "; if (evaluator == null) log.info(msg + "Expanding..."); else log.info(msg + "Evaluating " + evaluator.getDataName() + "..."); if (i >= 2) { if (useTranslation) { possibleSeeds = intersect(prevEntities, currEntities, selector.getFeature(), selector.getNumPossibleSeeds(), translator); if (possibleSeeds == null) possibleSeeds = prevEntities; } else possibleSeeds = prevEntities; } EntityList seeds = selector.select(possibleSeeds); if (seeds == null) return null; historicalSeeds.addAll(seeds); expander.expand(seeds); // expander.assignWeights(selector.getFeature()); prevEntities = currEntities; currEntities = expander.getEntityList(); if (evaluator != null) { EvalResult evalResult = evaluator.evaluate(currEntities); log.info("==> Mean Average Precision: " + Helper.formatNumber(evalResult.meanAvgPrecision*100, 2) + "%"); evalResultList.add(evalResult); } } // fills up the rest of the evaluation result list if seeds for the next iteration are missing if (sourceEval != null && possibleSeeds == null) { for (int i = evalResultList.size(); i < numExpansions; i++) evalResultList.add(evalResultList.get(i-2)); } return currEntities; } public List<EvalResult> getEvalResultList() { return evalResultList; } public int getNumExpansions() { return numExpansions; } public int getNumTopTrans() { return numTopTrans; } public double getPctTopEntities() { return pctTopEntities; } public double getSimThreshold() { return simThreshold; } public Evaluator getSourceEval() { return sourceEval; } public String getSourceLangID() { return sourceLangID; } public String getTargetLangID() { return targetLangID; } public boolean isUseTranslation() { return useTranslation; } public void setEval(Evaluator sourceEval) { this.sourceEval = sourceEval; } public void setLangID(String sourceLangID, String targetLangID) { this.sourceLangID = sourceLangID; this.targetLangID = targetLangID; } public void setNumExpansions(int numIteration) { this.numExpansions = numIteration; } public void setNumTopTrans(int numTopTrans) { this.numTopTrans = numTopTrans; } public void setPctTopEntities(double pctTopEntities) { this.pctTopEntities = pctTopEntities; } public void setSimThreshold(double simThresh) { this.simThreshold = simThresh; } public void setUseTranslation(boolean useTranslation) { this.useTranslation = useTranslation; } private EntityList intersect(EntityList entities1, EntityList entities2, Object feature, int numPossibleSeeds, Proximator translator) { EntityList seeds = new EntityList(); // TranslationPair transPair = translator.getTransPair(); for (int i = 0; i < entities1.size(); i++) { if ( (double)(i+1) / entities1.size() > pctTopEntities) break; Entity entity1 = entities1.get(i); // skip if the entity has been used as seeds if (historicalSeeds.contains(entity1)) continue; // get the best translation pair // kmr possible gotcha String name1 = entity1.getName().toString(); EntityList translations = translator.getTargets(name1); Entity entity2 = getBestMatch(translations, entities2, feature); if (entity2 == null) continue; // kmr possible gotcha String name2 = entity2.getName().toString(); // store the translation pair for future use // transPair.add(name1, name2); log.info("--> " + (i+1) + ". \"" + name1 + "\" translates to \"" + name2 + "\""); seeds.add(entity1); if (seeds.size() >= numPossibleSeeds) return seeds; } log.warn("!!! Could not find matching translations... expanded set is too small?!"); return null; } private Entity getBestMatch(EntityList transList, EntityList inputList, Object inputFeature) { if (transList == null || inputList == null || inputFeature == null) return null; Entity bestInputEnt = null; double maxWeight = Double.MIN_VALUE; for (int i = 0; i < Math.min(numTopTrans, transList.size()); i++) { Entity transEntity = transList.get(i); double transWeight = transEntity.getWeight(Proxistat.PROXISCORE); for (int j = 0; j < inputList.size(); j++) { if ( (double)(j+1) / inputList.size() > pctTopEntities) break; Entity inputEntity = inputList.get(j); // kmr possible gotcha double similarity = StringEditDistance.levenshtein(inputEntity.getName().toString(), transEntity.getName().toString()); if (similarity < simThreshold) continue; double inputWeight = inputEntity.getWeight(inputFeature); log.info(transEntity.getName() + "(" + Math.round(transWeight*100) + "%)" + " --> " + (j+1) + ". " + inputEntity.getName() + "(" + Math.round(inputWeight*100) + "%)"); double weight = transWeight * inputWeight * similarity; if (weight > maxWeight) { bestInputEnt = inputEntity; maxWeight = weight; } } } return bestInputEnt; } private Evaluator toTargetEval(Evaluator sourceEval) { if (sourceEval == null) return null; String goldFilePath = sourceEval.getGoldFile().getPath(); goldFilePath = goldFilePath.replace(sourceLangID, targetLangID); File targetGoldFile = new File(goldFilePath); Evaluator targetEval = null; if (targetGoldFile.exists()) { targetEval = new Evaluator(); targetEval.loadGoldFile(targetGoldFile); } return targetEval; } private SetExpander toTargetExpander(SetExpander sourceExpander) { SetExpander targetExpander; if (sourceExpander instanceof Seal) { targetExpander = new Seal(); } else if (sourceExpander instanceof GoogleSets) { targetExpander = new GoogleSets(); } else { log.fatal("Error: Could not understand: " + sourceExpander.getClass().getSimpleName()); return null; } return targetExpander; } }
package com.arkaces.aces_marketplace_api.user; import lombok.Data; @Data public class User { private String id; private String name; private String emailAddress; private String createdAt; }
package com.nevmmv; //import mpi.BasicType; import mpi.MPI; import mpi.MPIException; import mpi.Status; import java.io.*; import java.nio.*; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Mykola Nevmerzhytskyi */ public final class Main { /* * D:\java\mpi_lab\out\production\mpi_lab>mpjrun -np 4 com.nevmmv.Main MPJ Express (0.44) is started in the multicore configuration Starting core 3, size 4 Starting core 1, size 4 Starting core 0, size 4 Starting core 2, size 4 sending to core 1 sending to core 2 sending to core 3 Received [1528357875236, 1528357875236, 1528357875236, 1528357875236] Received [1528357875236, 1528357875236, 1528357875236, 1528357875236] Received [1528357875236, 1528357875236, 1528357875236, 1528357875236] D:\java\mpi_lab\out\production\mpi_lab>mpjrun -np 8 com.nevmmv.Main MPJ Express (0.44) is started in the multicore configuration Starting core 1, size 8 Starting core 5, size 8 Starting core 0, size 8 Starting core 4, size 8 Starting core 2, size 8 Starting core 7, size 8 Starting core 6, size 8 Starting core 3, size 8 sending to core 1 sending to core 2 sending to core 3 sending to core 4 sending to core 5 Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] sending to core 6 Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] sending to core 7 Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] Received [1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444, 1528357920444] D:\java\mpi_lab\out\production\mpi_lab>mpjrun -np 12 com.nevmmv.Main MPJ Express (0.44) is started in the multicore configuration Starting core 9, size 12 Starting core 3, size 12 Starting core 5, size 12 Starting core 8, size 12 Starting core 4, size 12 Starting core 2, size 12 Starting core 10, size 12 Starting core 11, size 12 Starting core 7, size 12 Starting core 0, size 12 Starting core 1, size 12 Starting core 6, size 12 sending to core 1 sending to core 2 sending to core 3 sending to core 4 sending to core 5 sending to core 6 sending to core 7 Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] sending to core 8 sending to core 9 Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] sending to core 10 sending to core 11 Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] Received [1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495, 1528357955495] */ public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); } /* public static void main(String[] args) throws MPIException, IOException, ClassNotFoundException { MPI.Init(args); final int me = MPI.COMM_WORLD.Rank(); final int size = MPI.COMM_WORLD.Size(); // Logger.getLogger(Main.class.getName()).info("Rank = "+me+" ; size = "+size); System.out.println(String.format("Starting core %d, size %d", me, size)); if (me == 0) { final Object[] arr = new Object[size]; Arrays.fill(arr, System.currentTimeMillis()); for (int i = 1; i < size; ++i) { sendArrayOfObjects(arr, i, 0); System.out.println(String.format("sending to core %d", i)); } } else { System.out.println(String.format("Received %s", Arrays.toString(recvArrayOfObjects(size, 0, 0)))); } MPI.Finalize(); } public static void sendArrayOfObjects(Object[] a, int proc, int tag) { for (int i = 0; i < a.length; i++) sendObject(a[i], proc, tag + i); } public static void sendObject(Object o, int proc, int tag) { // try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos = new ObjectOutputStream(bos)) { // // oos.writeObject(o); // // final byte[] temp = bos.toByteArray(); // final ByteBuffer buf = ByteBuffer.allocateDirect(temp.length); //MPI.newByteBuffer(temp.length); // // buf.put(temp); // MPI.COMM_WORLD.Isend(buf,0, temp.length, MPI.BYTE, proc, tag); // } catch (Exception ex) { // Logger.getLogger(Main.class.getName()). // log(Level.SEVERE, null, ex); // // throw new RuntimeException(ex); // } ///////////////////////// try { Object[] sendArr = new Object[1]; sendArr[0] = (Object) o; MPI.COMM_WORLD.Isend(sendArr, 0, 1, MPI.OBJECT, proc, tag); // byte[] bytes = serialize(o); // ByteBuffer byteBuffer = ByteBuffer.allocateDirect(bytes.length); // ByteBuffer byteBuff = ByteBuffer.wrap(bytes);//allocateDirect(bytes.length /*+ MPI.SEND_OVERHEAD* /); // byteBuff.put(bytes); // MPI.Buffer_attach(byteBuff); // Logger.getLogger(Main.class.getName()). // log(Level.INFO, "SEND_SIZE="+ bytes.length+'\n'+String.valueOf(bytes)); // System.out.println("Serialized to " + bytes.length); // MPI.COMM_WORLD.Isend(byteBuffer.put(bytes), 0, bytes.length, MPI.BYTE, proc, tag); } catch (Exception ex) { Logger.getLogger(Main.class.getName()). log(Level.SEVERE, null, ex); throw new RuntimeException(ex); } } public static Object[] recvArrayOfObjects(int n, int proc, int tag) throws MPIException, IOException, ClassNotFoundException { Object[] o = new Object[n]; for (int i = 0; i < n; i++) o[i] = recvObject(proc, tag + i); return o; } public static Object recvObject(int proc, int tag) throws MPIException, IOException, ClassNotFoundException { Status st = MPI.COMM_WORLD.Probe(proc, tag); int size = st.Get_count(MPI.OBJECT);//count;//(MPI.BYTE); // Logger.getLogger(Main.class.getName()). // log(Level.INFO, "RECV_SIZE="+ size); // byte[] tmp = new byte[size]; Object[] tmp = new Object[size]; MPI.COMM_WORLD.Recv(tmp, 0, size, MPI.OBJECT, proc, tag); return tmp[0]; /* ByteArrayInputStream bis = new ByteArrayInputStream(tmp); ObjectInputStream ois = new ObjectInputStream(bis); Object res = null; // while (ois.read() != -1) { res = ois.readObject(); //...rest of the code // } bis.close(); return res;*/ } /* public static Object[] recvObjects(int m, int proc, int tag) throws MPIException { Status s = MPI.COMM_WORLD.Probe(proc, tag); int n = s.Get_count(MPI.BYTE); byte[] arr = new byte[n]; MPI.COMM_WORLD.Recv(arr, 0, n, MPI.BYTE, proc, tag); Object[] res = new Object[m]; try { ByteArrayInputStream bis = new ByteArrayInputStream(arr); ObjectInputStream ois = new ObjectInputStream(bis); for (int i = 0; i < arr.length; i++) res[i] = (Object) ois.readObject(); } catch (Exception ex) { Logger.getLogger(Main.class.getName()). log(Level.SEVERE, null, ex); } return res; } } */
package com.designpattern.structuralpattern.proxy.staticproxy; public interface Person { //找对象 void findLove(); //找工作 void findJob(); }
package day16; import heima.bean.Student; import java.util.ArrayList; import java.util.Collection; public class test1 { @SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) { Collection c = new ArrayList(); c.add(new Student("Achilles",23)); c.add(new Student("Forest",22)); c.add(new Student("Suzy",22)); c.add(new Student("Erwin",22)); Object[] arr = c.toArray(); System.out.println("-----------------"); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } System.out.println("-----------------"); for (int i = 0; i < arr.length; i++) { Student s = (Student)arr[i]; System.out.println(s.getAge()+"...."+s.getName()); } } }
package com.ricex.cartracker.androidrequester.request.tracker; import com.ricex.cartracker.androidrequester.request.AbstractRequest; import com.ricex.cartracker.androidrequester.request.ApplicationPreferences; import com.ricex.cartracker.androidrequester.request.response.RequestResponse; import com.ricex.cartracker.androidrequester.request.exception.RequestException; import com.ricex.cartracker.androidrequester.request.type.BulkUploadResponseType; import com.ricex.cartracker.common.entity.ReaderLog; import com.ricex.cartracker.common.viewmodel.BulkUploadResult; import com.ricex.cartracker.common.viewmodel.BulkUploadViewModel; import com.ricex.cartracker.common.viewmodel.entity.ReaderLogViewModel; import java.util.List; /** * Created by Mitchell on 2016-11-01. */ public class BulkUploadReaderLogRequest extends AbstractRequest<List<BulkUploadResult>> { private final List<BulkUploadViewModel<ReaderLogViewModel>> readerLogs; /** Creates a new Bulk Upload request for the given logs * * @param applicationPreferences */ public BulkUploadReaderLogRequest(ApplicationPreferences applicationPreferences, List<BulkUploadViewModel<ReaderLogViewModel>> readerLogs) { super(applicationPreferences); this.readerLogs = readerLogs; } @Override protected RequestResponse<List<BulkUploadResult>> executeRequest() throws RequestException { return postForObject(serverAddress + "/log/reader/bulk", readerLogs, new BulkUploadResponseType()); } }
package online.stringtek.toy.framework.toymybatis.pojo; import lombok.Data; import java.util.List; @Data public class BoundSQL { private String sql; private List<String> parameterNameList; }
package Saip; public class Saipaotest { public static void main(String[] args) { Relay relay = new Relay(); Thread t1 = new Thread(relay,"长鹤选手"); Thread t2 = new Thread(relay,"李通选手"); Thread t3 = new Thread(relay,"啵啵选手"); Thread t4 = new Thread(relay,"海军选手"); t1.start(); t2.start(); t3.start(); t4.start(); } }
package VEW.XMLCompiler.ASTNodes; import VEW.Planktonica2.Model.Catagory; import VEW.Planktonica2.Model.Type; import VEW.Planktonica2.Model.VarietyType; public class BooleanBinOpNode extends BExprNode { private BooleanBinOperator booleanOp; private BExprNode rBExpr; private BExprNode lBExpr; public BooleanBinOpNode(BooleanBinOperator booleanOp, BExprNode lBExpr, BExprNode rBExpr, int line) { this.booleanOp = booleanOp; this.rBExpr = rBExpr; this.lBExpr = lBExpr; this.line_number = line; } @Override public void check(Catagory enclosingCategory, ConstructedASTree enclosingTree) { rBExpr.check(enclosingCategory, enclosingTree); lBExpr.check(enclosingCategory, enclosingTree); Type rBExprType = rBExpr.getBExprType(); Type lBExprType = lBExpr.getBExprType(); setBExprType(checkTypeCompatible(rBExprType, lBExprType)); } private Type checkTypeCompatible(Type rBExprType, Type lBExprType) { AmbientVariableTables varTables = AmbientVariableTables.getTables(); Type boolType = (Type) varTables.checkTypeTable("$boolean"); if (rBExprType instanceof VarietyType || lBExprType instanceof VarietyType) { return new VarietyType("boolean", boolType); } return boolType; } @Override public String generateXML() { String op = ""; switch (booleanOp) { case AND : op = "and"; break; case OR : op = "or"; break; } return "\\" + op + "{" + lBExpr.generateXML() + "," + rBExpr.generateXML() + "}"; } public String generateLatex() { String op = "???"; String left = "???"; if (lBExpr != null) left = lBExpr.generateLatex(); String right = "???"; if (rBExpr != null) right = rBExpr.generateLatex(); switch (booleanOp) { case AND : op = " \\cap "; break; case OR : op = " \\cup "; break; } return left + "\\;" + op + "\\;" + right; } }
public class Hints { public int key = 0; public String value = null; public String time = null; public void setKey(int key){ this.key = key; } public void setValue(String value){ this.value = value; } public void setTime(String time){ this.time = time; } public int getKey(){ return key; } public String getValue(){ return value; } public String getTime(){ return time; } }
package com.polsl.edziennik.desktopclient.controller.utils; import javax.swing.JEditorPane; import javax.swing.text.Document; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; public class HtmlEditor extends JEditorPane { public HtmlEditor(String html) { // editor = new JEditorPane(); HTMLEditorKit kit = new HTMLEditorKit(); setEditorKit(kit); // add some styles to the html StyleSheet styleSheet = kit.getStyleSheet(); styleSheet.addRule("body {color:#000; font-family:times; margin: 4px; }"); // styleSheet.addRule("h1 {color: blue;}"); // styleSheet.addRule("h2 {color: #ff0000;}"); styleSheet.addRule("pre {font : 10px monaco; color : black; background-color : #fafafa; }"); // create some simple html as a string // create a document, set it on the editor, then add the html Document doc = kit.createDefaultDocument(); setDocument(doc); setText(html); // scroll = new JScrollPane(editor); // add(scroll); } }
import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.Objects; @Entity @Table(name = "Subscriptions") public class Subscription implements Serializable{ @EmbeddedId private Key key; @Column(name = "subscription_date") private Date subscriptionDate; public Subscription(){} public Subscription(Key key) { this.key = key; } public Date getSubscriptionDate() { return subscriptionDate; } public void setSubscriptionDate(Date subscriptionDate) { this.subscriptionDate = subscriptionDate; } public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Subscription)) return false; Subscription that = (Subscription) o; if (!Objects.equals(key, that.key)) return false; return Objects.equals(subscriptionDate, that.subscriptionDate); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (subscriptionDate != null ? subscriptionDate.hashCode() : 0); return result; } @Embeddable public static class Key implements Serializable { @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "student_id") public Student student; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "course_id") public Course course; public Key(){}; public Key(Student student, Course course) { this.student = student; this.course = course; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } } } /*@Entity @Table(name = "Subscriptions") public class Subscription implements Serializable { @EmbeddedId private Id id; @ManyToOne(cascade = CascadeType.ALL) private Student student; @ManyToOne(cascade = CascadeType.ALL) private Course course; @Column(name = "subscription_date") @Temporal(TemporalType.TIMESTAMP) private Date subscriptionsDate; *//* @Column(name = "subscription_date") private Date subscriptionsDate;*//* public Subscription(Id id) { this.id = id; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Date getSubscriptionsDate() { return subscriptionsDate; } public void setSubscriptionsDate(Date subscriptionsDate) { this.subscriptionsDate = subscriptionsDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Subscription)) return false; Subscription that = (Subscription) o; if (!Objects.equals(id, that.id)) return false; return Objects.equals(subscriptionsDate, that.subscriptionsDate); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (subscriptionsDate != null ? subscriptionsDate.hashCode() : 0); return result; } @Embeddable public static class Id implements Serializable{ public Id(){} @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "student_id", referencedColumnName="id") public Student student; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "course_id", referencedColumnName="id") public Course course; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Id)) return false; Id id = (Id) o; if (!Objects.equals(student, id.student)) return false; return Objects.equals(course, id.course); } @Override public int hashCode() { int result = student != null ? student.hashCode() : 0; result = 31 * result + (course != null ? course.hashCode() : 0); return result; } } }*/
package com.smxknife.java2.io.input; /** * @author smxknife * 2019-02-01 */ public class PushbackInputStreamDemo4 { public static void main(String[] args) { } }
package com.minipg.fanster.armoury.activity; import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.minipg.fanster.armoury.R; import com.minipg.fanster.armoury.dao.LoginResponseItemDao; import com.minipg.fanster.armoury.dao.RegisterResponseItemDao; import com.minipg.fanster.armoury.manager.HttpManager; import com.minipg.fanster.armoury.object.RegisterForm; import java.io.IOException; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RegisterActivity extends AppCompatActivity { private FloatingActionButton fabCancle; private Button btnRegister; private EditText etName; private EditText etPW; private EditText etRPW; private EditText etUser; private RelativeLayout touchInterceptor; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); iniInstane(); } private void iniInstane() { touchInterceptor = (RelativeLayout) findViewById(R.id.relativeLayoutRegister); fabCancle = (FloatingActionButton) findViewById(R.id.fabCancel); btnRegister = (Button) findViewById(R.id.bt_register); etName = (EditText) findViewById(R.id.et_name); etUser = (EditText) findViewById(R.id.et_username); etPW = (EditText) findViewById(R.id.et_password); etRPW = (EditText) findViewById(R.id.et_repeatpassword); initHideKeyboard(touchInterceptor); etUser.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable s) { String location_name = s.toString(); if (location_name.matches(".*[^A-Za-z^0-9_].*")) { etUser.setError("Only letters, numbers and underscore are allowed!"); } } }); etPW.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable s) { String location_name = s.toString(); if (location_name.matches(".*[^A-Za-z^0-9_].*")) { etPW.setError("Only letters, numbers and underscore are allowed!"); } } }); etRPW.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void afterTextChanged(Editable s) { String location_name = s.toString(); if (location_name.matches(".*[^A-Za-z^0-9_].*")) { etPW.setError("Only letters, numbers and underscore are allowed!"); } } }); etRPW.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { boolean handled = false; if (i == EditorInfo.IME_ACTION_DONE) { btnRegister.performClick(); handled = true; InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(etRPW.getWindowToken(), 0); } return handled; } }); fabCancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean canRegister = true; if (etName.getText().toString().length() == 0) { etName.setError("Name is required."); canRegister = false; } else if (etName.getText().toString().length() < 4) { etName.setError("Name must at least 4 letter"); canRegister = false; } if (etUser.getText().toString().length() == 0) { etUser.setError("Username is required."); canRegister = false; } else if (etUser.getText().toString().length() < 4) { etUser.setError("Username must at least 4 letter"); canRegister = false; } if (etPW.getText().toString().length() == 0) { etPW.setError("Password is required."); canRegister = false; } else if (etPW.getText().toString().length() < 4) { etPW.setError("Password must at least 4 letter"); canRegister = false; } else if (etRPW.getText().toString().length() == 0) { etRPW.setError("Repeat password is required."); canRegister = false; } if (canRegister) { if (etRPW.getText().toString().equals(etPW.getText().toString())) { RegisterForm registerForm = new RegisterForm(etName.getText().toString(), etUser.getText().toString(), etPW.getText().toString()); register(registerForm); } else { etRPW.setError("Password not match"); } } } }); } @Override public boolean onTouchEvent(MotionEvent event) { hideKeyboard(); return super.onTouchEvent(event); } public void hideKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } private void register(final RegisterForm registerForm) { Call<RegisterResponseItemDao> call = HttpManager.getInstance().getService().register(registerForm); call.enqueue(new Callback<RegisterResponseItemDao>() { @Override public void onResponse(Call<RegisterResponseItemDao> call, Response<RegisterResponseItemDao> response) { if (response.isSuccessful()) { RegisterResponseItemDao dao = response.body(); if(!dao.isCheckName()){ etName.setError(registerForm.getName()+" already exists"); } if(!dao.isCheckUserName()){ etUser.setError(registerForm.getUsername()+" already exists"); } if (dao.isCheckUserName() && dao.isCheckName()) { showToast("Registration Success"); finish(); } else { showToast("Registration Fail"); } //register } else { try { showToast(response.errorBody().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<RegisterResponseItemDao> call, Throwable t) { showToast("Register Fail"); } }); } private void setHideKeyboard(final EditText editText) { editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { if (!b) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } } }); } private void showToast(String username) { Toast.makeText(RegisterActivity.this, username.toString(), Toast.LENGTH_SHORT).show(); } private void initHideKeyboard(RelativeLayout touchInterceptor) { touchInterceptor.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { setHideKeyboard(etUser,v,event); setHideKeyboard(etPW,v,event); setHideKeyboard(etRPW,v,event); setHideKeyboard(etName,v,event); } return false; } }); } private void setHideKeyboard(final EditText editText,View v, MotionEvent event) { if (editText.isFocused()) { Rect outRect = new Rect(); editText.getGlobalVisibleRect(outRect); if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) { editText.clearFocus(); InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2017.01.28 at 02:10:24 PM CST // package org.mesa.xml.b2mml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ToIDType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ToIDType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ToIDValue" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ToType" type="{http://www.mesa.org/xml/B2MML-V0600}ToTypeType"/> * &lt;element name="IDScope" type="{http://www.mesa.org/xml/B2MML-V0600}IDScopeType"/> * &lt;group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}ToID" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ToIDType", propOrder = { "toIDValue", "toType", "idScope" }) public class ToIDType { @XmlElement(name = "ToIDValue", required = true) protected String toIDValue; @XmlElement(name = "ToType", required = true) protected ToTypeType toType; @XmlElement(name = "IDScope", required = true) protected IDScopeType idScope; /** * Gets the value of the toIDValue property. * * @return * possible object is * {@link String } * */ public String getToIDValue() { return toIDValue; } /** * Sets the value of the toIDValue property. * * @param value * allowed object is * {@link String } * */ public void setToIDValue(String value) { this.toIDValue = value; } /** * Gets the value of the toType property. * * @return * possible object is * {@link ToTypeType } * */ public ToTypeType getToType() { return toType; } /** * Sets the value of the toType property. * * @param value * allowed object is * {@link ToTypeType } * */ public void setToType(ToTypeType value) { this.toType = value; } /** * Gets the value of the idScope property. * * @return * possible object is * {@link IDScopeType } * */ public IDScopeType getIDScope() { return idScope; } /** * Sets the value of the idScope property. * * @param value * allowed object is * {@link IDScopeType } * */ public void setIDScope(IDScopeType value) { this.idScope = value; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2017.01.28 at 02:10:24 PM CST // package org.mesa.xml.b2mml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ProductionScheduleType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ProductionScheduleType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" minOccurs="0"/> * &lt;element name="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Location" type="{http://www.mesa.org/xml/B2MML-V0600}LocationType" minOccurs="0"/> * &lt;element name="HierarchyScope" type="{http://www.mesa.org/xml/B2MML-V0600}HierarchyScopeType" minOccurs="0"/> * &lt;element name="PublishedDate" type="{http://www.mesa.org/xml/B2MML-V0600}PublishedDateType" minOccurs="0"/> * &lt;element name="StartTime" type="{http://www.mesa.org/xml/B2MML-V0600}StartTimeType" minOccurs="0"/> * &lt;element name="EndTime" type="{http://www.mesa.org/xml/B2MML-V0600}EndTimeType" minOccurs="0"/> * &lt;element name="EquipmentElementLevel" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentElementLevelType" minOccurs="0"/> * &lt;element name="ProductionRequest" type="{http://www.mesa.org/xml/B2MML-V0600}ProductionRequestType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="ScheduleState" type="{http://www.mesa.org/xml/B2MML-V0600}RequestStateType" minOccurs="0"/> * &lt;group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}ProductionSchedule" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProductionScheduleType", propOrder = { "id", "description", "location", "hierarchyScope", "publishedDate", "startTime", "endTime", "equipmentElementLevel", "productionRequest", "scheduleState" }) public class ProductionScheduleType { @XmlElement(name = "ID") protected IdentifierType id; @XmlElement(name = "Description") protected List<DescriptionType> description; @XmlElement(name = "Location") protected LocationType location; @XmlElement(name = "HierarchyScope") protected HierarchyScopeType hierarchyScope; @XmlElement(name = "PublishedDate") protected PublishedDateType publishedDate; @XmlElement(name = "StartTime") protected StartTimeType startTime; @XmlElement(name = "EndTime") protected EndTimeType endTime; @XmlElement(name = "EquipmentElementLevel") protected EquipmentElementLevelType equipmentElementLevel; @XmlElement(name = "ProductionRequest") protected List<ProductionRequestType> productionRequest; @XmlElement(name = "ScheduleState") protected RequestStateType scheduleState; /** * Gets the value of the id property. * * @return * possible object is * {@link IdentifierType } * */ public IdentifierType getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link IdentifierType } * */ public void setID(IdentifierType value) { this.id = value; } /** * Gets the value of the description 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 description property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDescription().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DescriptionType } * * */ public List<DescriptionType> getDescription() { if (description == null) { description = new ArrayList<DescriptionType>(); } return this.description; } /** * Gets the value of the location property. * * @return * possible object is * {@link LocationType } * */ public LocationType getLocation() { return location; } /** * Sets the value of the location property. * * @param value * allowed object is * {@link LocationType } * */ public void setLocation(LocationType value) { this.location = value; } /** * Gets the value of the hierarchyScope property. * * @return * possible object is * {@link HierarchyScopeType } * */ public HierarchyScopeType getHierarchyScope() { return hierarchyScope; } /** * Sets the value of the hierarchyScope property. * * @param value * allowed object is * {@link HierarchyScopeType } * */ public void setHierarchyScope(HierarchyScopeType value) { this.hierarchyScope = value; } /** * Gets the value of the publishedDate property. * * @return * possible object is * {@link PublishedDateType } * */ public PublishedDateType getPublishedDate() { return publishedDate; } /** * Sets the value of the publishedDate property. * * @param value * allowed object is * {@link PublishedDateType } * */ public void setPublishedDate(PublishedDateType value) { this.publishedDate = value; } /** * Gets the value of the startTime property. * * @return * possible object is * {@link StartTimeType } * */ public StartTimeType getStartTime() { return startTime; } /** * Sets the value of the startTime property. * * @param value * allowed object is * {@link StartTimeType } * */ public void setStartTime(StartTimeType value) { this.startTime = value; } /** * Gets the value of the endTime property. * * @return * possible object is * {@link EndTimeType } * */ public EndTimeType getEndTime() { return endTime; } /** * Sets the value of the endTime property. * * @param value * allowed object is * {@link EndTimeType } * */ public void setEndTime(EndTimeType value) { this.endTime = value; } /** * Gets the value of the equipmentElementLevel property. * * @return * possible object is * {@link EquipmentElementLevelType } * */ public EquipmentElementLevelType getEquipmentElementLevel() { return equipmentElementLevel; } /** * Sets the value of the equipmentElementLevel property. * * @param value * allowed object is * {@link EquipmentElementLevelType } * */ public void setEquipmentElementLevel(EquipmentElementLevelType value) { this.equipmentElementLevel = value; } /** * Gets the value of the productionRequest 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 productionRequest property. * * <p> * For example, to add a new item, do as follows: * <pre> * getProductionRequest().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProductionRequestType } * * */ public List<ProductionRequestType> getProductionRequest() { if (productionRequest == null) { productionRequest = new ArrayList<ProductionRequestType>(); } return this.productionRequest; } /** * Gets the value of the scheduleState property. * * @return * possible object is * {@link RequestStateType } * */ public RequestStateType getScheduleState() { return scheduleState; } /** * Sets the value of the scheduleState property. * * @param value * allowed object is * {@link RequestStateType } * */ public void setScheduleState(RequestStateType value) { this.scheduleState = value; } }
// Sun Certified Java Programmer // Chapter 2, P91 // Object Orientation public class TestShapes { public static void main(String[] args) { PlayerPiece shape = new PlayerPiece(); shape.displayShape(); shape.movePiece(); } }
package tutorialFX; import javafx.scene.paint.*; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Rot; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.*; import java.util.HashMap; import java.util.Random; /** * @author dilip then ea */ public class Utils { private static final Vec2 gravity = new Vec2(0, -1.0f); private static final float mutationRate = 2f; //Create a JBox2D world. // with gravity vector. public static final World world = new World(gravity); //Screen width and height in pixels public static final int WIDTH_px = 500; public static final int HEIGHT_px = 500; public static final float WIDTHd2 = 500f; public static final float HEIGHTd2 = 500f; // step frequency public static final float DT = 1f / 25f; //Initial size in pixel public static final float LIMB_SIZE = 5f; //Total number of limbs public final static int NO_OF_INITIAL_BIOTS = 1; public static final int MAX_BIOTS = 150; ///////// interaction constants static final float InitialBIRTHENERGY = 3000f; static final long MAXAGE = 8500; // 8500*DT / 60 = 5.6 Minutes of life time max static final float EAT_EFFICIENCY = 10.6f; static final float RED_HURTS_RED = 2.8f; static final float SUNRADIATION = 1.2f; static final float LIVINGCostOfRedLimb = 1.19f; // 0.04f; // the random generator static Random r = new Random(System.currentTimeMillis()); static private final HashMap<Color, Paint> cachedPaints = new HashMap<>(); public static void fourWalls() { // vier wände: // the Body BodyDef bd = new BodyDef(); bd.type = BodyType.STATIC; bd.setPosition(new Vec2()); Body staticBody = world.createBody(bd); FixtureDef fd = new FixtureDef(); // parameter die bei allen Fixtures gelten fd.setRestitution(2.3f); // dann die shapes PolygonShape polygonShape = new PolygonShape(); polygonShape.setAsBox(WIDTHd2 / 2, 1f, new Vec2(WIDTHd2 / 2, 0), 0f); // BODEN fd.setShape(polygonShape); // zur FD staticBody.createFixture(fd); // diese fixture muss zum Body polygonShape.setAsBox(WIDTHd2 / 2, 1f, new Vec2(WIDTHd2 / 2, HEIGHTd2), 0f); // Decke fd.setShape(polygonShape); // zur FD staticBody.createFixture(fd); // diese fixture muss zum Body polygonShape.setAsBox(1f, HEIGHTd2 / 2, new Vec2(0f, HEIGHTd2 / 2), 0f); // Linke Wand fd.setShape(polygonShape); // zur FD staticBody.createFixture(fd); // diese fixture muss zum Body polygonShape.setAsBox(1f, HEIGHTd2 / 2, new Vec2(WIDTHd2, HEIGHTd2 / 2), 0f); // rechte Wand fd.setShape(polygonShape); // zur FD staticBody.createFixture(fd); // diese fixture muss zum Body } public static Paint getGradient(Color color) { Paint paint = cachedPaints.get(color); if (paint == null) { //This gives a gradient paint = new LinearGradient(0.0, 0.0, 1.0, 0.0, true, CycleMethod.NO_CYCLE, new Stop(0, Color.WHITE), new Stop(1, color)); cachedPaints.put(color, paint); } return paint; } //Convert a JBox2D x coordinate to a JavaFX pixel x coordinate public static double toPixelPosX(float posX) { return WIDTH_px * posX / WIDTHd2; } //Convert a JavaFX pixel x coordinate to a JBox2D x coordinate public static float toPosX(double posX) { return (float) (posX * WIDTHd2 / WIDTH_px); } //Convert a JBox2D y coordinate to a JavaFX pixel y coordinate public static double toPixelPosY(float posY) { return HEIGHT_px - posY * HEIGHT_px / HEIGHTd2; } //Convert a JavaFX pixel y coordinate to a JBox2D y coordinate public static float toPosY(double posY) { return (float) (HEIGHTd2 - posY * HEIGHTd2 / HEIGHT_px); } //Convert a JBox2D width to pixel width public static double toPixelWidth(float width) { return width * WIDTH_px / WIDTHd2; } //Convert a JBox2D height to pixel height public static double toPixelHeight(float height) { return height * HEIGHT_px / HEIGHTd2; } //Convert a pixel distance into JBox2D distance (in X axis) public static float toDistance(double radius) { return (float) (radius * WIDTHd2 / WIDTH_px); } /** * Random between [1-p,1+p] p multiplied by mutationRate * * @param percent 0..1.0f * @return factor */ static float RandomInPercentageRange(float percent) { return 1f + (r.nextFloat() - 0.5f) * percent * mutationRate; } /** * Random between [min-max]. range stretched around mid by mutationRate * * @param min * @param max * @return random float */ static float RandomInRange(float min, float max) { assert min < max; final float v = max - min; return min + v / 2f * (1 - mutationRate) + r.nextFloat() * mutationRate * v; } /** * Random between [min-max]. no stretch of range by mutationRate. * * @param min * @param max * @return random float */ static float RandomInRangeNoMRATE(float min, float max) { assert min < max; return min + r.nextFloat() * (max - min); } /** * Vectore of length mutationRate in random direction. * @return */ static Vec2 RandomUnitVector() { final Rot rot = new Rot(RandomInRange(0f, 360f * MathUtils.DEG2RAD)); Vec2 result = new Vec2(); rot.getXAxis(result); result.mulLocal(mutationRate); return result; } /** * return true with specified probability (approx) probablity is mulitplied by mutationRate. * * @param probability * @return true with the given probability */ static boolean RandomBoolean(float probability) { return r.nextFloat() <= probability * mutationRate; } }
package com.akikun.leetcode.struct; public class ListNode { public int val; /** * if this is double linked list, will use the property 'pre' */ public ListNode pre; public ListNode next; public ListNode(int val) { this.val = val; } public static ListNode from(int[] arr) { if (arr.length == 0) { return null; } ListNode head = new ListNode(arr[0]); if (arr.length == 1) { return head; } ListNode lastOne = head; for (int i = 1; i < arr.length; ++i) { ListNode node = new ListNode(arr[i]); lastOne.next = node; lastOne = node; } return head; } public void print() { ListNode p = this; StringBuilder sb = new StringBuilder("ListNode: ["); while (p != null && p.next != null) { sb.append(p.val).append(" -> "); p = p.next; } sb.append(p.val).append(']'); System.out.println(sb.toString()); } }
package com.example.spring04.modelDAO; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.example.spring04.modelVO.MemberVO; @Repository public class LoginDAOImpl implements LoginDAO { @Inject private SqlSession sqlSession; @Override public MemberVO memberLogin(MemberVO memLogin) throws Exception { return sqlSession.selectOne("login.memCptLogin", memLogin); } }
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import java.io.*; import java.util.*; import java.sql.*; import javax.servlet.http.*; import javax.servlet.*; public final class show_005fbook_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.Vector _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public Object getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <title>Data Page</title>\n"); out.write(" <style type=\"text/css\">\n"); out.write("\n"); out.write(" .modalDialog {\n"); out.write(" position: fixed;\n"); out.write(" font-family: Arial, Helvetica, sans-serif;\n"); out.write(" top: 0;\n"); out.write(" right: 0;\n"); out.write(" bottom: 0;\n"); out.write(" left: 0;\n"); out.write(" background: rgba(0,0,0,.5);\n"); out.write(" z-index: 99999;\n"); out.write(" opacity:0;\n"); out.write(" -webkit-transition: opacity 400ms ease-in;\n"); out.write(" -moz-transition: opacity 400ms ease-in;\n"); out.write(" transition: opacity 400ms ease-in;\n"); out.write(" pointer-events: none;\n"); out.write(" }\n"); out.write(" .modalDialog:target {\n"); out.write(" opacity:1;\n"); out.write(" pointer-events: auto;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modalDialog > div {\n"); out.write(" width: 400px;\n"); out.write(" position: relative;\n"); out.write(" margin: 10% auto;\n"); out.write(" padding: 5px 20px 13px 20px;\n"); out.write(" border-radius: 10px;\n"); out.write(" background: #fff;\n"); out.write(" background: -moz-linear-gradient(#fff, #999);\n"); out.write(" background: -webkit-linear-gradient(#fff, #999);\n"); out.write(" background: -o-linear-gradient(#fff, #999);\n"); out.write(" }\n"); out.write(" </style>\n"); out.write(" </head> \n"); out.write(" <body>\n"); out.write(" <center>\n"); out.write("\n"); out.write("\n"); out.write(" <table>\n"); out.write(" <tr> \n"); out.write(" <td><form action=\"show_book.jsp\" method=\"post\">\n"); out.write(" <strong>Book Name:</strong>\n"); out.write(" <input type=\"\" name=\"book_name\">\n"); out.write(" <input type=submit value=\"Search\"> \n"); out.write(" </form> \n"); out.write(" </tr><tr><td>\n"); out.write(" <form action=\"show_book.jsp\" method=\"post\">\n"); out.write(" <strong>Writer Name:</strong>\n"); out.write(" <input type=\"\" name=\"writer_name\">\n"); out.write(" <input type=submit value=\"Search\"> \n"); out.write("\n"); out.write(" </form>\n"); out.write(" </td>\n"); out.write(" </tr><br> \n"); out.write(" </table>\n"); out.write("\n"); out.write(" </center>\n"); out.write(" <center>\n"); out.write(" <table border=\"3\" >\n"); out.write(" <br>\n"); out.write(" <tr>\n"); out.write("\n"); out.write(" <td width=\"119\"><b>Book ID</b></td>\n"); out.write(" <td width=\"168\"><b>Writer Name</b></td>\n"); out.write(" <td width=\"168\"><b>Book Name</b></td>\n"); out.write(" <td width=\"168\"><b>Download</b></td> \n"); out.write(" </tr>\n"); out.write("\n"); out.write(" "); String p = null; try { String user = "root"; String password = "123"; String database = "test"; Connection con; String url = "jdbc:mysql://localhost:3306/" + database + "?useUnicode=true&amp;characterEncoding=UTF8;"; Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection(url, user, password); Statement stms = con.createStatement(); //String bookName=request.getParameter("search"); String m = request.getParameter("book_name"); String n = request.getParameter("writer_name"); String sql; if (m != null) { sql = "select book_id,writter_name,book_name,location from book_details where book_name='" + m + "'"; } else if (n != null) { sql = "select book_id,writter_name,book_name,location from book_details where writter_name='" + n + "'"; } else { sql = "select book_id,writter_name,book_name,location from book_details"; } ResultSet rs = stms.executeQuery(sql); PrintWriter ou = response.getWriter(); try { while (rs.next()) { //Add records into data list // dataList.add(rs.getInt("serial")); // dataList.add(rs.getString("book_id")); //// dataList.add(rs.getString("writter_name")); //dataList.add(rs.getString("book_name")); //dataList.add(rs.getString("location")); out.write("\n"); out.write(" <tr>\n"); out.write("\n"); out.write(" <td width=\"168\">"); out.print(rs.getString("book_id")); out.write("</td>\n"); out.write(" <td width=\"168\">"); out.print(rs.getString("writter_name")); out.write("</td>\n"); out.write(" <td width=\"168\">"); out.print(rs.getString("book_name")); out.write("</td>\n"); out.write(" "); p = rs.getString("location"); out.write("\n"); out.write("\n"); out.write(" \n"); out.write(" \n"); out.write(" <td><a href=\"#openModal\"value=\""); out.print(p); out.write('"'); out.write('>'); out.print(p); out.write("</a></td>\n"); out.write(" \n"); out.write("\n"); out.write("\n"); out.write(" </tr>\n"); out.write("\n"); out.write(" "); } } catch (Exception e) { } out.write("\n"); out.write(" "); out.write("\n"); out.write("\n"); out.write(" "); } catch (Exception e) { } out.write(" \n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" </table>\n"); out.write(" </center>\n"); out.write(" <div id=\"openModal\" class=\"modalDialog\">\n"); out.write(" <div>\n"); out.write("\n"); out.write(" "); request.getParameter("id"); out.write("\n"); out.write("\n"); out.write(" <a href=\"#close\" title=\"Close\" class=\"close\">X</a>\n"); out.write(" <form method=\"Get\" action=\"download1\" enctype=\"multipart/form-data\">\n"); out.write(" \n"); out.write(" <td>Please Login First</br></br></td>\n"); out.write(" <td>User Name</td> \n"); out.write(" \n"); out.write(" <td><td><input type=\"hidden\" name=\"id\" value=\""); out.print(p); out.write("\" /></td></td>\n"); out.write(" <td><input type=\"text\" name=\"user_name\" value=\"\" /></td></br>\n"); out.write(" <td>password</td>\n"); out.write(" <td><input type=\"password\" name=\"pass\" value=\"\" /></td>\n"); out.write(" <td><input type=\"submit\" value=\"submit\"/></td>\n"); out.write(" \n"); out.write(" </form>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write("\n"); out.write("</body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
package com.lxy.response; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 验证码热身 * @author 15072 * */ public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在内存中生成图片 BufferedImage image = new BufferedImage(300, 500, BufferedImage.TYPE_INT_RGB); // 获取画笔对象 Graphics g = image.getGraphics(); // 设置颜色 g.setColor(Color.RED); // 画一个矩形 g.drawRect(100, 100, 150, 100); g.setColor(Color.YELLOW); // 定义字符串 String str = "abc"; g.drawString(str, 80, 80); // 把内存中的图片输出到浏览器端 ImageIO.write(image, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package org.codeshifts.spring.batch.core; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor; import org.springframework.batch.core.explore.support.JobExplorerFactoryBean; import org.springframework.batch.core.launch.support.SimpleJobLauncher; import org.springframework.batch.core.launch.support.SimpleJobOperator; import org.springframework.batch.core.repository.JobRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; /** * Created by werner.diwischek on 12.05.17. */ @Configuration public class ContextJobConfiguration { private final JobExplorerFactoryBean jobExplorer; private final JobRepository jobRepository; private final JobRegistry jobRegistry; @Autowired public ContextJobConfiguration(JobExplorerFactoryBean jobExplorer, JobRepository jobRepository, JobRegistry jobRegistry) { this.jobExplorer = jobExplorer; this.jobRepository = jobRepository; this.jobRegistry = jobRegistry; } /* <bean id="jobOperator" class="org.springframework.spring.batch.core.launch.support.SimpleJobOperator" p:jobLauncher-ref="jobLauncher" p:jobExplorer-ref="jobExplorer" p:jobRepository-ref="jobRepository" p:jobRegistry-ref="jobRegistry" /> */ @Bean public SimpleJobOperator operator() throws Exception { SimpleJobOperator operator = new SimpleJobOperator(); operator.setJobLauncher(launcher()); operator.setJobExplorer(jobExplorer.getObject()); operator.setJobRepository(jobRepository); operator.setJobRegistry(jobRegistry); return operator; } /* <bean id="jobLauncher" class="org.springframework.spring.batch.core.launch.support.SimpleJobLauncher" p:jobRepository-ref="jobRepository" /> */ @Bean public SimpleJobLauncher launcher() throws Exception { SimpleJobLauncher launcher = new SimpleJobLauncher(); launcher.setJobRepository(jobRepository); return launcher; } @Bean public JobRegistryBeanPostProcessor postProcessor() { JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcessor(); postProcessor.setJobRegistry(jobRegistry); return postProcessor; } }
package j1.s.p0010; import java.util.Random; import java.util.Scanner; public class J1SP0010 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Number of array: "); int length = sc.nextInt(); System.out.println("Enter search value"); int search = sc.nextInt(); int[] arr = new int[length]; for (int i = 0; i < length; i++){ arr[i] = new Random().nextInt(length * 10); } J1SP0010 find = new J1SP0010(); int result = find.linerSearch(arr, search); find.display(arr, result); } public void display(int[] arr, int index){ System.out.println("Array: "); for (int i = 0; i < arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(""); if (index == -1) { System.out.println("Not found."); }else { System.out.println("[" + index + "]"); } } public int linerSearch(int[] arr, int key){ for (int i = 0; i < arr.length; i++){ if (key == arr[i]){ return i; } } return -1; } }
package com.example.jbarrientos.bilbapp.Model; import java.io.IOException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import android.content.Context; import com.example.jbarrientos.bilbapp.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Created by jbarrientos on 5/01/17. */ public class DataPopulator { private RestClient restClient; private String server = "http://u017633.ehu.eus:28080/BILBAPP_SERVER/rest/Bilbapp"; private ArrayList<Sitios> arraySitios = new ArrayList<Sitios>(); private ArrayList<Experience> arrayExperiencias = new ArrayList<Experience>(); private List<String> Lines; public DataPopulator (){ restClient = new RestClient(server); } public ArrayList<Translation> cargaTranslations(Context ctx,String typeSitio){ switch (typeSitio) { case "fiesta": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_fiesta)); break; case "compras": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_compras)); break; case "restaurantes": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_restaurantes)); break; case "alojamiento": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_alojamiento)); break; case "deportes": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_deportes)); break; case "monumentos": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_monumentos)); break; case "transportes": Lines = Arrays.asList(ctx.getResources().getStringArray(R.array.expresion_transporte)); default: break; } ArrayList<Translation> versiones = new ArrayList<Translation>(); for (int i=0;i<Lines.size();i++){ String cadena= Lines.get(i); ArrayList<String> list = new ArrayList<String>(Arrays.asList(cadena.split(";"))); versiones.add( new Translation(list.get(0), list.get(1),list.get(2))); } return versiones; } public ArrayList<Sitios> cargaInfoSitios(String tipoSitio) throws IOException, JSONException { JSONObject jo = restClient.getJson(String.format("requestSitios?opcionName=%s",tipoSitio)); JSONArray listaSitios = jo.getJSONArray("sitio"); int listaSitiosLength = listaSitios.length(); for(int i = 0;i<listaSitiosLength;i++){ JSONObject jsonSitio = listaSitios.getJSONObject(i); Sitios sitioTemp = new Sitios(jsonSitio.getString("sitio"),jsonSitio.getInt("puntuacion"),jsonSitio.getString("direccion")); arraySitios.add(sitioTemp); } return arraySitios; } public ArrayList<Experience> cargaExperienciasByName(String name) throws IOException, JSONException{ String formatedName = URLEncoder.encode(name,"UTF-8"); JSONObject jo = restClient.getJson(String.format("requestCriticas?sitioName=%s",formatedName)); JSONArray listaCriticas = jo.getJSONArray("critica"); int listaCriticasLength = listaCriticas.length(); Date inputDate = new Date(); for(int i = 0;i<listaCriticasLength;i++){ JSONObject jsonCritica = listaCriticas.getJSONObject(i); String inputString = jsonCritica.getString("fecha"); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { inputDate = dateFormat.parse(inputString); } catch (ParseException e) { e.printStackTrace(); } Experience expTemp = new Experience(jsonCritica.getString("usuario"),inputDate,jsonCritica.getString("critica")); arrayExperiencias.add(expTemp); } return arrayExperiencias; } }
package com.filiereticsa.arc.augmentepf.localization; import android.graphics.Point; import android.util.Pair; /** * Created by anthonyprudhomme on 11/10/16. * Copyright © 2016 Granite Apps. All rights reserved. */ public class LocalizedBeaconStatus { String regionUUIDString; String proximity; double accuracy; Point coordinates; int mapId; Pair<Integer, Integer> mapIndexPath; String keyString; public LocalizedBeaconStatus(String uuidString, String proximity, double accuracy, Point coordinates, int mapId, Pair<Integer, Integer> mapIndexPath, String keyString) { if (keyString == null) { keyString = ""; } this.regionUUIDString = uuidString; this.proximity = proximity; this.accuracy = accuracy; this.coordinates = coordinates; this.mapId = mapId; this.mapIndexPath = mapIndexPath; this.keyString = keyString; } public double description() { return this.accuracy; } }
package com.service; import com.bean.BillInfo; import java.util.List; public interface BillInfoService { List<BillInfo> getBillInfo(BillInfo billInfo); }
package org.simpleflatmapper.converter.impl; import org.simpleflatmapper.converter.Converter; import java.util.UUID; public class CharSequenceUUIDConverter implements Converter<CharSequence, UUID> { @Override public UUID convert(CharSequence in) throws Exception { if (in == null) return null; return UUID.fromString(in.toString()); } public String toString() { return "CharSequenceToUUID"; } }
package de.juliushetzel.boilerplate.presentation.login; import de.juliushetzel.boilerplate.domain.executor.ThreadExecutor; import de.juliushetzel.boilerplate.presentation.base.presenter.PresenterFactory; public class LoginPresenterFactory implements PresenterFactory<LoginContract.Presenter> { @Override public LoginContract.Presenter create() { return new LoginPresenter(ThreadExecutor.getInstance()); } }
package views; import java.awt.Dimension; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.ResourceBundle; import controllers.AppController; import javafx.event.EventHandler; import javafx.scene.Group; //import javafx.scene.Parent; //import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollBar; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Shape; import models.grid.Cell; import resources.AppResources; import views.styles.CellStyleGuide; import views.grid.*; /** * A class used to set up and manage the UI * @author Guhan Muruganandam * */ public class AppScene { private CellStyleGuide fCellStyleGuide; private Group fAppRoot; private int fWidth; private int fHeight; private ArrayList<Button> buttonList= new ArrayList<Button>(); private ArrayList<ScrollBar> scrollbarList= new ArrayList<ScrollBar>(); private AppController fAppController; private ResourceBundle mytext=ResourceBundle.getBundle("Resources/textfiles"); private GridViewUpdate myGrid; private ScrollBar fSpeedScrollBar; private ScrollBar fParameterScrollBar; private Rectangle basicGrid; private final NumberAxis xAxis=new NumberAxis(); private final NumberAxis yAxis=new NumberAxis(); private LineChart<Number,Number> myDataChart= new LineChart<Number,Number>(xAxis, yAxis); private XYChart.Series<Number,Number> mySeriesone= new XYChart.Series<Number,Number>(); private XYChart.Series<Number,Number> mySeriestwo= new XYChart.Series<Number,Number>(); public AppScene(int aHeight, int aWidth, AppController aAppController) { fAppRoot = new Group(); fHeight = aHeight; fWidth = aWidth; fAppController = aAppController; setBackground(); setButtons(fWidth); setScrollBars(fWidth); setLabels(fWidth); setGrid(fWidth,fHeight); } public Group getRoot() { return fAppRoot; } private void setBackground() { Rectangle rectangle = new Rectangle(); rectangle.setWidth(fWidth); rectangle.setHeight(fHeight); rectangle.setFill(Color.web(mytext.getString("BACKGROUNDCOLOR"))); fAppRoot.getChildren().add(rectangle); } private void setButtons(int width) { Button startButton= makeButton("StartCommand",AppResources.OFFSET,AppResources.THIRTEEN_SIXTEENTHS,width,true); startButton.setOnAction(e->fAppController.onStartButtonPressed()); Button pauseButton= makeButton("PauseCommand",AppResources.OFFSET,AppResources.THREE_QUARTERS, width,true); pauseButton.setOnAction(e->fAppController.onPauseButtonPressed()); Button resetButton= makeButton("ResetCommand",AppResources.OFFSET,AppResources.FIVE_EIGHTHS, width,true); resetButton.setOnAction(e->fAppController.onResetButtonPressed()); Button stepButton= makeButton("StepCommand",AppResources.OFFSET,AppResources.ELEVEN_SIXTEENTHS, width,true); stepButton.setOnAction(e->fAppController.onStepButtonPressed()); Button setSimulationButton= makeButton("SetSimulationCommand",AppResources.OFFSET,AppResources.SEVEN_EIGHTHS, width,false); setSimulationButton.setOnAction(e-> fAppController.onSetSimulationButtonPressed()); } private Button makeButton(String name, double xlayout, double ylayout,int width,Boolean disable) { Button b = new Button(mytext.getString(name)); b.setLayoutX(width*xlayout); b.setLayoutY(width*ylayout); b.setPrefSize(200, 20); if(disable){ b.setDisable(true); } fAppRoot.getChildren().add(b); buttonList.add(b); return b; } public void Display(){ Iterator<Button> buttonIter= buttonList.iterator(); while(buttonIter.hasNext()){ Button b=buttonIter.next(); b.setDisable(false); } Iterator<ScrollBar> scrollbarIter= scrollbarList.iterator(); while(scrollbarIter.hasNext()){ ScrollBar s=scrollbarIter.next(); s.setDisable(false); } } private void setScrollBars(int width) { fParameterScrollBar=makeScrollBar(AppResources.FIVE_EIGHTHS,AppResources.FIVE_EIGHTHS,width,true); fParameterScrollBar.valueProperty().addListener(e->fAppController.onParameterDrag(fParameterScrollBar.getValue())); fSpeedScrollBar=makeScrollBar(AppResources.FIVE_EIGHTHS,AppResources.ELEVEN_SIXTEENTHS,width,true); fSpeedScrollBar.valueProperty().addListener(e -> fAppController.onSpeedDrag(fSpeedScrollBar.getValue())); } public void setSpeedScrollBarValue(double aValue) { fSpeedScrollBar.setValue(aValue); } public void setParameterScrollBarValue(double aValue) { fParameterScrollBar.setValue(aValue); } private ScrollBar makeScrollBar(double xlayout, double ylayout,int width,Boolean disable) { ScrollBar s=new ScrollBar(); s.setLayoutX(width*xlayout); s.setLayoutY(width*ylayout); if(disable){ s.setDisable(true); } scrollbarList.add(s); fAppRoot.getChildren().add(s); return s; } private void setLabels(int width) { Label parameterLabel= makeLabel("ParameterText",AppResources.HALF,AppResources.FIVE_EIGHTHS,width); fAppRoot.getChildren().add(parameterLabel); Label speedLabel= makeLabel("SpeedText",AppResources.HALF,AppResources.ELEVEN_SIXTEENTHS,width); fAppRoot.getChildren().add(speedLabel); } private Label makeLabel(String name,double xlayout,double ylayout,int width){ Label l=new Label(mytext.getString(name)); l.setLayoutX(width*xlayout); l.setLayoutY(width*ylayout); return l; } private void setGrid(int width, int height){ basicGrid=new Rectangle(width*AppResources.ONE_SIXTEENTH,height*AppResources.ONE_SIXTEENTH, width*AppResources.HALF,height*AppResources.HALF); basicGrid.setFill(Color.GRAY); fAppRoot.getChildren().add(basicGrid); } //XXX: Change the grid construction to a factory public void intializeGrid(Collection<Cell> cells,CellStyleGuide csg, Dimension dimensions, GridType aGridType){ //myGrid=GridViewUpdateFactory.BuildGridView(gridtype); //myGrid= new GridViewUpdateSquare(fWidth,fHeight,dimensions,fAppRoot,csg,cells); //myGrid= new GridViewUpdateTriangles(fWidth,fHeight,dimensions,fAppRoot,csg,cells); GridViewUpdate newGrid; switch (aGridType) { case Square: newGrid= new GridViewUpdateSquare(fWidth,fHeight,dimensions,fAppRoot,csg,cells); break; case Hex: newGrid= new GridViewUpdateHexagon(fWidth,fHeight,dimensions,fAppRoot,csg,cells); break; case Triangle: newGrid= new GridViewUpdateTriangles(fWidth,fHeight,dimensions,fAppRoot,csg,cells); break; default: newGrid = null; // throw new GridNotFoundException() } fAppRoot.getChildren().remove(basicGrid); // myGrid.clearGrid(); myGrid = newGrid; myGrid.makeGrid(); } public void clearGrid() { if (myGrid != null) { myGrid.clearGrid(); } } public void updateGrid(Collection<Cell> cells) { myGrid.stepGrid(cells); } public void updateCell(Cell aCell) { myGrid.colorCell(aCell); } //public void mouseClickGrid(){ // fAppScene.setOnMouseClicked(e -> GridViewUpdateSquare.handleMouseClick(e.getX(), e.getY())); //} public void buildCellListeners(Collection<Cell> cells) { Iterator<Shape> shapeIterator= myGrid.getShapeIterator(); for(Cell c:cells){ Shape s= shapeIterator.next(); // s.setOnMouseClicked(e->fAppController.updateCellState(c)); s.setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { fAppController.updateCellState(c); } }); } } public void changeCellColor(Cell c) { fAppRoot.getChildren().remove(myGrid.getShape(c)); myGrid.colorCell(c); fAppRoot.getChildren().add(myGrid.getShape(c)); } public void updateGraphData(int stepnumber,double datapointone, double datapointtwo){ if(fAppRoot.getChildren().contains(myDataChart)){ fAppRoot.getChildren().remove(myDataChart); } mySeriesone.getData().add(new XYChart.Data<Number,Number>(stepnumber,datapointone)); mySeriestwo.getData().add(new XYChart.Data<Number,Number>(stepnumber,datapointtwo)); } public void BuildGraph(){ myDataChart.getData().addAll(mySeriesone,mySeriestwo); myDataChart.setLayoutX(fWidth*AppResources.FIVE_EIGHTHS); myDataChart.setLayoutY(fHeight*AppResources.QUARTER); fAppRoot.getChildren().add(myDataChart); } }
package com.app.steyrix.question_clone_app.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.util.Log; import javax.net.ssl.HttpsURLConnection; public class JSONParser { public static JSONArray makeHttpRequest(String url, String method, HashMap<String, String> params) { InputStream is; JSONArray jObj = null; String json = ""; HashMap<String,String> postDataParams = params; try { if (method == "GET") { if(params != null) { url += "?" + getPostDataString(params); } URL urlObj = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection(); urlConnection.setRequestMethod("GET"); is = urlConnection.getInputStream(); if(is == null) throw new Exception("InputStream is null;" + urlConnection.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString().trim(); } else if (method == "POST"){ URL urlObj = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection(); urlConnection.setRequestMethod("POST"); OutputStream os = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); is = urlConnection.getInputStream(); if(is == null) throw new Exception("InputStream is null;" + urlConnection.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader( is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString().trim(); } else throw new Exception("Invalid method"); } catch (Exception e) { Log.e("Error: ", e.toString()); e.printStackTrace(); } try { Log.i("tagconvertstr", "["+json+"]"); Object item = new JSONTokener(json).nextValue(); if(item instanceof JSONArray) jObj = (JSONArray)item; else { JSONArray out = new JSONArray(); out.put(item); jObj = out; } } catch (JSONException e) { Log.e("JSON Parser", method + ", Error parsing data " + e.toString()); } return jObj; } private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } Log.e("PAR", result.toString()); return result.toString(); } }
package blockchain.block; /* * Represents the data section of the block and contains a list of all data points in the block * The data section can vary in size from block to block */ import blockchain.block.data_points.DataPoint; import blockchain.utility.ByteUtils; import java.io.*; import java.util.ArrayList; public class Data { private final ArrayList<DataPoint> dataPoints; private int dataPointCount; // Construct a data object based on a list of DataPoints public Data(ArrayList<DataPoint> dataPoints) { this.dataPoints = dataPoints; dataPointCount = dataPoints.size(); } // Constructs a data object with an empty list of DataPoints public Data() { this.dataPoints = new ArrayList<>(); dataPointCount = 0; } // Adds a DataPoint and returns its' position in the list public int addData(DataPoint dataPoint) { dataPoints.add(dataPoint); // Increment after returning data point count return dataPointCount++; } public ArrayList<DataPoint> getDataPoints() { return dataPoints; } public int getDataPointCount() { return dataPointCount; } // Converts all DataPoints into a sequence of bytes for hashing public byte[] getDataBytes() { ArrayList<byte[]> allBytes = new ArrayList<>(); for (DataPoint dp : dataPoints) allBytes.add(dp.getBytes()); return ByteUtils.combineByteArrays(allBytes); } // Returns a string containing the formatted strings of each data point public String toString() { StringBuilder sb = new StringBuilder(); for (DataPoint dp : dataPoints){ sb.append(dp.getFormattedDataString()); sb.append("\n"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } }
package inheritance.service; public class MotorVehicle { protected String modelName; protected int modelNumber; protected int modelPrice; public MotorVehicle() { } public MotorVehicle(String modelName, int modelNumber, int modelPrice) { this.modelName = modelName; this.modelNumber = modelNumber; this.modelPrice = modelPrice; } void display() { System.out.println("Model Name : " + this.modelName); System.out.println("Model Number : " + modelNumber); System.out.println("Model price : " + modelPrice); } }
package com.enat.sharemanagement.attendance; import com.enat.sharemanagement.agenda.AgendaVote; import com.enat.sharemanagement.shareholder.Shareholder; import com.enat.sharemanagement.utils.Auditable; import com.enat.sharemanagement.vote.Candidate; import lombok.AccessLevel; import lombok.Data; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import java.util.Set; @Entity(name = "attendance") @Data public class Attendance extends Auditable implements Serializable { @Id private long id; @OneToOne private Shareholder shareholder; private boolean attend; private boolean voted; @ManyToMany(cascade = CascadeType.ALL) @JoinTable( name = "shareholder_vote", joinColumns = @JoinColumn(name = "shareholder_id"), inverseJoinColumns = @JoinColumn(name = "candidate_id") ) private List<Candidate> candidates; private String budgetYear; private BigDecimal noOfShares; @ManyToOne private Delegate delegate; @OneToMany(mappedBy = "attendance") Set<AgendaVote> attendance; }
package com.example.david.helloworld; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; public class MyActivity extends Activity { TextView txtVw; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); txtVw = (TextView) findViewById(R.id.colorDisplayer); Button b1 = (Button)findViewById(R.id.but1); Button b2 = (Button)findViewById(R.id.but2); Button b3 = (Button)findViewById(R.id.but3); RadioButton r1 = (RadioButton)findViewById(R.id.rad1); RadioButton r2 = (RadioButton)findViewById(R.id.rad2); RadioButton r3 = (RadioButton)findViewById(R.id.rad3); b1.setOnClickListener(new ColorSetter(Color.RED)); b2.setOnClickListener(new ColorSetter(Color.BLUE)); b3.setOnClickListener(new ColorSetter(Color.GREEN)); r1.setOnClickListener(new ColorSetter(Color.RED)); r2.setOnClickListener(new ColorSetter(Color.BLUE)); r3.setOnClickListener(new ColorSetter(Color.GREEN)); } public void setRegionColor(int color) { txtVw.setBackgroundColor(color); } private class ColorSetter implements View.OnClickListener { private int regionColor; public ColorSetter(int regionColor) { this.regionColor = regionColor; } @Override public void onClick(View v) { setRegionColor(regionColor); } } }
import java.util.Arrays; import java.util.Scanner; public class BattleShip { private int size; private int loc[][]; private int hitNum; // 构造函数 BattleShip(int initSize){ size = initSize; hitNum = 0; } // 生成随机位置 public int[][] getRandomLoc(int maxRow, int maxCol){ int initRow, initCol; int randomLoc[][] = {}; boolean isVertical = true; int TorF = (int)(Math.random() * 2); // 随机判断垂直或水平 if (TorF == 0){ isVertical = true; } else if (TorF == 1){ isVertical = false; } else{ System.out.println("Something is wrong with the random direction."); } if (isVertical){ //System.out.println("isVertical"); initRow = (int)(Math.random() * (maxRow - size)); initCol = (int)(Math.random() * (maxCol)); if (size == 2){ int[][] tempLoc = {{initRow, initCol}, {initRow + 1, initCol}}; randomLoc = tempLoc; } if (size == 3){ int[][] tempLoc = {{initRow, initCol}, {initRow + 1, initCol}, {initRow + 2, initCol}}; randomLoc = tempLoc; } } else{ //System.out.println("!isVertical"); initRow = (int)(Math.random() * (maxRow)); initCol = (int)(Math.random() * (maxCol - size)); if (size == 2){ int[][] tempLoc = {{initRow, initCol}, {initRow, initCol + 1}}; randomLoc = tempLoc; } if (size == 3){ int[][] tempLoc = {{initRow, initCol}, {initRow, initCol + 1}, {initRow, initCol + 2}}; randomLoc = tempLoc; } } return randomLoc; } // 确定无重叠后确定位置 public void setLoc(int finalLoc[][]){ loc = finalLoc; } // 判断是否被击中 public boolean isHit(int hitLoc[]){ for (int i = 0; i < size; i++){ if (loc[i][0] == hitLoc[0] && loc[i][1] == hitLoc[1]){ hitNum++; return true; } } return false; } // 判断是否击沉 public boolean isSink(){ if (hitNum >= size){ return true; } return false; } // 返回大小 public int getSize(){ return size; } // 返回位置 public int[][] getLoc(){ return loc; } // 打印状态(测试用) public void printStatus(){ System.out.println("Size = " + size); System.out.println("Loc = "); for (int i = 0; i < size; i++){ System.out.println(Arrays.toString(loc[i])); } System.out.println("\n"); } // 主函数 public static void main(String args[]){ BattleShip testShip = new BattleShip(3); int testPos[][] = testShip.getRandomLoc(7, 7); for (int i = 0; i < 3; i++){ System.out.println(Arrays.toString(testPos[i])); } testShip.setLoc(testPos); Scanner input = new Scanner(System.in); int row, col; System.out.println("请输入打击的横坐标: "); row = input.nextInt(); System.out.println("请输入打击的纵坐标: "); col = input.nextInt(); int[] tempLoc = {row, col}; System.out.println(testShip.isHit(tempLoc)); input.close(); } }
package com.example.android.pokefinder.data; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import java.util.List; @Dao public interface SavedPokemonDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(Pokemon pokemon); @Query("SELECT * FROM pokemon") List<Pokemon> getAll(); @Delete void delete(Pokemon pokemon); }
package SUT.SE61.Team07.Controller; import SUT.SE61.Team07.Entity.*; import SUT.SE61.Team07.Repository.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @RestController @CrossOrigin(origins = "http://localhost:4200") class StaffController { private StaffRepository staffrepository; public StaffController(StaffRepository staffrepository) { this.staffrepository = staffrepository; } @GetMapping("/Staff-list") public Collection<Staff> staffs() { return staffrepository.findAll().stream().collect(Collectors.toList()); } @GetMapping("/Staff/{staffId}") public Staff staffFind(@PathVariable("staffId") Long id) { return staffrepository.findByStaffId(id); } @GetMapping("/Staffuser/{staffUser}") public Staff staffuser(@PathVariable("staffUser") String staffUser) { return staffrepository.findByStaffUser(staffUser); } @GetMapping("/staffpassword/{staffPass}") public Staff staffpassword(@PathVariable("staffPass") String staffPass) { return staffrepository.findByStaffPass(staffPass); } @GetMapping("/StaffOnline/{status}") public Staff staffonline(@PathVariable("status")String status){ return staffrepository.findByOnline(status); } @PostMapping("/Staff/Staffuser/{staffUser}/staffpassword/{staffPass}") public ResponseEntity<Map<String, Object>> staffcheck(@PathVariable("staffUser") String staffUser, @PathVariable("staffPass") String staffPass) { Staff staffuser = this.staffrepository.findByStaffUser(staffUser); Staff staffpass = this.staffrepository.findByStaffPass(staffPass); if ((staffuser != null) && (staffpass != null)) { Map<String, Object> json = new HashMap<String, Object>(); json.put("success", true); json.put("status", "found"); json.put("user", staffuser); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.add("X-Fsl-Location", "/"); headers.add("X-Fsl-Response-Code", "302"); return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK)); } else { Map<String, Object> json = new HashMap<String, Object>(); json.put("success", false); json.put("status", "not found"); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.add("X-Fsl-Location", "/"); headers.add("X-Fsl-Response-Code", "404"); return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK)); } } @PostMapping("/Staff/StaffOnline/{onlineId}/staffName/{staffName}/staffUser/{staffUser}/staffPass/{staffPass}/staffPhone/{staffPhone}") public ResponseEntity<Map<String, Object>> setStaffOnline(@PathVariable("onlineId") Long onlineId, @PathVariable("staffName") String staffName, @PathVariable("staffUser") String staffUser, @PathVariable("staffPass") String staffPass, @PathVariable("staffPhone") String staffPhone) { System.out.println("=============stafflogin================="); System.out.println(onlineId); System.out.println(staffName); System.out.println(staffUser); System.out.println(staffPass); System.out.println(staffPhone); System.out.println("================stafflogin=============="); Staff staff = this.staffrepository.findByStaffId(onlineId); if (staff != null) { staff.setStaffId(onlineId); staff.setStaffName(staffName); staff.setStaffUser(staffUser); staff.setStaffPass(staffPass); staff.setStaffPhone(staffPhone); staff.setOnline("true"); this.staffrepository.save(staff); Map<String, Object> json = new HashMap<String, Object>(); json.put("success", true); json.put("status", "found"); json.put("user", staff); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.add("X-Fsl-Location", "/"); headers.add("X-Fsl-Response-Code", "302"); return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK)); } else { Map<String, Object> json = new HashMap<String, Object>(); json.put("success", false); json.put("status", "not found"); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.add("X-Fsl-Location", "/"); headers.add("X-Fsl-Response-Code", "404"); return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK)); } } @PostMapping("/Staff/StaffOffline/{onlineId}") public ResponseEntity<Map<String, Object>> setStaffOffline(@PathVariable("onlineId") Long onlineId) { Staff staff = this.staffrepository.findByStaffId(onlineId); if (staff != null) { staff.setStaffId(onlineId); staff.setOnline("false"); this.staffrepository.save(staff); Map<String, Object> json = new HashMap<String, Object>(); json.put("success", true); json.put("status", "found"); json.put("user", staff); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.add("X-Fsl-Location", "/"); headers.add("X-Fsl-Response-Code", "302"); return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK)); } else { Map<String, Object> json = new HashMap<String, Object>(); json.put("success", false); json.put("status", "not found"); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.add("X-Fsl-Location", "/"); headers.add("X-Fsl-Response-Code", "404"); return (new ResponseEntity<Map<String, Object>>(json, headers, HttpStatus.OK)); } } }
package com.xu.easyweb.service; import com.xu.easyweb.dao.BaseDao; import com.xu.easyweb.util.EntityMap; import com.xu.easyweb.util.paging.Pager; import com.xu.easyweb.util.paging.SQLField; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.transform.ResultTransformer; import org.hibernate.type.Type; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * 服务层接口实现 * author:zht */ @Service public class BaseServiceImpl implements BaseService { private BaseDao baseDao; public BaseServiceImpl() { } public BaseDao getBaseDao() { return baseDao; } @Resource public void setBaseDao(BaseDao baseDao) { this.baseDao = baseDao; } public <T> T get(Class<T> clazz, String id) { return baseDao.get(clazz, id); } public <T> T get(Class<T> clazz, String id, boolean newSession) { return baseDao.get(clazz, id, newSession); } public <T> T load(Class<T> clazz, String id) { return baseDao.load(clazz, id); } public <T> List<T> get(Class<T> clazz, String[] ids) { return baseDao.get(clazz, ids); } public <T> T get(Class<T> clazz, String propertyName, Object value) { return baseDao.get(clazz, propertyName, value); } public <T> List<T> getList(Class<T> clazz,String propertyName, Object value) { return baseDao.getList(clazz, propertyName, value); } public void batchDel(List<String> sqls) throws Exception { baseDao.batchDel(sqls); } public String getSequenceId(Class<?> clazz) { return baseDao.getSequenceId(clazz); } public Map<String, Object> getQueryResultToMap(String sql) { return baseDao.getQueryResultToMap(sql); } public List<Map<String, Object>> getQueryResultToListMap(String sql) { return baseDao.getQueryResultToListMap(sql); } public <T> List<T> getAll(Class<T> clazz) { return baseDao.getAll(clazz); } public Long getTotalCount(Class<?> clazz) { return baseDao.getTotalCount(clazz); } public boolean isUnique(Class<?> clazz, String propertyName, Object oldValue, Object newValue) { return baseDao.isUnique(clazz, propertyName, oldValue, newValue); } public boolean isExist(Class<?> clazz, String propertyName, Object value) { return baseDao.isExist(clazz, propertyName, value); } public String save(Object entity) { return baseDao.save(entity); } public <T> String save(List<T> list) { return baseDao.save(list); } @Override public <T> String saveBatch( List<T> list ) { return baseDao.saveBatch( list ); } public void update(Object entity) { baseDao.update(entity); } public <T> void update(List<T> list) { baseDao.update(list); } public void updateByHql(String hql, Map params) { baseDao.updateByHql(hql, params); } public void saveOrUpdate(Object entity) { baseDao.saveOrUpdate(entity); } public <T> void saveOrUpdate(List<T> list) { baseDao.saveOrUpdate(list); } public void delete(Object entity) { baseDao.delete(entity); } public <T> void delete(List<T> list) { baseDao.delete(list); } public void delete(Class<?> clazz, String id) { baseDao.delete(clazz, id); } public void delete(Class<?> clazz, String[] ids) { baseDao.delete(clazz, ids); } public void flush() { baseDao.flush(); } public void clear() { baseDao.clear(); } public void evict(Object object) { baseDao.evict(object); } public Pager findByPager(Class<?> clazz,Pager pager) { return baseDao.findByPager(clazz, pager); } public Pager findByPager(Pager pager, DetachedCriteria detachedCriteria) { return baseDao.findByPager(pager, detachedCriteria); } public <T> List<T> find(Class<T> clazz, List<Criterion> criterias, List<Order> orderBy, int start, int limit) { return baseDao.find(clazz, criterias, orderBy, start, limit); } public <T> List<T> find(Class<T> clazz, List<? extends SQLField> fields) { return baseDao.find(clazz, fields); } public List findByHql(String hql, Map params) { return baseDao.findByHql(hql, params); } public Pager findByHql(String hql, Map params, Pager pager) throws Exception { return baseDao.findByHql(hql, params, pager); } public List findBySql(String sql) { return baseDao.findBySql(sql); } public List findBySql(String sql,Class clazz) { return baseDao.findBySql(sql, clazz); } public List findBySql(String sql, List<EntityMap> clazzList, Map params) { return baseDao.findBySql(sql, clazzList, params); } public List findBySql(String sql, List<EntityMap> clazzList, Map<String, Type> scalarMap, Map params) throws Exception { return baseDao.findBySql(sql, clazzList, scalarMap, params); } public Pager findBySql(String sql, List<EntityMap> clazzList, Map<String, Type> scalarMap, Map params, Pager pager) throws Exception { return baseDao.findBySql(sql, clazzList, scalarMap, params, pager); } public Pager findBySql(String sql, List<EntityMap> clazzList, Map<String, Type> scalarMap, Map params, Pager pager, ResultTransformer rt) throws Exception { return baseDao.findBySql(sql, clazzList, scalarMap, params, pager, rt); } public void persist(Object entity) { baseDao.persist(entity); } public Object merge(Object object) { return baseDao.merge(object); } /** * * findByCustomSql(自定义分页) * TODO(列名对应返回的名称) * @param param * @return return * @Exception Exception * @author liao Date:2015.9.9 */ public Pager findBySqlCustomPagerList(String sql,Pager pager) throws Exception { return baseDao.findBySqlCustomPagerList(sql,pager); } }
package com.app.gamaacademy.cabrasdoagrest.bankline.test.service; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import com.app.gamaacademy.cabrasdoagrest.bankline.dtos.PlanoContaDTO; import com.app.gamaacademy.cabrasdoagrest.bankline.dtos.TransacaoDTO; import com.app.gamaacademy.cabrasdoagrest.bankline.exceptions.BanklineBusinessException; import com.app.gamaacademy.cabrasdoagrest.bankline.exceptions.ErrorCode; import com.app.gamaacademy.cabrasdoagrest.bankline.models.Conta; import com.app.gamaacademy.cabrasdoagrest.bankline.models.PlanoConta; import com.app.gamaacademy.cabrasdoagrest.bankline.models.TipoOperacao; import com.app.gamaacademy.cabrasdoagrest.bankline.models.Transacao; import com.app.gamaacademy.cabrasdoagrest.bankline.repository.ContaRepository; import com.app.gamaacademy.cabrasdoagrest.bankline.repository.TransacaoRepository; import com.app.gamaacademy.cabrasdoagrest.bankline.service.TransacaoServiceImpl; import com.app.gamaacademy.cabrasdoagrest.bankline.service.UsuarioService; import com.app.gamaacademy.cabrasdoagrest.bankline.test.builders.ContaBuilder; import com.app.gamaacademy.cabrasdoagrest.bankline.test.builders.PlanoContaBuilder; import com.app.gamaacademy.cabrasdoagrest.bankline.test.builders.TransacaoBuilder; import com.app.gamaacademy.cabrasdoagrest.bankline.test.builders.UsuarioBuilder; import com.app.gamaacademy.cabrasdoagrest.bankline.utils.Mapper; @SpringBootTest @TestMethodOrder(OrderAnnotation.class) public class TransacaoServiceTest { @Autowired private TransacaoServiceImpl service; @Autowired private TransacaoBuilder umaTransacao; @Autowired private ContaBuilder umaConta; @Autowired private PlanoContaBuilder umPlano; @Autowired private UsuarioBuilder umUsuario; @MockBean private TransacaoRepository repositoryMock; @MockBean private ContaRepository contaRepositoryMock; @MockBean private UsuarioService usuarioServiceMock; @BeforeEach public void reset() { umaTransacao.inicial(); umaConta.inicial(); // when(repositoryMock.findByLoginOrCpfEquals(any(String.class), // any(String.class))).thenReturn(null); } @Test @Order(1) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação nula") public void criandoTransacaoNula() { BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { service.salvar(null); }); assertEquals(exception.getErrorCode(), ErrorCode.E0001); } @Test @Order(2) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação sem conta origem") public void criandoTransacaoSemContaOrigem() { BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { service.salvar(umaTransacao.comValor(10.0).buildDto()); }); assertEquals(exception.getErrorCode(), ErrorCode.E0002); assertEquals(exception.getProperty(), "contaOrigem"); } @Test @Order(3) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação conta origem inexistente") public void criandoTransacaoComContaOrigemInexistente() { Conta conta = umaConta.build(); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.empty()); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { TransacaoDTO transacao = umaTransacao.daConta(conta).comValor(10.0).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0003); assertEquals(exception.getProperty(), "contaOrigem"); } @Test @Order(4) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação com valor menor igual a zero") public void criandoTransacaoComValorZero() { Conta conta = umaConta.build(); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { TransacaoDTO transacao = umaTransacao.daConta(conta).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0004); assertEquals(exception.getProperty(), "valor"); } @Test @Order(5) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação com plano de conta nulo") public void criandoTransacaoComPlanoNulo() { Conta conta = umaConta.build(); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { TransacaoDTO transacao = umaTransacao.comValor(10.0).comPlano(null).daConta(conta).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0002); assertEquals(exception.getProperty(), "plano"); } @Test @Order(6) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação com plano de conta inválido") public void criandoTransacaoComPlanoInvalido() { Conta conta = umaConta.build(); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { TransacaoDTO transacao = umaTransacao.comValor(10.0).comPlano(umPlano.build()).daConta(conta).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0002); assertEquals(exception.getProperty(), "tipo"); } @Test @Order(7) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação com plano de conta não pertencente ao usuário") public void criandoTransacaoComPlanoNaoPertencenteAoUsuario() { Conta conta = umaConta.doUsuario(umUsuario.comId().build()).build(); List<PlanoContaDTO> listaPlanos = new ArrayList<PlanoContaDTO>(); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)); when(usuarioServiceMock.obterPlanoContas(anyInt())).thenReturn(listaPlanos); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { PlanoConta planoConta = umPlano.comId(1).comTipo(TipoOperacao.RECEITA).build(); TransacaoDTO transacao = umaTransacao.comValor(10.0).comPlano(planoConta).daConta(conta).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0003); assertEquals(exception.getProperty(), "tipo"); } /* * @Test * * @Order(8) * * @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação com plano de conta com nome inválido" * ) public void criandoTransacaoComPlanoDeNomeInvalido() { Conta conta = * umaConta.doUsuario(umUsuario.comId().build()).build(); PlanoConta planoConta * = umPlano.comId(1).comNome("Luz").comTipo(TipoOperacao.DESPESA).build(); * * List<PlanoContaDTO> listaPlanos = new ArrayList<PlanoContaDTO>(); * listaPlanos.add(umPlano.buildDto()); * * when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util. * Optional.of(conta)); * when(usuarioServiceMock.obterPlanoContas(anyInt())).thenReturn(listaPlanos) * .thenReturn(new ArrayList<PlanoContaDTO>()); * * Throwable exception = assertThrows(DataRetrievalFailureException.class, () -> * { TransacaoDTO transacao = * umaTransacao.comValor(-10.0).daConta(conta).comPlano(planoConta).buildDto(); * * service.salvar(transacao); }); * * String mensagemRecebida = exception.getMessage(); * System.out.println(mensagemRecebida); String mensagemEsperada = * "Nome do Plano de conta não está cadastrado para o usuário"; * * assertTrue(mensagemRecebida.contains(mensagemEsperada)); } */ @Test @Order(9) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação do tipo transferência com conta destino nula") public void criandoTransacaoTransferenciaContaDestinoNula() { Conta conta = umaConta.doUsuario(umUsuario.comId().build()).build(); PlanoConta planoConta = umPlano.comId(1).comNome("PIX").comTipo(TipoOperacao.TRANSFERENCIA).build(); List<PlanoContaDTO> listaPlanos = new ArrayList<PlanoContaDTO>(); listaPlanos.add(umPlano.buildDto()); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)); when(usuarioServiceMock.obterPlanoContas(anyInt())).thenReturn(listaPlanos); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { TransacaoDTO transacao = umaTransacao.comValor(-10.0).daConta(conta).comPlano(planoConta).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0002); assertEquals(exception.getProperty(), "contaDestino"); } @Test @Order(10) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação do tipo transferência com conta destino igual a conta origem") public void criandoTransacaoTransferenciaContaDestinoIgualContaOrigem() { Conta conta = umaConta.doUsuario(umUsuario.comId().build()).build(); PlanoConta planoConta = umPlano.comId(1).comNome("PIX").comTipo(TipoOperacao.TRANSFERENCIA).build(); List<PlanoContaDTO> listaPlanos = new ArrayList<PlanoContaDTO>(); listaPlanos.add(umPlano.buildDto()); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)); when(usuarioServiceMock.obterPlanoContas(anyInt())).thenReturn(listaPlanos); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { TransacaoDTO transacao = umaTransacao.comValor(-10.0).daConta(conta).paraConta(conta).comPlano(planoConta) .buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0005); } @Test @Order(11) @DisplayName("Deve lançar uma exceção ao tentar fazer uma transação do tipo transferência com conta destino não existente") public void criandoTransacaoTransferenciaContaDestinoaoExistente() { Conta conta = umaConta.doUsuario(umUsuario.comId().build()).build(); PlanoConta planoConta = umPlano.comId(1).comNome("PIX").comTipo(TipoOperacao.TRANSFERENCIA).build(); List<PlanoContaDTO> listaPlanos = new ArrayList<PlanoContaDTO>(); listaPlanos.add(umPlano.buildDto()); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)) .thenReturn(java.util.Optional.empty()); when(usuarioServiceMock.obterPlanoContas(anyInt())).thenReturn(listaPlanos); BanklineBusinessException exception = assertThrows(BanklineBusinessException.class, () -> { umaConta.inicial(); Conta contaDestino = umaConta.doUsuario(null).build(); TransacaoDTO transacao = umaTransacao.comValor(-10.0).daConta(conta).paraConta(contaDestino) .comPlano(planoConta).buildDto(); service.salvar(transacao); }); assertEquals(exception.getErrorCode(), ErrorCode.E0003); assertEquals(exception.getProperty(), "contaDestino"); } @Test @Order(12) @DisplayName("Deve retornar o id da transação em caso de sucesso") public void criandoTransacaoValida() throws Exception { Conta conta = umaConta.doUsuario(umUsuario.comId().build()).build(); umaConta.inicial(); Conta contaDestino = umaConta.doUsuario(umUsuario.comId().build()).build(); PlanoConta planoConta = umPlano.comId(1).comNome("PIX").comTipo(TipoOperacao.TRANSFERENCIA).build(); List<PlanoContaDTO> listaPlanos = new ArrayList<PlanoContaDTO>(); listaPlanos.add(umPlano.buildDto()); when(contaRepositoryMock.findById(any(Long.class))).thenReturn(java.util.Optional.of(conta)) .thenReturn(java.util.Optional.of(contaDestino)); when(usuarioServiceMock.obterPlanoContas(anyInt())).thenReturn(listaPlanos); Transacao transacao = umaTransacao.comId(1).comValor(-10.0).daConta(conta).paraConta(contaDestino) .comPlano(planoConta).build(); when(repositoryMock.save(any(Transacao.class))).thenReturn(transacao); Integer idRecebido = service.salvar(Mapper.convertTransacaoEntityToDto(transacao)); Integer idEsperado = transacao.getId(); assertEquals(idEsperado, idRecebido); } }
package la.opi.verificacionciudadana.models; /** * Created by Jhordan on 01/03/15. */ public class ImageEvidence { private String evidence; private String title; public String getEvidence() { return evidence; } public void setEvidence(String evidence) { this.evidence = evidence; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
package factorioMain; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; public class ItemSlot { private Image image; private int number = 1; private String name; public Image getImage() { return this.image; } public ItemSlot(Image image, String name) { this.image = image; this.setName(name); } public ItemSlot(Entity e, int number) { this.image = e.getImage(); this.setName(e.getName()); this.number = number; } public void draw(Graphics g, int x, int y) { g.drawImage(this.image,x,y); } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.espendwise.manta.web.controllers; import com.espendwise.manta.model.data.GroupData; import com.espendwise.manta.model.view.DistributorListView; import com.espendwise.manta.service.DistributorService; import com.espendwise.manta.spi.AutoClean; import com.espendwise.manta.spi.Locate; import com.espendwise.manta.util.AppComparator; import com.espendwise.manta.util.Constants; import com.espendwise.manta.util.SelectableObjects; import com.espendwise.manta.util.Utility; import com.espendwise.manta.util.alert.ArgumentedMessage; import com.espendwise.manta.util.criteria.DistributorListViewCriteria; import com.espendwise.manta.web.forms.LocateDistributorFilterForm; import com.espendwise.manta.web.forms.LocateDistributorFilterResultForm; import com.espendwise.manta.web.forms.WebForm; import com.espendwise.manta.web.util.SessionKey; import com.espendwise.manta.web.util.WebAction; import com.espendwise.manta.web.util.WebErrors; import com.espendwise.manta.web.util.WebSort; import com.google.gson.Gson; import org.apache.log4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpSession; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Controller @Locate @RequestMapping(UrlPathKey.LOCATE.LOCATE_DISTRIBUTOR) @SessionAttributes({SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT, SessionKey.LOCATE_DISTRIBUTOR_FILTER}) @AutoClean(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) public class LocateDistributorFilterController extends BaseController { private static final Logger logger = Logger.getLogger(LocateDistributorFilterController.class); private DistributorService distributorService; @Autowired public LocateDistributorFilterController(DistributorService distributorService) { this.distributorService = distributorService; } @RequestMapping(value = {"", "/multi"}, method = RequestMethod.GET) public String multiFilter(@ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER) LocateDistributorFilterForm filterForm, @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) LocateDistributorFilterResultForm filterResultForm) { initFilter(filterForm, true); filterResultForm.setMultiSelected(true); return "distributor/locate"; } @RequestMapping(value = "/single", method = RequestMethod.GET) public String singleFilter(@ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER) LocateDistributorFilterForm filterForm, @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) LocateDistributorFilterResultForm filterResultForm) { initFilter(filterForm, true); filterResultForm.setMultiSelected(false); return "distributor/locate"; } @RequestMapping(value = "/filter", method = RequestMethod.POST) public String findDistributors(WebRequest request, @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) LocateDistributorFilterResultForm form, @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER) LocateDistributorFilterForm filterForm) throws Exception { WebErrors webErrors = new WebErrors(request); List<? extends ArgumentedMessage> validationErrors = WebAction.validate(filterForm); if (!validationErrors.isEmpty()) { webErrors.putErrors(validationErrors); return "distributor/locate"; } form.reset(); DistributorListViewCriteria criteria = new DistributorListViewCriteria(getStoreId(), Constants.FILTER_RESULT_LIMIT.DISTRIBUTOR); if (Utility.isSet(filterForm.getDistributorId())) { criteria.setDistributorId(filterForm.getDistributorId()); } if (Utility.isSet(filterForm.getDistributorName())) { criteria.setDistributorName(filterForm.getDistributorName()); criteria.setDistributorNameFilterType(filterForm.getDistributorNameFilterType()); } criteria.setStoreId(getStoreId()); criteria.setActiveOnly(!Utility.isTrue(filterForm.getShowInactive())); List<DistributorListView> distributors = distributorService.findDistributorsByCriteria(criteria); SelectableObjects<DistributorListView> selectableObj = new SelectableObjects<DistributorListView>( distributors, new ArrayList<DistributorListView>(), AppComparator.DISTRIBUTOR_LIST_VIEW_COMPARATOR ); form.setSelectedDistributors(selectableObj); WebSort.sort(form, DistributorListView.DISTRIBUTOR_NAME); return "distributor/locate"; } @ResponseBody @RequestMapping(value = "/selected", method = RequestMethod.POST, produces = "application/json; charset=UTF-8") public String returnSelected(HttpSession session, @RequestParam(value = "filter", required = false) String filter, @RequestParam(value = "index", required = false) String index, @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) LocateDistributorFilterResultForm filterResultForm) throws Exception { logger.info("returnSelected()=> BEGIN, filter:" + filter); List<DistributorListView> selected = filterResultForm.getSelectedDistributors().getSelected(); if(!filterResultForm.getMultiSelected()){ selected = Utility.toList(selected.get(0)); } if (Utility.isSet(filter)) { List<String> filterKeys = Arrays.asList(Utility.split(filter, ".")); WebForm targetForm = (WebForm) session.getAttribute(filterKeys.get(0)); Method method = null; if (index != null) { method = BeanUtils.findMethod(targetForm.getClass(), Utility.javaBeanPath(filterKeys.subList(1, filterKeys.size()).toArray(new String[filterKeys.size() - 1])), Integer.class, List.class); logger.info("returnSelected()=> method:" + method); method.invoke(targetForm, Integer.valueOf(index), selected); } else { method = BeanUtils.findMethod(targetForm.getClass(), Utility.javaBeanPath(filterKeys.subList(1, filterKeys.size()).toArray(new String[filterKeys.size() - 1])), List.class); logger.info("returnSelected()=> method:" + method); method.invoke(targetForm, selected); } } logger.info("returnSelected()=> END."); return new Gson().toJson(selected); } @RequestMapping(value = "/filter/sortby/{field}", method = RequestMethod.GET) public String sort(@ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) LocateDistributorFilterResultForm form, @PathVariable String field) throws Exception { WebSort.sort(form, field); return "distributor/locate"; } @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT) public LocateDistributorFilterResultForm init(HttpSession session) { LocateDistributorFilterResultForm locateDistributorFilterResult = (LocateDistributorFilterResultForm) session.getAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER_RESULT); if (locateDistributorFilterResult == null) { locateDistributorFilterResult = new LocateDistributorFilterResultForm(); } return locateDistributorFilterResult; } @ModelAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER) public LocateDistributorFilterForm initFilter(HttpSession session) { LocateDistributorFilterForm locateDistributorFilter = (LocateDistributorFilterForm) session.getAttribute(SessionKey.LOCATE_DISTRIBUTOR_FILTER); return initFilter(locateDistributorFilter, false); } private LocateDistributorFilterForm initFilter(LocateDistributorFilterForm locateDistributorFilter, boolean init) { if (locateDistributorFilter == null) { locateDistributorFilter = new LocateDistributorFilterForm(); } // init at once if (init && !locateDistributorFilter.isInitialized()) { locateDistributorFilter.initialize(); } return locateDistributorFilter; } }
package api; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /** * 提供api给其他服务(打包) */ @FeignClient(name="spring-cloud-consul-consumer",path = "helloProducer") public interface IHelloProducerService { @GetMapping("/sayHello") String sayHello(String name); }
/*Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". click to show clarification. Clarification: What constitutes a word? A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. How about multiple spaces between two words? Reduce them to a single space in the reversed string. */ public class Solution { public static String reverseWords(String s) { String result = ""; String[] temp = s.trim().split(" "); for(int i = temp.length - 1; i >= 0 ; i--){ if(!temp[i].trim().equals("")) { result = result + temp[i] + " "; } } return result.trim(); } public static void main(String[] args){ String s = "the sky is blue"; String s1 = " a b "; System.out.println(reverseWords(s)); System.out.println(reverseWords(s1)); } }
package com.liyinghua.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.github.pagehelper.PageInfo; import com.liyinghua.common.StatusMessages; import com.liyinghua.entity.Article; import com.liyinghua.entity.Channel; import com.liyinghua.entity.Link; import com.liyinghua.entity.User; import com.liyinghua.service.ArticleService; import com.liyinghua.service.ChannelService; import com.liyinghua.service.UserService; @Controller @RequestMapping("admin") public class AdminController { @Autowired private UserService service; @Autowired private ChannelService channelService; @Autowired private ArticleService service2; /** * + * @Title: index * @Description: 跳转中心页面 * @return * @return: String */ @RequestMapping("hello") public String index(Model m) { return "admin/index"; } /** * * @Title: getUsersList * @Description: 获取用户列表(包括分页和模糊查询) * @param hr * @param mohu * @param fy * @return * @return: String */ @RequestMapping("userlist") private String getUsersList(HttpServletRequest hs ,String mohu,@RequestParam(defaultValue = "1")Integer fy) { System.out.println(mohu); PageInfo<User> info=service.getUsersList(fy,mohu); hs.setAttribute("info",info); hs.setAttribute("mohu", mohu); return "admin/user/userlist"; } /** * * @Title: updLocked * @Description: 修改用户状态 (首先要进行用户是否存在查询,其次再判断传过来的状态值是否符合要求) * @return * @return: Object */ @ResponseBody @RequestMapping("updLocked") private Object updLocked(Integer id,Integer locked) { Boolean n=service.getUserById(id); if(n) { return new StatusMessages(1, "信息有误,请刷新", null); } System.out.println(locked); if(locked==1||locked==0) { }else { return new StatusMessages(2, "状态有误,请联系管理员", null); } if(service.updLocked(id,locked)>0) { return new StatusMessages(0, "修改成功", null); } return new StatusMessages(3, "修改失败,请联系管理员", null); } /** * * @Title: toHomePage * @Description: 跳转首页(传入频道列表) * @param hs * @return * @return: String */ @RequestMapping(value = {"/toHomePage","/"}) private String toHomePage(HttpServletRequest hs) { List<Article> hotNews=channelService.getHotNews(); List<Channel> list=channelService.getChannelList(); List<Article> imgArticles = service2.getImgArticles(10); hs.setAttribute("imgArticles", imgArticles); hs.setAttribute("list", list); hs.setAttribute("hotNews", hotNews); hs.setAttribute("yz", true); hs.setAttribute("yz", true); return "admin/news/homePage"; } @RequestMapping("UserHello") private String UserHello() { return "admin/userIndex"; } }
package service; import com.github.kreker721425.marvel.Application; import com.github.kreker721425.marvel.dto.CharacterDto; import com.github.kreker721425.marvel.dto.ComicBookDto; import com.github.kreker721425.marvel.entity.CharacterEntity; import com.github.kreker721425.marvel.entity.ComicBookEntity; import com.github.kreker721425.marvel.mapper.CharacterMapper; import com.github.kreker721425.marvel.mapper.ComicBookMapper; import com.github.kreker721425.marvel.repository.CharacterRepository; import com.github.kreker721425.marvel.repository.ComicBookRepository; import com.github.kreker721425.marvel.service.impl.CharacterServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Collection; import java.util.Collections; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @SpringBootTest(classes = Application.class) public class TestCharacterService { private CharacterRepository characterRepository; private CharacterServiceImpl characterService; @Autowired private CharacterMapper characterMapper; @BeforeEach void init() { characterRepository = mock(CharacterRepository.class); characterService = new CharacterServiceImpl(mock(ComicBookRepository.class), characterRepository, characterMapper, mock(ComicBookMapper.class)); } @Test public void findAllTest() { when(characterRepository.findAll()) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.findAll()); } @Test public void findByHeroNameTest() { when(characterRepository.findByHeroName(anyString())) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.findByHeroName("heroName")); } @Test public void findByHumanNameTest() { when(characterRepository.findByHeroName(anyString())) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.findByHeroName("humanName")); } @Test public void findByHeroNameAndHumanName() { when(characterRepository.findByHeroNameAndHumanName(anyString(),anyString())) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.findByHeroNameAndHumanName("heroName", "humanName")); } @Test public void sortByHeroNameTest() { when(characterRepository.sortByHeroName()) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.sortByHeroName()); } @Test public void sortByHumanNameTest() { when(characterRepository.sortByHumanName()) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.sortByHumanName()); } @Test public void saveTest() { UUID id = UUID.randomUUID(); CharacterEntity entity = new CharacterEntity(); entity.setId(id); CharacterDto dto = new CharacterDto(); dto.setId(id); when(characterRepository.save(entity)) .thenReturn(entity); assertEquals(id, characterService.save(dto).getId()); } @Test public void findCharactersByComicBookTest() { ComicBookEntity comicBookEntity = new ComicBookEntity(); ComicBookDto comicBookDto = new ComicBookDto(); when(characterRepository.findCharacterEntitiesByComics(comicBookEntity)) .thenReturn(Collections.emptyList()); assertEquals(Collections.emptyList(), characterService.findCharactersByComicBook(comicBookDto)); } }
package com.jobs.workbook.entites.user; import java.text.DateFormatSymbols; public class MonthlyEarnings implements Comparable { int id; String month; Long value; int count; public MonthlyEarnings(int id, Long value) { this.id = id; this.value = value; this.count = 0; this.month = this.getMonthForInt(id); } public int getId() { return id; } public void setId(int id) { this.id = id; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getMonth() { return month; } public void setMonth(String month) { this.month = month; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void incrementCount() { this.count++; } @Override public int compareTo(Object o) { int compareTo = ((MonthlyEarnings) o).getId(); return id - compareTo; } String getMonthForInt(int num) { String month = "wrong"; DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getMonths(); if (num >= 0 && num <= 11 ) { month = months[num]; } return month; } }
package com.ibiscus.myster.service.report; import java.util.Optional; import static com.ibiscus.myster.service.report.MonthInterval.currentMonthInterval; public class ReportCriteriaBuilder { private Long surveyId; private MonthInterval interval = currentMonthInterval(); private Optional<String> code = Optional.empty(); private Optional<String> name = Optional.empty(); public ReportCriteriaBuilder(Long surveyId) { this.surveyId = surveyId; } public ReportCriteriaBuilder usingCriteria(ReportCriteria criteria) { this.interval = criteria.getMonthInterval(); this.code = criteria.getCode(); this.name = criteria.getName(); return this; } public ReportCriteriaBuilder withInterval(MonthInterval value) { this.interval = value; return this; } public ReportCriteriaBuilder withCode(String value) { this.code = Optional.of(value); return this; } public ReportCriteriaBuilder withName(String value) { this.name = Optional.of(value); return this; } public ReportCriteria build() { return new ReportCriteria(surveyId, interval, code, name); } public static ReportCriteriaBuilder newReportCriteriaBuilder(Long surveyId) { return new ReportCriteriaBuilder(surveyId); } }
package cn.canlnac.onlinecourse.data.cache; import android.content.Context; import java.io.File; import javax.inject.Inject; import javax.inject.Singleton; import cn.canlnac.onlinecourse.data.cache.serializer.JsonSerializer; import cn.canlnac.onlinecourse.data.exception.NotFoundException; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import rx.Observable; /** * 实体类缓存实现. */ @Singleton public class EntityCacheImpl<E> implements EntityCache<E> { private static final String SETTINGS_FILE_NAME = "cn.canlnac.onlinecourse.settings"; private static final String SETTINGS_KEY_LAST_CACHE_UPDATE = "last_cache_update"; private static final long EXPIRATION_TIME = 60 * 10 * 1000; private final String DEFAULT_FILE_NAME; private final Context context; private final File cacheDir; private final JsonSerializer<E> serializer; private final FileManager fileManager; private final ThreadExecutor threadExecutor; /** * 构造函数 {@link EntityCacheImpl}. * * @param context android上下文 * @param cacheSerializer 缓存序列化. * @param fileManager 文件管理. */ @Inject public EntityCacheImpl( Context context, JsonSerializer<E> cacheSerializer, String cacheFileName, FileManager fileManager, ThreadExecutor executor ) { if (context == null || cacheSerializer == null || cacheFileName == null || fileManager == null || executor == null) { throw new IllegalArgumentException("Invalid null parameter"); } this.DEFAULT_FILE_NAME = cacheFileName + "_"; this.context = context.getApplicationContext(); this.cacheDir = this.context.getCacheDir(); this.serializer = cacheSerializer; this.fileManager = fileManager; this.threadExecutor = executor; } /** * 获取一个实体类 * @param id 实体类ID * @return */ @Override public Observable<E> get(final int id) { return Observable.create(subscriber -> { File file = EntityCacheImpl.this.buildFile(id); String fileContent = EntityCacheImpl.this.fileManager.readFileContent(file); E e = EntityCacheImpl.this.serializer.deserialize(fileContent); if (e != null) { subscriber.onNext(e); subscriber.onCompleted(); } else { subscriber.onError(new NotFoundException()); } }); } /** * 添加一个实体类的缓存 * @param id 实体类对象ID * @param e 实体类. */ @Override public void put(int id, E e) { if (e != null) { File file = this.buildFile(id); if (!isCached(id)) { String jsonString = this.serializer.serialize(e); this.executeAsynchronously(new CacheWriter(this.fileManager, file, jsonString)); setLastCacheUpdateTimeMillis(); } } } /** * 是否缓存 * @return */ @Override public boolean isCached(int id) { File file = this.buildFile(id); return this.fileManager.exists(file); } /** * 创建文件 * * @param id 实体类对象ID * @return */ private File buildFile(int id) { StringBuilder builder = new StringBuilder(); builder.append(this.cacheDir.getPath()); builder.append(File.separator); builder.append(DEFAULT_FILE_NAME); builder.append(id); return new File(builder.toString()); } /** * 数据是否过期了 * @return */ @Override public boolean isExpired() { long currentTime = System.currentTimeMillis(); long lastUpdateTime = this.getLastCacheUpdateTimeMillis(); boolean expired = ((currentTime - lastUpdateTime) > EXPIRATION_TIME); if (expired) { this.evictAll(); } return expired; } @Override public void evictAll() { this.executeAsynchronously(new CacheEvictor(this.fileManager, this.cacheDir)); } /** * 设置最近一次缓存更新的时间. */ private void setLastCacheUpdateTimeMillis() { long currentMillis = System.currentTimeMillis(); this.fileManager.writeToPreferences(this.context, SETTINGS_FILE_NAME, SETTINGS_KEY_LAST_CACHE_UPDATE, currentMillis); } /** * 在另外一个线程中执行一个任务. * * @param runnable 执行任务 */ private void executeAsynchronously(Runnable runnable) { this.threadExecutor.execute(runnable); } /** * 获取最后一次缓存更新的时间 * @return */ private long getLastCacheUpdateTimeMillis() { return this.fileManager.getFromPreferences(this.context, SETTINGS_FILE_NAME, SETTINGS_KEY_LAST_CACHE_UPDATE); } /** 写缓存的Runnable类,线程中执行 */ private static class CacheWriter implements Runnable { private final FileManager fileManager; private final File fileToWrite; private final String fileContent; CacheWriter(FileManager fileManager, File fileToWrite, String fileContent) { this.fileManager = fileManager; this.fileToWrite = fileToWrite; this.fileContent = fileContent; } @Override public void run() { this.fileManager.writeToFile(fileToWrite, fileContent); } } /** 清空缓存,Runnable任务,线程中运行 */ private static class CacheEvictor implements Runnable { private final FileManager fileManager; private final File cacheDir; CacheEvictor(FileManager fileManager, File cacheDir) { this.fileManager = fileManager; this.cacheDir = cacheDir; } @Override public void run() { this.fileManager.clearDirectory(this.cacheDir); } } }
package io; import java.io.*; /** * 文件的工具类 * @Author created by barrett in 2020/5/16 17:17 */ public class FileUtils { public static void main(String[] args) { try { InputStream is = new FileInputStream("src/main/resources/file/dest.txt"); OutputStream os = new FileOutputStream("src/main/resources/file/dest-2.txt"); copy(is,os); } catch (FileNotFoundException e) { e.printStackTrace(); } byte[] bytes=null; //图片 try { InputStream is = new FileInputStream("src/main/resources/img/man.gif"); ByteArrayOutputStream os = new ByteArrayOutputStream(); //todo 这种方式也行,更直接 // OutputStream os = new FileOutputStream("src/main/resources/img/man-2.gif"); copy(is,os); bytes = os.toByteArray(); System.out.println(bytes.length); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); FileOutputStream fos = new FileOutputStream("src/main/resources/img/man-2.gif"); copy(bis,fos); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * 文件拷贝 * @Author created by barrett in 2020/5/16 21:26 */ public static void copy(InputStream is , OutputStream os){ try{ int len; byte[] bytes = new byte[1024]; while((len=is.read(bytes))!=-1){ os.write(bytes,0,len); } os.flush(); }catch (Exception e){ e.printStackTrace(); }finally { close(is,os); } } /** * 通用的关闭流 * @Author created by barrett in 2020/5/16 16:59 */ public static void close(Closeable... ios){ for (Closeable io : ios) { if(io != null) { try { io.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package LC800_1000.LC850_900; import LeetCodeUtils.TreeNode; import java.util.ArrayList; import java.util.List; public class LC872_Leaf_Similar_Trees { public boolean leafSimilar(TreeNode root1, TreeNode root2) { List<Integer> l1 = new ArrayList<>(), l2 = new ArrayList<>(); dfs(root1, l1); dfs(root2, l2); return l1.equals(l2); } public void dfs (TreeNode root, List<Integer> list) { if (root.right == null && root.left == null) { list.add(root.val); return; } if (root.left != null) dfs(root.left, list); if (root.right != null) dfs(root.right, list); } }
package org.lxy.service; import org.lxy.dao.UserDao; import org.lxy.domain.User; import org.lxy.exception.LoginException; /** * @author menglanyingfei * @date 2017-4-27 */ public class UserService { // service层的登录方法 public User login(User user) throws LoginException { return new UserDao().findUser1(user); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * 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 com.openkm.frontend.client.widget.properties.version; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.gen2.table.client.AbstractScrollTable.ResizePolicy; import com.google.gwt.gen2.table.client.AbstractScrollTable.ScrollPolicy; import com.google.gwt.gen2.table.client.AbstractScrollTable.ScrollTableImages; import com.google.gwt.gen2.table.client.FixedWidthFlexTable; import com.google.gwt.gen2.table.client.FixedWidthGrid; import com.google.gwt.gen2.table.client.ScrollTable; import com.google.gwt.gen2.table.client.SelectionGrid; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.bean.GWTDocument; import com.openkm.frontend.client.bean.GWTPermission; import com.openkm.frontend.client.bean.GWTVersion; import com.openkm.frontend.client.service.OKMDocumentService; import com.openkm.frontend.client.service.OKMDocumentServiceAsync; import com.openkm.frontend.client.util.ScrollTableHelper; import com.openkm.frontend.client.util.Util; import com.openkm.frontend.client.widget.ConfirmPopup; /** * VersionScrollTable * * @author jllort */ public class VersionScrollTable extends Composite implements ClickHandler { private final OKMDocumentServiceAsync documentService = (OKMDocumentServiceAsync) GWT.create(OKMDocumentService.class); // Number of columns public static final int NUMBER_OF_COLUMNS = 7; private GWTDocument doc; private ScrollTable table; private FixedWidthFlexTable headerTable; private FixedWidthGrid dataTable; private ExtendedColumnSorter columnSorter; public List<String> versions; private boolean visibleButtons = true; private Button purge; private List<Button> buttonView; private List<Button> buttonRestore; public Map<Integer, GWTVersion> data = new HashMap<Integer, GWTVersion>(); /** * Version */ public VersionScrollTable() { versions = new ArrayList<String>(); buttonView = new ArrayList<Button>(); buttonRestore = new ArrayList<Button>(); purge = new Button(Main.i18n("version.purge.document"), this); purge.setStyleName("okm-CompactButton"); purge.setEnabled(false); ScrollTableImages scrollTableImages = new ScrollTableImages() { public AbstractImagePrototype scrollTableAscending() { return new AbstractImagePrototype() { public void applyTo(Image image) { image.setUrl("img/sort_asc.gif"); } public Image createImage() { return new Image("img/sort_asc.gif"); } public String getHTML() { return "<img border=\"0\" src=\"img/sort_asc.gif\"/>"; } }; } public AbstractImagePrototype scrollTableDescending() { return new AbstractImagePrototype() { public void applyTo(Image image) { image.setUrl("img/sort_desc.gif"); } public Image createImage() { return new Image("img/sort_desc.gif"); } public String getHTML() { return "<img border=\"0\" src=\"img/sort_desc.gif\"/>"; } }; } public AbstractImagePrototype scrollTableFillWidth() { return new AbstractImagePrototype() { public void applyTo(Image image) { image.setUrl("img/fill_width.gif"); } public Image createImage() { return new Image("img/fill_width.gif"); } public String getHTML() { return "<img border=\"0\" src=\"img/fill_width.gif\"/>"; } }; } }; headerTable = new FixedWidthFlexTable(); dataTable = new FixedWidthGrid(); columnSorter = new ExtendedColumnSorter(); table = new ScrollTable(dataTable, headerTable, scrollTableImages); dataTable.setColumnSorter(columnSorter); table.setCellSpacing(0); table.setCellPadding(2); table.setSize("540px", "140px"); ScrollTableHelper.setColumnWidth(table, 0, 60, ScrollTableHelper.FIXED); ScrollTableHelper.setColumnWidth(table, 1, 120, ScrollTableHelper.MEDIUM); ScrollTableHelper.setColumnWidth(table, 2, 120, ScrollTableHelper.MEDIUM, true, false); ScrollTableHelper.setColumnWidth(table, 3, 60, ScrollTableHelper.MEDIUM); ScrollTableHelper.setColumnWidth(table, 4, 90, ScrollTableHelper.FIXED); ScrollTableHelper.setColumnWidth(table, 5, 140, ScrollTableHelper.FIXED); ScrollTableHelper.setColumnWidth(table, 6, 150, ScrollTableHelper.MEDIUM, true, false); table.setColumnSortable(4, false); table.setColumnSortable(5, false); // Level 1 headers headerTable.setHTML(0, 0, Main.i18n("version.name")); headerTable.setHTML(0, 1, Main.i18n("version.created")); headerTable.setHTML(0, 2, Main.i18n("version.author")); headerTable.setHTML(0, 3, Main.i18n("version.size")); headerTable.setHTML(0, 4, "&nbsp;"); headerTable.setWidget(0, 5, purge); headerTable.setHTML(0, 6, Main.i18n("version.comment")); headerTable.getCellFormatter().setHorizontalAlignment(0, 5, HasAlignment.ALIGN_CENTER); headerTable.getCellFormatter().setVerticalAlignment(0, 5, HasAlignment.ALIGN_MIDDLE); // Table data dataTable.setSelectionPolicy(SelectionGrid.SelectionPolicy.ONE_ROW); table.setResizePolicy(ResizePolicy.FILL_WIDTH); table.setScrollPolicy(ScrollPolicy.BOTH); headerTable.addStyleName("okm-DisableSelect"); dataTable.addStyleName("okm-DisableSelect"); initWidget(table); } /** * Language refresh */ public void langRefresh() { headerTable.setHTML(0, 0, Main.i18n("version.name")); headerTable.setHTML(0, 1, Main.i18n("version.created")); headerTable.setHTML(0, 2, Main.i18n("version.author")); headerTable.setHTML(0, 3, Main.i18n("version.size")); headerTable.setHTML(0, 6, Main.i18n("version.comment")); purge.setHTML(Main.i18n("version.purge.document")); // Translate all view buttons if (!buttonView.isEmpty()) { for (Iterator<Button> it = buttonView.iterator(); it.hasNext();) { Button button = it.next(); button.setHTML(Main.i18n("button.view")); } } if (!buttonRestore.isEmpty()) { for (Iterator<Button> it = buttonRestore.iterator(); it.hasNext();) { Button button = it.next(); button.setHTML(Main.i18n("button.restore")); } } } /** * Sets the document * * @param GWTDocument The document */ public void set(GWTDocument doc) { this.doc = doc; } /** * Removes all rows except the first */ public void reset() { // Purge all rows except first while (dataTable.getRowCount() > 0) { dataTable.removeRow(0); } dataTable.resize(0, NUMBER_OF_COLUMNS); versions = new ArrayList<String>(); data = new HashMap<Integer, GWTVersion>(); } /** * Adds a version to the history table * * @param version The Version to add */ public void addRow(GWTVersion version) { final int rows = dataTable.getRowCount(); dataTable.insertRow(rows); dataTable.setHTML(rows, 0, version.getName()); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern")); dataTable.setHTML(rows, 1, dtf.format(version.getCreated())); dataTable.setHTML(rows, 2, version.getUser().getUsername()); dataTable.setHTML(rows, 3, Util.formatSize(version.getSize())); dataTable.setHTML(rows, 6, version.getComment()); versions.add(version.getName()); data.put(rows, version); // Special case when visibleButtons are false, widget are on trash, must // disable all buttons, // but must enable the actual version to view ( on default is not // enabled because is active one ) if (version.isActual() && visibleButtons) { dataTable.selectRow(rows, true); } else { // Only on trash widget it'll occurs if (version.isActual()) { dataTable.selectRow(rows, true); } Button restoreButton = new Button(Main.i18n("button.restore"), new ClickHandler() { @Override public void onClick(ClickEvent event) { List<String> versions = Main.get().mainPanel.desktop.browser.tabMultiple.tabDocument.version.versions; String ver = (String) versions.get(rows); Main.get().confirmPopup.setConfirm(ConfirmPopup.CONFIRM_RESTORE_HISTORY_DOCUMENT); Main.get().confirmPopup.setValue(ver); Main.get().confirmPopup.show(); } }); restoreButton.setVisible(visibleButtons); if ((doc.getPermissions() & GWTPermission.WRITE) == GWTPermission.WRITE && !doc.isCheckedOut() && !doc.isLocked()) { restoreButton.setEnabled(true); } else { restoreButton.setEnabled(false); } dataTable.setWidget(rows, 5, restoreButton); dataTable.getCellFormatter().setHorizontalAlignment(rows, 5, HorizontalPanel.ALIGN_CENTER); buttonRestore.add(restoreButton); restoreButton.setStyleName("okm-YesButton"); } Button viewButton = new Button(Main.i18n("button.view"), new ClickHandler() { @Override public void onClick(ClickEvent event) { List<String> versions = Main.get().mainPanel.desktop.browser.tabMultiple.tabDocument.version.versions; String ver = (String) versions.get(rows); Util.downloadFileByUUID(doc.getUuid(), "ver=" + ver); } }); viewButton.setVisible(Main.get().workspaceUserProperties.getWorkspace().isTabDocumentVersionDownloadVisible()); dataTable.setWidget(rows, 4, viewButton); dataTable.getCellFormatter().setHorizontalAlignment(rows, 4, HorizontalPanel.ALIGN_CENTER); buttonView.add(viewButton); viewButton.setStyleName("okm-ViewButton"); } /** * Refresh the version history */ final AsyncCallback<List<GWTVersion>> callbackGetVersionHistory = new AsyncCallback<List<GWTVersion>>() { public void onSuccess(List<GWTVersion> result) { reset(); // Initializes buttons lists ( to make language translations ) buttonView = new ArrayList<Button>(); buttonRestore = new ArrayList<Button>(); // When there's more than one version document can purge it if (result.size() > 1) { purge.setEnabled(true); } else { purge.setEnabled(false); } for (Iterator<GWTVersion> it = result.iterator(); it.hasNext();) { GWTVersion version = it.next(); addRow(version); } Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetVersionHistory(); } public void onFailure(Throwable caught) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetVersionHistory(); Main.get().showError("GetVersionHistory", caught); } }; /** * Refresh the version history after restoring version */ final AsyncCallback<Object> callbackRestoreVersion = new AsyncCallback<Object>() { public void onSuccess(Object result) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetRestoreVersion(); Main.get().mainPanel.topPanel.toolBar.executeRefresh(); } public void onFailure(Throwable caught) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetRestoreVersion(); Main.get().showError("GetVersionHistory", caught); } }; /** * Refresh the version history after purge version */ final AsyncCallback<Object> callbackPurgeVersionHistory = new AsyncCallback<Object>() { public void onSuccess(Object result) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetPurgeVersionHistory(); Main.get().mainPanel.topPanel.toolBar.executeRefresh(); Main.get().workspaceUserProperties.getUserDocumentsSize(); } public void onFailure(Throwable caught) { Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetPurgeVersionHistory(); Main.get().showError("purgeVersionHistory", caught); } }; /** * Gets the version history on the server */ public void getVersionHistory() { if (doc != null) { Main.get().mainPanel.desktop.browser.tabMultiple.status.setVersionHistory(); documentService.getVersionHistory(doc.getUuid(), callbackGetVersionHistory); } } /** * Revert to a history document */ public void restoreVersion(String versionId) { if (doc != null) { Main.get().mainPanel.desktop.browser.tabMultiple.status.setRestoreVersion(); documentService.restoreVersion(doc.getPath(), versionId, callbackRestoreVersion); } } /** * Purges a version history */ public void purgeVersionHistory() { if (doc != null) { Main.get().mainPanel.desktop.browser.tabMultiple.status.setPurgeVersionHistory(); documentService.purgeVersionHistory(doc.getPath(), callbackPurgeVersionHistory); } } /** * Sets visibility to buttons ( true / false ) * * @param visible The visible value */ public void setVisibleButtons(boolean visible) { visibleButtons = visible; } /** * @return the data table */ public FixedWidthGrid getDataTable() { return dataTable; } /* * (non-Javadoc) * @see * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event * .dom.client.ClickEvent) */ public void onClick(ClickEvent event) { Main.get().confirmPopup.setConfirm(ConfirmPopup.CONFIRM_PURGE_VERSION_HISTORY_DOCUMENT); Main.get().confirmPopup.show(); } /** * fillWidth */ public void fillWidth() { table.fillWidth(); } }
package kg.inai.equeuesystem.entities; import lombok.*; import lombok.experimental.FieldDefaults; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.util.Date; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE) @Table(name = "employee") @Entity public class Employee { @Id @GeneratedValue @Column(name = "employee_id") Long id; @DateTimeFormat(pattern = "dd-MM-yyyy hh:mm") @Column(name = "registration_date", nullable = false) Date registration_date; @Column(name = "name") String name; @Column(name = "surname") String surname; @Column(name = "middle_name") String middle_name; @Column(name = "pin") String pin; @Column(name = "phone_number") String phone_number; @Column(name = "address") String address; @Column(name = "profile_photo") String profile_photo; @Column(name = "description") String description; @Column(name = "isAdmin") Boolean isAdmin; @Column(name = "isLiveQueue") Boolean isLiveQueue; @ManyToOne @JoinColumn(name = "department_id") Department department; @ManyToOne @JoinColumn(name = "category_id") Category category; @ManyToOne @JoinColumn(name = "region_id") Region region; @ManyToOne @JoinColumn(name = "user_id", nullable = false) User user; }
package br.com.univag.logic; import br.com.univag.controller.Logica; import br.com.univag.exception.DaoException; import br.com.univag.service.UsuarioService; import br.com.univag.util.Mensagem; import java.io.IOException; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author CRISTIANO */ public class ListaUsuarioLogic implements Logica { Connection con; Mensagem mensagem = new Mensagem(); UsuarioService service = new UsuarioService(); public ListaUsuarioLogic() { } @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { mensagem.setRequest(request); con = (Connection) request.getAttribute("connection"); service.setCon(con); try { Integer totalPaginas = service.quantidadePaginas(); request.setAttribute("totalPgn", totalPaginas - 1); String valor = request.getParameter("valor"); if (valor != null) { int parametro = Integer.parseInt(valor); request.setAttribute("listUser", service.listUsuario(parametro)); return "privado/listUsuarioView.jsp"; } request.setAttribute("listUser", service.listUsuario(0)); } catch (DaoException ex) { ex.getMessage(); } return "privado/listUsuarioView.jsp"; } }
package schr0.tanpopo.init; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.BlockColored; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.client.renderer.color.IItemColor; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import schr0.tanpopo.Tanpopo; @SideOnly(Side.CLIENT) public class TanpopoBehaviorsColors { public void initClient() { registerBlockArrayColor(TanpopoBlocks.FLUFF_CUSHION); } // TODO /* ======================================== MOD START =====================================*/ private static void registerBlockArrayColor(Block block) { Tanpopo.proxy.getMinecraft().getBlockColors().registerBlockColorHandler(new IBlockColor() { @Override public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { return ((EnumDyeColor) state.getValue(BlockColored.COLOR)).getMapColor().colorValue; } }, block); Tanpopo.proxy.getMinecraft().getItemColors().registerItemColorHandler(new IItemColor() { @Override public int getColorFromItemstack(ItemStack stack, int tintIndex) { return EnumDyeColor.byMetadata(stack.getItemDamage()).getMapColor().colorValue; } }, Item.getItemFromBlock(block)); } }
package br.com.bloder.blorm; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import br.com.bloder.blormlib.Blorm; import br.com.bloder.blormlib.validation.Action; import br.com.bloder.blormlib.validation.Validate; import br.com.bloder.blormlib.validation.Validation; import static br.com.bloder.blormlib.validation.Validations.*; public class MainActivity extends AppCompatActivity { private EditText editTextFilled; private Button submit; private CheckBox checkBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editTextFilled = (EditText) findViewById(R.id.edit_text_filled); submit = (Button) findViewById(R.id.submit); checkBox = (CheckBox) findViewById(R.id.check_box); editTextFilled.setText("Hello"); new Blorm.Builder() .field(editTextFilled).is(filled) .andField(checkBox).is(checked) .onSuccess(new Action() { @Override public void call() { onSuccess(); } }) .onError(new Action() { @Override public void call() { onError(); } }) .submitOn(submit); } private void onSuccess() { editTextFilled.setError(null); checkBox.setError(null); Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show(); } private void onError() { Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show(); } }
package com.tencent.mm.plugin.game.ui; import android.content.Context; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.game.d.dj; import com.tencent.mm.plugin.game.f.e; import com.tencent.mm.plugin.game.f.f; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.pluginsdk.ui.a.b; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.storage.ab; import java.util.LinkedList; import java.util.List; class GameDetailRankLikedUI$a extends BaseAdapter { List<dj> jWl = new LinkedList(); private Context mContext; public GameDetailRankLikedUI$a(Context context) { this.mContext = context; } public final int getCount() { return this.jWl.size(); } private dj qV(int i) { return (dj) this.jWl.get(i); } public final long getItemId(int i) { return (long) i; } public final View getView(int i, View view, ViewGroup viewGroup) { a aVar; if (view == null) { view = LayoutInflater.from(this.mContext).inflate(f.game_detail2_rank_liked_item, viewGroup, false); aVar = new a((byte) 0); aVar.eKk = (ImageView) view.findViewById(e.game_detail_rank_liked_item_avatar); aVar.gwk = (TextView) view.findViewById(e.game_detail_rank_liked_item_name); aVar.jWm = (TextView) view.findViewById(e.game_detail_rank_liked_item_time); view.setTag(aVar); } else { aVar = (a) view.getTag(); } dj qV = qV(i); b.a(aVar.eKk, qV.jTv, 0.5f, false); ab Yg = ((i) g.l(i.class)).FR().Yg(qV.jTv); if (Yg != null) { aVar.gwk.setText(new SpannableString(j.a(this.mContext, Yg.BL(), aVar.gwk.getTextSize()))); } else { aVar.gwk.setText(""); } aVar.jWm.setText(qV.jTw); return view; } }
/* * Copyright (C) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * modified by: David Yonge-Mallo */ package com.example.android.inputmethod.persian; import java.util.ArrayList; import java.util.List; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.inputmethodservice.InputMethodService; import android.inputmethodservice.Keyboard; import android.inputmethodservice.KeyboardView; import android.inputmethodservice.ExtractEditText; import android.preference.PreferenceManager; import android.text.method.MetaKeyKeyListener; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; /** * Example of writing an input method for a soft keyboard. This code is * focused on simplicity over completeness, so it should in no way be considered * to be a complete soft keyboard implementation. Its purpose is to provide * a basic example for how you would get started writing an input method, to * be fleshed out as appropriate. */ public class PersianInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener, OnSharedPreferenceChangeListener { static final boolean DEBUG = false; /** * This boolean indicates the optional example code for performing * processing of hard keys in addition to regular text generation * from on-screen interaction. It would be used for input methods that * perform language translations (such as converting text entered on * a QWERTY keyboard to Chinese), but may not be used for input methods * that are primarily intended to be used for on-screen text entry. */ static final boolean PROCESS_HARD_KEYS = true; private KeyboardView mInputView; private CandidateView mCandidateView; private CompletionInfo[] mCompletions; private StringBuilder mComposing = new StringBuilder(); private boolean mPredictionOn; private boolean mCompletionOn; private int mLastDisplayWidth; private boolean mCapsLock; // private long mLastShiftTime; private long mMetaState; private PersianKeyboard mSymbolsKeyboard; private PersianKeyboard mSymbolsShiftedKeyboard; private PersianKeyboard mStandardKeyboard; private PersianKeyboard mCurKeyboard; private String mWordSeparators; // Preferences settings. private boolean mPrefSelectSuggestion; private boolean mPrefUseReducedKeys; private boolean mPrefPreferFullscreenMode; private boolean mPrefShowRedundantKeyboard; // Persian vocabulary static private PersianWordGuesser mGuesser = null; static private ArrayList<String> mCandidateList = null; static private String mBestGuess = null; /** * Main initialization of the input method component. Be sure to call * to super class. */ @Override public void onCreate() { super.onCreate(); mWordSeparators = getResources().getString(R.string.word_separators); // Initialise the Persian word mGuesser (and restore its state). if( mGuesser == null ) { mGuesser = new PersianWordGuesser(getBaseContext()); } if( mCandidateList == null ) { mCandidateList = new ArrayList<String>(); } // Register the listener for a shared preference change. PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); } /* * Called when service is no longer used and is being removed. */ @Override public void onDestroy() { // Save the selected words, before discarding them. // However, do NOT set mGuesser to null here, as the updateCandidates // is sometimes called after onDestroy. mGuesser.saveState(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); // Release everything. super.onDestroy(); } // Implements the interface for OnSharedPreferenceChangeListener. public void onSharedPreferenceChanged(final SharedPreferences sharedPrefs, final String key) { // If shared preferences have changed, update the values. if (key.equals(Preferences.KEY_SELECT_SUGGESTION_CHECKBOX_PREFERENCE)) { mPrefSelectSuggestion = sharedPrefs.getBoolean(Preferences.KEY_SELECT_SUGGESTION_CHECKBOX_PREFERENCE, true); } else if (key.equals(Preferences.KEY_USE_REDUCED_KEYS_CHECKBOX_PREFERENCE)) { mPrefUseReducedKeys = sharedPrefs.getBoolean(Preferences.KEY_USE_REDUCED_KEYS_CHECKBOX_PREFERENCE, false); configureKeyboards(); } else if (key.equals(Preferences.KEY_PREFER_FULLSCREEN_CHECKBOX_PREFERENCE)) { mPrefPreferFullscreenMode = sharedPrefs.getBoolean(Preferences.KEY_PREFER_FULLSCREEN_CHECKBOX_PREFERENCE, false); } else if (key.equals(Preferences.KEY_SHOW_REDUNDANT_KEYBOARD_CHECKBOX_PREFERENCE)) { mPrefShowRedundantKeyboard = sharedPrefs.getBoolean(Preferences.KEY_SHOW_REDUNDANT_KEYBOARD_CHECKBOX_PREFERENCE, true); } } /* * Configure the keyboard views, depending on the preferences. */ private void configureKeyboards() { if( mPrefUseReducedKeys ) { mStandardKeyboard = new PersianKeyboard(this, R.xml.reduced_keys); } else { mStandardKeyboard = new PersianKeyboard(this, R.xml.standard); } mSymbolsKeyboard = new PersianKeyboard(this, R.xml.symbols); mSymbolsShiftedKeyboard = new PersianKeyboard(this, R.xml.symbols); } /** * This is the point where you can do all of your UI initialization. It * is called after creation and any configuration change. */ @Override public void onInitializeInterface() { // Get the preferences. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Input preferences. mPrefSelectSuggestion = sharedPrefs.getBoolean(Preferences.KEY_SELECT_SUGGESTION_CHECKBOX_PREFERENCE, true); // Display preferences. mPrefUseReducedKeys = sharedPrefs.getBoolean(Preferences.KEY_USE_REDUCED_KEYS_CHECKBOX_PREFERENCE, false); mPrefPreferFullscreenMode = sharedPrefs.getBoolean(Preferences.KEY_PREFER_FULLSCREEN_CHECKBOX_PREFERENCE, false); mPrefShowRedundantKeyboard = sharedPrefs.getBoolean(Preferences.KEY_SHOW_REDUNDANT_KEYBOARD_CHECKBOX_PREFERENCE, true); if (mStandardKeyboard != null) { // Configuration changes can happen after the keyboard gets recreated, // so we need to be able to re-build the keyboards if the available // space has changed. int displayWidth = getMaxWidth(); if (displayWidth == mLastDisplayWidth) return; mLastDisplayWidth = displayWidth; } // Configure the keyboards. configureKeyboards(); } /** * Called by the framework when your view for creating input needs to * be generated. This will be called the first time your input method * is displayed, and every time it needs to be re-created such as due to * a configuration change. */ @Override public View onCreateInputView() { mInputView = (KeyboardView) getLayoutInflater().inflate( R.layout.persian_keyboard, null); mInputView.setOnKeyboardActionListener(this); mInputView.setKeyboard(mStandardKeyboard); return mInputView; } /** * Called by the framework when your view for showing candidates needs to * be generated, like {@link #onCreateInputView}. */ @Override public View onCreateCandidatesView() { mCandidateView = new CandidateView(this); mCandidateView.setService(this); setCandidatesViewShown(true); return mCandidateView; } /** * Called by the framework to create the layout for showing extracted text. */ @Override public View onCreateExtractTextView() { View view = super.onCreateExtractTextView(); ExtractEditText inputExtractEditText = (ExtractEditText)view.findViewById(android.R.id.inputExtractEditText); inputExtractEditText.setGravity(android.view.Gravity.RIGHT); inputExtractEditText.setScrollBarStyle(android.view.View.SCROLLBARS_OUTSIDE_OVERLAY); return view; } /** * This is the main point where we do our initialization of the input method * to begin operating on an application. At this point we have been * bound to the client, and are now receiving all of the detailed information * about the target of our edits. */ @Override public void onStartInput(EditorInfo attribute, boolean restarting) { super.onStartInput(attribute, restarting); // Reset our state. We want to do this even if restarting, because // the underlying state of the text editor could have changed in any way. mComposing.setLength(0); updateCandidates(); if (!restarting) { // Clear shift states. mMetaState = 0; } mPredictionOn = false; mCompletionOn = false; mCompletions = null; // We are now going to initialize our state based on the type of // text being edited. switch (attribute.inputType&EditorInfo.TYPE_MASK_CLASS) { case EditorInfo.TYPE_CLASS_NUMBER: case EditorInfo.TYPE_CLASS_DATETIME: // Numbers and dates default to the symbols keyboard, with // no extra features. mCurKeyboard = mSymbolsKeyboard; break; case EditorInfo.TYPE_CLASS_PHONE: // Phones will also default to the symbols keyboard, though // often you will want to have a dedicated phone keyboard. mCurKeyboard = mSymbolsKeyboard; break; case EditorInfo.TYPE_CLASS_TEXT: // This is general text editing. We will default to the // normal alphabetic keyboard, and assume that we should // be doing predictive text (showing candidates as the // user types). mCurKeyboard = mStandardKeyboard; mPredictionOn = true; // We now look for a few special variations of text that will // modify our behavior. int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD || variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { // Do not display predictions / what the user is typing // when they are entering a password. mPredictionOn = false; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_URI || variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) { // Our predictions are not useful for e-mail addresses // or URIs. mPredictionOn = false; } if ((attribute.inputType&EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { // If this is an auto-complete text view, then our predictions // will not be shown and instead we will allow the editor // to supply their own. We only show the editor's // candidates when in fullscreen mode, otherwise relying // on it displaying its own UI. mPredictionOn = false; mCompletionOn = isFullscreenMode(); } // We also want to look at the current state of the editor // to decide whether our alphabetic keyboard should start out // shifted. updateShiftKeyState(attribute); break; default: // For all unknown input types, default to the alphabetic // keyboard with no special features. mCurKeyboard = mStandardKeyboard; updateShiftKeyState(attribute); } // Update the label on the enter key, depending on what the application // says it will do. mCurKeyboard.setImeOptions(getResources(), attribute.imeOptions); } /** * This is called when the user is done editing a field. We can use * this to reset our state. */ @Override public void onFinishInput() { super.onFinishInput(); // Clear current composing text and candidates. mComposing.setLength(0); updateCandidates(); // We only hide the candidates window when finishing input on // a particular editor, to avoid popping the underlying application // up and down if the user is entering text into the bottom of // its window. setCandidatesViewShown(false); mCurKeyboard = mStandardKeyboard; if (mInputView != null) { mInputView.closing(); } // Save the selected words. mGuesser.saveState(); } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { super.onStartInputView(attribute, restarting); // Apply the selected keyboard to the input view. mInputView.setKeyboard(mCurKeyboard); mInputView.closing(); } /** * Deal with the editor reporting movement of its cursor. */ @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); // If the current selection in the text view changes, we should // clear whatever candidate text we have. if (mComposing.length() > 0 && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) { mComposing.setLength(0); updateCandidates(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); } } } /** * This tells us about completions that the editor has determined based * on the current text in it. We want to use this in fullscreen mode * to show the completions ourself, since the editor can not be seen * in that situation. */ @Override public void onDisplayCompletions(CompletionInfo[] completions) { if (mCompletionOn) { mCompletions = completions; if (completions == null) { setSuggestions(null, false, false); return; } List<String> stringList = new ArrayList<String>(); for (int i=0; i<(completions != null ? completions.length : 0); i++) { CompletionInfo ci = completions[i]; if (ci != null) stringList.add(ci.getText().toString()); } setSuggestions(stringList, true, true); } } /** * This translates incoming hard key events in to edit operations on an * InputConnection. It is only needed when using the * PROCESS_HARD_KEYS option. */ private boolean translateKeyDown(int keyCode, KeyEvent event) { mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState, keyCode, event); int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState)); mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState); InputConnection ic = getCurrentInputConnection(); if (c == 0 || ic == null) { return false; } //boolean dead = false; if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) { //dead = true; c = c & KeyCharacterMap.COMBINING_ACCENT_MASK; } if (mComposing.length() > 0) { char accent = mComposing.charAt(mComposing.length() -1 ); int composed = KeyEvent.getDeadChar(accent, c); if (composed != 0) { c = composed; mComposing.setLength(mComposing.length()-1); } } onKey(c, null); return true; } /** * Use this to monitor key events being delivered to the application. * We get first crack at them, and can either resume them or let them * continue to the app. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: // The InputMethodService already takes care of the back // key for us, to dismiss the input method if it is shown. // However, our keyboard could be showing a pop-up window // that back should dismiss, so we first allow it to do that. if (event.getRepeatCount() == 0 && mInputView != null) { if (mInputView.handleBack()) { return true; } } break; case KeyEvent.KEYCODE_DEL: // Special handling of the delete key: if we currently are // composing text for the user, we want to modify that instead // of let the application to the delete itself. if (mComposing.length() > 0) { onKey(Keyboard.KEYCODE_DELETE, null); return true; } break; /* case KeyEvent.KEYCODE_ENTER: // Let the underlying text editor always handle these. return false; */ default: // For all other keys, if we want to do transformations on // text being entered with a hard keyboard, we need to process // it and do the appropriate action. if (PROCESS_HARD_KEYS) { InputConnection ic = getCurrentInputConnection(); if( ic != null ) { if (!event.isAltPressed() && !event.isSymPressed()) { // Neither Alt nor Sym is pressed (but Shift might be pressed). // The following code is really ugly. It should // probably be changed to use an array or hash table. switch(keyCode) { // Row 1 case KeyEvent.KEYCODE_Q: mComposing.append("\u0636"); break; case KeyEvent.KEYCODE_W: mComposing.append("\u0635"); break; case KeyEvent.KEYCODE_E: mComposing.append("\u062B"); break; case KeyEvent.KEYCODE_R: mComposing.append("\u0642"); break; case KeyEvent.KEYCODE_T: mComposing.append("\u0641"); break; case KeyEvent.KEYCODE_Y: mComposing.append("\u063A"); break; case KeyEvent.KEYCODE_U: mComposing.append("\u0639"); break; case KeyEvent.KEYCODE_I: mComposing.append("\u0647"); break; case KeyEvent.KEYCODE_O: mComposing.append("\u062E"); break; case KeyEvent.KEYCODE_P: mComposing.append("\u062D"); break; // Note that "[" and "]" are treated as Alt-V and Alt-B. // Row 2 case KeyEvent.KEYCODE_A: if( event.isShiftPressed() ) { // If shift is pressed, then it's vav with hamza above. mComposing.append("\u0624"); } else { // Regular shin. mComposing.append("\u0634"); } break; case KeyEvent.KEYCODE_S: if( event.isShiftPressed() ) { // If shift is pressed, then it's yeh with hamza above. mComposing.append("\u0626"); } else { // Regular sin. mComposing.append("\u0633"); } break; case KeyEvent.KEYCODE_D: mComposing.append("\u06CC"); break; case KeyEvent.KEYCODE_F: if( event.isShiftPressed() ) { // If shift is pressed, then it's alef with hamza below. mComposing.append("\u0625"); } else { // Regular beh. mComposing.append("\u0628"); } break; case KeyEvent.KEYCODE_G: if( event.isShiftPressed() ) { // If shift is pressed, then it's alef with hamza above. mComposing.append("\u0623"); } else { // Regular lam. mComposing.append("\u0644"); } break; case KeyEvent.KEYCODE_H: if( event.isShiftPressed() ) { // If shift is pressed, then it's an alef with madda above. mComposing.append("\u0622"); } else { // Regular alef. mComposing.append("\u0627"); } break; case KeyEvent.KEYCODE_J: mComposing.append("\u062A"); break; case KeyEvent.KEYCODE_K: mComposing.append("\u0646"); break; case KeyEvent.KEYCODE_L: mComposing.append("\u0645"); break; // Note that ";" and "'" are treated as Alt-J and Alt-L. case KeyEvent.KEYCODE_Z: mComposing.append("\u0638"); break; case KeyEvent.KEYCODE_X: mComposing.append("\u0637"); break; case KeyEvent.KEYCODE_C: if( event.isShiftPressed() ) { // If shift is pressed, then it's a zheh. mComposing.append("\u0698"); } else { // Regular zeh. mComposing.append("\u0632"); } break; case KeyEvent.KEYCODE_V: mComposing.append("\u0631"); break; case KeyEvent.KEYCODE_B: if( event.isShiftPressed() ) { // If shift is pressed, then it's a zero-width non-joiner. mComposing.append("\u200C"); } else { // The letter zal. mComposing.append("\u0630"); } break; case KeyEvent.KEYCODE_N: mComposing.append("\u062F"); break; case KeyEvent.KEYCODE_M: if( event.isShiftPressed() ) { // If shift is pressed, then it's a hamza. mComposing.append("\u0621"); } else { // The letter peh. mComposing.append("\u067E"); } break; case KeyEvent.KEYCODE_COMMA: if( event.isShiftPressed() ) { // If shift is pressed, then it's a Persian question mark. mComposing.append("\u0621"); } else { // The letter vav. mComposing.append("\u0648"); } break; case KeyEvent.KEYCODE_0: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append(")"); } else { mComposing.append("\u06F0"); } commitTyped(ic); break; case KeyEvent.KEYCODE_1: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("!"); } else { mComposing.append("\u06F1"); } commitTyped(ic); break; case KeyEvent.KEYCODE_2: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\u066C"); } else { mComposing.append("\u06F2"); } commitTyped(ic); break; case KeyEvent.KEYCODE_3: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\u066B"); } else { mComposing.append("\u06F3"); } commitTyped(ic); break; case KeyEvent.KEYCODE_4: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\uFDFC"); } else { mComposing.append("\u06F4"); } commitTyped(ic); break; case KeyEvent.KEYCODE_5: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\u066A"); } else { mComposing.append("\u06F5"); } commitTyped(ic); break; case KeyEvent.KEYCODE_6: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\u00D7"); } else { mComposing.append("\u06F6"); } commitTyped(ic); break; case KeyEvent.KEYCODE_7: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\u060C"); } else { mComposing.append("\u06F7"); } commitTyped(ic); break; case KeyEvent.KEYCODE_8: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("\u002A"); } else { mComposing.append("\u06F8"); } commitTyped(ic); break; case KeyEvent.KEYCODE_9: commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("("); } else { mComposing.append("\u06F9"); } commitTyped(ic); break; case KeyEvent.KEYCODE_PERIOD: // TODO: Find out why this is never reached. commitTyped(ic); if( event.isShiftPressed() ) { mComposing.append("/"); } else { mComposing.append("."); } commitTyped(ic); break; case KeyEvent.KEYCODE_ENTER: commitTyped(ic); // Commit what is currently being typed, but // let the underlying editor handle the Enter key. return false; case KeyEvent.KEYCODE_SPACE: // Handle Space so the insert symbol dialog doesn't show. commitTyped(ic); mComposing.append(" "); commitTyped(ic); break; default: // Let the underlying text editor handle this. return false; } ic.setComposingText(mComposing, 1); updateShiftKeyState(getCurrentInputEditorInfo()); updateCandidates(); return true; } else if (event.isAltPressed() && !event.isShiftPressed() && !event.isSymPressed()) { // The Alt meta key is pressed. switch(keyCode) { case KeyEvent.KEYCODE_V: // Alt-V is "[", which is jim. mComposing.append("\u062C"); break; case KeyEvent.KEYCODE_B: // Alt-B is "]", which is cheh. mComposing.append("\u0686"); break; case KeyEvent.KEYCODE_J: // Alt-J is ";", which is kaf. mComposing.append("\u06A9"); break; case KeyEvent.KEYCODE_L: // Alt-L is "'", which is gaf. mComposing.append("\u06AF"); break; case KeyEvent.KEYCODE_SPACE: // Handle Alt-Space so the insert symbol dialog doesn't show. commitTyped(ic); mComposing.append(" "); commitTyped(ic); break; default: return false; } ic.setComposingText(mComposing, 1); updateShiftKeyState(getCurrentInputEditorInfo()); updateCandidates(); return true; } } // if ( ic != NULL ) if (mPredictionOn && translateKeyDown(keyCode, event)) { return true; } } } return super.onKeyDown(keyCode, event); } /** * Use this to monitor key events being delivered to the application. * We get first crack at them, and can either resume them or let them * continue to the app. */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // If we want to do transformations on text being entered with a hard // keyboard, we need to process the up events to update the meta key // state we are tracking. if (PROCESS_HARD_KEYS) { if (mPredictionOn) { mMetaState = MetaKeyKeyListener.handleKeyUp(mMetaState, keyCode, event); } } return super.onKeyUp(keyCode, event); } /** * Helper function to commit any text being composed in to the editor. */ private void commitTyped(InputConnection inputConnection, boolean isManuallyPicked) { if ( !isManuallyPicked && mPrefSelectSuggestion && (mBestGuess != null) ) { // If the word is manually picked, don't override the user's choice. // Otherwise, if the user has requested to select the suggestion, // replace the typed text with the best guess. mGuesser.selectWord(mBestGuess); mComposing = new StringBuilder(mBestGuess); } if (mComposing.length() > 0) { inputConnection.commitText(mComposing, mComposing.length()); mComposing.setLength(0); updateCandidates(); } } private void commitTyped(InputConnection inputConnection) { commitTyped(inputConnection, false); } /** * Helper to update the shift state of our keyboard based on the initial * editor state. */ private void updateShiftKeyState(EditorInfo attr) { if (attr != null && mInputView != null && mStandardKeyboard == mInputView.getKeyboard()) { int caps = 0; EditorInfo ei = getCurrentInputEditorInfo(); if (ei != null && ei.inputType != EditorInfo.TYPE_NULL) { caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType); } mInputView.setShifted(mCapsLock || caps != 0); } } /** * Helper to determine if a given character code is alphabetic. */ private boolean isAlphabet(int code) { if (Character.isLetter(code)) { return true; } else { return false; } } /** * Helper to send a key down / key up pair to the current editor. */ private void keyDownUp(int keyEventCode) { getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); } /** * Helper to send a character to the editor as raw key events. */ private void sendKey(int keyCode) { switch (keyCode) { case '\n': keyDownUp(KeyEvent.KEYCODE_ENTER); break; default: if (keyCode >= '0' && keyCode <= '9') { keyDownUp(keyCode - '0' + KeyEvent.KEYCODE_0); } else { getCurrentInputConnection().commitText(String.valueOf((char) keyCode), 1); } break; } } // Implementation of KeyboardViewListener public void onKey(int primaryCode, int[] keyCodes) { if (isWordSeparator(primaryCode)) { // Handle separator if (mComposing.length() > 0) { commitTyped(getCurrentInputConnection()); } sendKey(primaryCode); updateShiftKeyState(getCurrentInputEditorInfo()); } else if (primaryCode == Keyboard.KEYCODE_DELETE) { handleBackspace(); } else if (primaryCode == Keyboard.KEYCODE_SHIFT) { handleShift(); } else if (primaryCode == Keyboard.KEYCODE_CANCEL) { handleClose(); return; } else if (primaryCode == PersianKeyboardView.KEYCODE_OPTIONS) { // Show a menu or somethin' } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE && mInputView != null) { Keyboard current = mInputView.getKeyboard(); if (current == mSymbolsKeyboard || current == mSymbolsShiftedKeyboard) { current = mStandardKeyboard; } else { current = mSymbolsKeyboard; } mInputView.setKeyboard(current); if (current == mStandardKeyboard || current == mSymbolsKeyboard) { current.setShifted(false); } } else { handleCharacter(primaryCode, keyCodes); } } public void onText(CharSequence text) { InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); if (mComposing.length() > 0) { commitTyped(ic); } ic.commitText(text, 0); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } /** * Update the list of available candidates from the current composing * text. This will need to be filled in by however you are determining * candidates. */ private void updateCandidates() { mBestGuess = null; if (!mCompletionOn) { if (mComposing.length() > 0) { mCandidateList.clear(); // Add the current composed string to the suggestions, and // determine if it is in the word list. mCandidateList.add(mComposing.toString()); boolean isInWordList = false; // Add other candidates. ArrayList<String> guessList = mGuesser.guess(mComposing.toString()); if( guessList.size() > 0 ) { mBestGuess = guessList.get(0); } for( String persianWord : guessList ) { if( persianWord.equals(mComposing.toString()) ) { isInWordList = true; } else{ mCandidateList.add(persianWord); } } // Send the candidates to CandidateView for display. setSuggestions(mCandidateList, true, isInWordList); } else { // No suggestions. setSuggestions(null, false, false); } } } public void setSuggestions(List<String> suggestions, boolean completions, boolean typedWordValid) { if (suggestions != null && suggestions.size() > 0) { setCandidatesViewShown(true); } else if (isExtractViewShown()) { setCandidatesViewShown(true); } if (mCandidateView != null) { mCandidateView.setSuggestions(suggestions, completions, typedWordValid); } } private void handleBackspace() { final int length = mComposing.length(); if (length > 1) { mComposing.delete(length - 1, length); getCurrentInputConnection().setComposingText(mComposing, 1); updateCandidates(); } else if (length > 0) { mComposing.setLength(0); getCurrentInputConnection().commitText("", 0); updateCandidates(); } else { keyDownUp(KeyEvent.KEYCODE_DEL); } updateShiftKeyState(getCurrentInputEditorInfo()); } private void handleShift() { if (mInputView == null) { return; } Keyboard currentKeyboard = mInputView.getKeyboard(); if (mStandardKeyboard == currentKeyboard) { mStandardKeyboard.setShifted(false); } else if (currentKeyboard == mSymbolsKeyboard) { mSymbolsKeyboard.setShifted(true); mInputView.setKeyboard(mSymbolsShiftedKeyboard); mSymbolsShiftedKeyboard.setShifted(true); } else if (currentKeyboard == mSymbolsShiftedKeyboard) { mSymbolsShiftedKeyboard.setShifted(false); mInputView.setKeyboard(mSymbolsKeyboard); mSymbolsKeyboard.setShifted(false); } } private void handleCharacter(int primaryCode, int[] keyCodes) { if (isInputViewShown()) { if (mInputView.isShifted()) { primaryCode = Character.toUpperCase(primaryCode); } } if (isAlphabet(primaryCode) && mPredictionOn) { mComposing.append((char) primaryCode); getCurrentInputConnection().setComposingText(mComposing, 1); updateShiftKeyState(getCurrentInputEditorInfo()); updateCandidates(); } else { getCurrentInputConnection().commitText( String.valueOf((char) primaryCode), 1); } } private void handleClose() { commitTyped(getCurrentInputConnection()); requestHideSelf(0); mInputView.closing(); } private String getWordSeparators() { return mWordSeparators; } public boolean isWordSeparator(int code) { String separators = getWordSeparators(); return separators.contains(String.valueOf((char)code)); } public void pickDefaultCandidate() { pickSuggestionManually(0); } public void pickSuggestionManually(int index) { if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) { CompletionInfo ci = mCompletions[index]; getCurrentInputConnection().commitCompletion(ci); if (mCandidateView != null) { mCandidateView.clear(); } updateShiftKeyState(getCurrentInputEditorInfo()); } else if (mComposing.length() > 0) { // Increase the rank of the selected word. mGuesser.selectWord(mCandidateList.get(index)); // User has selected one of the suggestions, so commit it. mComposing = new StringBuilder(mCandidateList.get(index) + " "); commitTyped(getCurrentInputConnection(), true); } } public void swipeRight() { if (mCompletionOn) { pickDefaultCandidate(); } } public void swipeLeft() { handleBackspace(); } public void swipeDown() { handleClose(); } public void swipeUp() { } public void onPress(int primaryCode) { } public void onRelease(int primaryCode) { } /* * Always show the on-screen keyboard (unless dismissed), if that is * the user's preference. The on-screen keyboard would then be * displayed even when the hardware keyboard is open. */ @Override public boolean onEvaluateInputViewShown() { // If this value is changed for any reason, remember to call updateInputViewShown(). return mPrefShowRedundantKeyboard || super.onEvaluateInputViewShown(); } /* * Show the keyboard in fullscreen mode, depending on the user's preference. */ @Override public boolean onEvaluateFullscreenMode() { // If this value is changed for any reason, remember to call updateFullscreenMode(). return mPrefPreferFullscreenMode || super.onEvaluateFullscreenMode(); } // User has long-pressed the first word, so add it. public boolean addWordToDictionary(String word) { mGuesser.selectWord(word); return true; } }
package validation; import common.TimeInForce; import crossing.MatchingUtil; import leafNode.OrderEntry; import sbe.msg.NewOrderEncoder; public class ClosingPriceCrossValidator implements SessionValidator { @Override public boolean isMessageValidForSession(OrderEntry orderEntry, int templateId) { //New Orders with GFA, GFX, OPG and ATC are rejected during this session //New Stop or Stop Limit order not allowed if(templateId == NewOrderEncoder.TEMPLATE_ID){ if(orderEntry.getTimeInForce() == TimeInForce.GFA.getValue() || orderEntry.getTimeInForce() == TimeInForce.GFX.getValue() || orderEntry.getTimeInForce() == TimeInForce.OPG.getValue() || orderEntry.getTimeInForce() == TimeInForce.ATC.getValue() || orderEntry.getTimeInForce() == TimeInForce.OPG.getValue()) { return false; } if(MatchingUtil.isParkedOrder(orderEntry)){ return false; } } return true; } }
package com.chanpyaeaung.moviez.api; import io.reactivex.Observable; import com.chanpyaeaung.moviez.BuildConfig; import com.chanpyaeaung.moviez.model.detail.MovieDetail; import com.chanpyaeaung.moviez.model.movie.Result; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import static com.chanpyaeaung.moviez.api.Api.DISCOVER_MOVIE; import static com.chanpyaeaung.moviez.api.Api.MOVIE; import static com.chanpyaeaung.moviez.helpers.Keys.API_KEY; import static com.chanpyaeaung.moviez.helpers.Keys.PRIMARY_RELEASE_DATE_LTE; import static com.chanpyaeaung.moviez.helpers.Keys.SORT_BY; import static com.chanpyaeaung.moviez.helpers.Keys.PAGE; import static com.chanpyaeaung.moviez.helpers.Keys.LANGUAGE; /** * Created by Chan Pyae Aung on 5/3/17. */ public interface MovieService { @GET(DISCOVER_MOVIE + "?" + API_KEY + "=" + BuildConfig.KEY) Observable<Result> getMovies(@Query(PAGE) int page); @GET(DISCOVER_MOVIE + "?" + API_KEY + "=" + BuildConfig.KEY) Observable<Result> getMoviesWithPrimaryReleaseDate(@Query(PRIMARY_RELEASE_DATE_LTE) String primaryDate, @Query(SORT_BY) String sortBy, @Query(PAGE) int page); @GET(DISCOVER_MOVIE + "?" + API_KEY + "=" + BuildConfig.KEY) Observable<Result> getMoviesBySort(@Query(SORT_BY) String sortBy, @Query(PAGE) int page); @GET(MOVIE + "/{id}" + "?" + API_KEY + "=" + BuildConfig.KEY) Observable<MovieDetail> getMovieDetail(@Path("id") int id, @Query(LANGUAGE) String language); }
package problem_solve.bfs.baekjoon; import java.util.Scanner; public class BaekJoon5014 { // 코딩 교육 스타트업 면접에 간 건물에 특정 층으로 가기 위한 로직 private static int highest; private static int start; private static int target; private static int up; private static int down; public static void main(String[] args){ Scanner scan = new Scanner(System.in); highest = scan.nextInt(); start = scan.nextInt(); target = scan.nextInt(); up = scan.nextInt(); down = scan.nextInt(); int answer = 0; int diff = target - start; if(diff == 0){ System.out.println(0); } else { if(diff > 0){ if(up == 0) { System.out.println("use the stairs"); } else { while(answer * up < diff){ answer++; } if(answer * up == diff){ System.out.println(answer); } else { int go_down = 0; while(answer * up - diff > go_down * down && down != 0){ go_down++; } if(go_down * down == answer * up - diff){ System.out.println(answer + go_down); } else { System.out.println("use the stairs"); } } } } else { int abs_diff = Math.abs(diff); if(down == 0) { System.out.println("use the stairs"); } else { while(abs_diff > answer * down){ answer++; } if(abs_diff == answer * down){ System.out.println(answer); } else { int go_up = 0; while(answer * down - abs_diff > up * go_up && up != 0){ go_up++; } if(answer * down - abs_diff == up * go_up){ System.out.println(answer + go_up); } else { System.out.println("use the stairs"); } } } } } } }
package cn.itcast.demo04; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class dayDemo_1 { public static void main(String[] args) throws Exception{ function(); } public static void function() throws Exception { Date today = new Date(); long todayTime = today.getTime(); System.out.println(todayTime); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date furture = sdf.parse("2018-08-30"); long furtureTime = furture.getTime(); System.out.println(furtureTime); long time = furtureTime-todayTime; System.out.println(time); System.out.println(time/(24*60*60*1000)); } }
package com.tencent.mm.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.platformtools.ai; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.bj; import com.tencent.mm.sdk.platformtools.x; class HomeUI$25 implements OnClickListener { final /* synthetic */ HomeUI tjS; HomeUI$25(HomeUI homeUI) { this.tjS = homeUI; } public final void onClick(View view) { h.mEJ.k(10919, "0"); HomeUI.f(this.tjS); if (HomeUI.tjy.booleanValue()) { HomeUI.a(this.tjS, Boolean.valueOf(true), Boolean.valueOf(true)); } if (HomeUI.tjz.booleanValue()) { HomeUI.a(this.tjS, Boolean.valueOf(true), Boolean.valueOf(false)); } if (!bj.chn()) { long VF = ai.VF(); if (VF - HomeUI.g(this.tjS) > 10000) { HomeUI.a(this.tjS, VF); HomeUI.h(this.tjS); return; } HomeUI.i(this.tjS); if (HomeUI.j(this.tjS) >= 5) { x.w("MicroMsg.LauncherUI.HomeUI", "Switch to MonkeyEnv now."); bj.lj(true); } } } }
// Copyright (c) 2013-2015 MediaMiser Ltd. All rights reserved. package com.mediamiser.test; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Allows setting/getting private and/or static and/or final variables and * invoking protected/private methods for mock injection and other testing * purposes. * * <br> * <br> * 100% code coverage can be difficult to reach, but with this class a variety * of parts of software can be manipulated to invoke difficult-to-reach code * paths. These code paths can be triggered by temporarily manipulating the * values of constants, injecting a mocked object (using a library like <a * href="https://code.google.com/p/mockito/">Mockito</a>) with custom behaviour, * and/or putting an object into a specific state by manipulating its fields or * invoking its protected/private functions. * * <br> * <br> * <b><i>This class cannot set constants that are primitives.</i></b> If you * need to set a primitive, replace said primitive with its object equivalent in * the class you are modifying, e.g., int to Integer, as a workaround. For more * details, see this <a * href="http://stackoverflow.com/q/14102000/2134">stackoverflow discussion</a>. * * @author Chris Fournier {@literal <chris.fournier@mediamiser.com>} * @author Simon Baribeau {@literal <simon.baribeau@mediamiser.com>} */ public class Manipulator { /** * Get the value of an instance's field. The field may belong to a parent class. * * @param instance * Instance to observe. * @param fieldName * Name of the field to observe (case-sensitive). * @return Value of the named field in the instance observed. * @throws Exception * If the field could not be accessed. */ public static Object get(final Object instance, final String fieldName) throws Exception { final List<Field> fields = getAllFields(new ArrayList<Field>(), instance.getClass()); for (Field field : fields) { if (field.getName().equals(fieldName)) { field.setAccessible(true); return field.get(instance); } } throw new NoSuchFieldException(fieldName); } /** * Set the value of an instance's field. The field may belong to a parent class. * * @param instance * Instance to manipulate. * @param fieldName * Name of the field (case-sensitive). * @param newValue * Value to store in the field. * @return Previous value of the named field in the instance manipulated. * @throws Exception * If the could not be manipulated. */ public static Object set(final Object instance, final String fieldName, final Object newValue) throws Exception { final List<Field> fields = getAllFields(new ArrayList<Field>(), instance.getClass()); for (Field field : fields) { if (field.getName().equals(fieldName)) { return set(instance, field, newValue); } } throw new NoSuchFieldException(fieldName); } /** * Get the value of a class' static field. The field may belong to a parent class. * * @param klass * Class to observe. * @param fieldName * Name of the static field (case-sensitive). * @return Value of the named static field. * @throws Exception * If the field could not be accessed. */ public static Object get(final Class<?> klass, final String fieldName) throws Exception { final List<Field> fields = getAllFields(new ArrayList<Field>(), klass); for (Field field : fields) { if (field.getName().equals(fieldName)) { field.setAccessible(true); return field.get(null); } } throw new NoSuchFieldException(fieldName); } /** * Set the value of an class' static field. The field may belong to a parent class. * * @param klass * Class to manipulate. * @param fieldName * Name of the field to manipulate (case-sensitive). * @param newValue * Value to store in the field. * @return Previous value of the field. * @throws Exception * If the field could not be manipulated. */ public static Object set(final Class<?> klass, final String fieldName, final Object newValue) throws Exception { final List<Field> fields = getAllFields(new ArrayList<Field>(), klass); for (Field field : fields) { if (field.getName().equals(fieldName)) { return set(null, field, newValue); } } throw new NoSuchFieldException(fieldName); } /** * Invoke a private/protected method of an instance. The method may belong to a parent class. * * @param instance * Instance containing the method. * @param methodName * Name of the method (case-sensitive). * @param args * Function arguments. * @return Return value of the method. * @throws Exception * If a method could not be executed. */ public static Object invokeMethod( final Object instance, final String methodName, final Object[] args) throws Exception { return invokeMethod(instance.getClass(), instance, methodName, args); } /** * Invoke a private/protected static method of a class. The method may belong to a parent class. * * @param klass * Class containing the function. * @param methodName * Name of the function (case-sensitive). * @param args * Function arguments. * @return Return value of the function. * @throws Exception * If a function could not be executed. */ public static Object invokeMethod( final Class<?> klass, final String methodName, final Object[] args) throws Exception { return invokeMethod(klass, null, methodName, args); } private static Object set(final Object instance, final Field field, final Object newValue) throws Exception { // Modify field field.setAccessible(true); final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); // Set final Object previousValue = field.get(instance); field.set(instance, newValue); return previousValue; } private static Object invokeMethod( final Class<?> klass, final Object instance, final String methodName, final Object[] args) throws Exception { final List<Method> methods = getAllMethods(new ArrayList<Method>(), klass); for (Method method : methods) { if (method.getName().equals(methodName)) { method.setAccessible(true); return method.invoke(instance, args); } } throw new NoSuchMethodException(methodName); } /** * Get all the fields of a class and its ancestors * * @param fields * List to contain the fields * @param klass * Type of the class * @return List of fields */ protected static List<Field> getAllFields(List<Field> fields, Class<?> klass) { fields.addAll(Arrays.asList(klass.getDeclaredFields())); if (klass.getSuperclass() != null) { fields = getAllFields(fields, klass.getSuperclass()); } return fields; } /** * Get all the methods of a class and its ancestors * * @param fields * List to contain the methods * @param klass * Type of the class * @return List of methods */ protected static List<Method> getAllMethods(List<Method> fields, Class<?> klass) { fields.addAll(Arrays.asList(klass.getDeclaredMethods())); if (klass.getSuperclass() != null) { fields = getAllMethods(fields, klass.getSuperclass()); } return fields; } }
package com.murkino.domain.cat.state; public final class GraduatedState extends State { @Override public String name() { return "graduated"; } }
/** * 矩阵顺时针,从外向内输出 */ public class PrintMatrix { public int[] spiralOrder(int[][] matrix) { if(matrix.length==0) return new int[0]; int b = matrix.length-1; //下边界 int r = matrix[0].length-1; //右边界 int l = 0; //左边界 int t = 0; //上边界 int[] res = new int[(b+1)*(r+1)]; int x = 0; while(true){ for(int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right. if(++t > b) break; for(int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom. if(l > --r) break; for(int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left. if(t > --b) break; for(int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top. if(++l > r) break; } return res; } public static void main(String[] args){ int[][] m = new int[][]{{1,2,3},{4,5,6},{7,8,9}}; PrintMatrix a = new PrintMatrix(); int[] res = a.spiralOrder(m); for(int k:res) System.out.println(k); } }
package collegematch; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class MessageBoard { private ArrayList<Message> messages; //used txt file instead of csv file in order to handle commas in text private String filePath = "./src/collegematch/messageBoard.txt"; public MessageBoard() { try { this.messages = this.readMessages(); } catch (FileNotFoundException e) { e.printStackTrace(); } } //read in messages from messageBoard.txt public ArrayList<Message> readMessages() throws FileNotFoundException { ArrayList<Message> allMessages = new ArrayList<Message>(); Scanner keyboardIn = new Scanner(new File(filePath)); keyboardIn.useDelimiter("/n"); while (keyboardIn.hasNextLine()) { String[] messageDataInArray = keyboardIn.nextLine().split("\t"); String messageName = messageDataInArray[0]; String messageDescription = messageDataInArray[1]; Message message = new Message(messageName,messageDescription); allMessages.add(message); } keyboardIn.close(); return allMessages; } public void displayMessageBoard() { System.out.println(""); System.out.println("********************* Messages *********************"); for (Message message : messages) { message.displayMessage(); } System.out.println("********************* Messages *********************"); System.out.println(""); } //adds to the messages array list public void addToMessageBoard(Message message) throws IOException { messages.add(message); FileWriter writer = new FileWriter(filePath, true); writer.append("\n"); writer.append(message.getMessageTitle()); writer.append("\t"); writer.append(message.getMessageDescription()); writer.close(); } public int getMessageBoardSize() { return messages.size(); } }
package ArrayQueue; public class arrayQueue { private int maxSize; private int front; private int rear; private int[] arr; public arrayQueue() { super(); } public arrayQueue(int arrMaxSize) { maxSize=arrMaxSize; arr=new int [maxSize]; front=-1; rear=-1; } //判断队列是否满 public boolean isFull() { return rear==maxSize-1; } //判断队列是否为空 public boolean isEmpty() { return rear==front; } //往队列添加元素 public void add(int e) { if(isFull()) { System.out.println("队列已满"); return; } arr[++rear]=e; } //获取队列数据 public int getQueue(){ if(isEmpty()) { throw new RuntimeException("队列为空,不能取"); } return arr[++front]; } //显示当前队列数据 public void showQueue() { if(isEmpty()) { System.out.println("队列为空,无法显示"); } for(int i=0;i<arr.length;i++) { System.out.print(" "+arr[i]); } System.out.println(); } //显示队列头数据 public void peek() { if(isEmpty()) { throw new RuntimeException("队列为空,无法显示"); } System.out.println(arr[front+1]); } }
package muleproject; public class HelloServiceImpl implements HelloService{ @Override public String hiService(String name) { return "Hello "+ name + " welcom to Web Services"; } }
package de.paluno.ledboard.tetris.objects; public interface Updateable { void update(); }
package com.steatoda.commons.fields.service.async.crud; import java.util.List; import java.util.Set; import com.steatoda.commons.fields.FieldEnum; import com.steatoda.commons.fields.FieldGraph; import com.steatoda.commons.fields.HasEntityFields; import com.steatoda.commons.fields.service.async.FieldsRequest; import com.steatoda.commons.fields.service.async.FieldsServiceHandler; /** * <p>'Collection' part of 'Collection/Instance' CRUD async interface.</p> * * @see InstanceCRUDFieldsAsyncService * @see CRUDFieldsAsyncService */ public interface CollectionCRUDFieldsAsyncService<I, C extends HasEntityFields<I, C, F>, F extends Enum<F> & FieldEnum, S> extends CRUDFieldsAsyncService<I, C, F, S> { @Override default FieldsRequest get(I id, FieldGraph<F> graph, FieldsServiceHandler<C> handler) { return instance(id).get(graph, handler); } FieldsRequest create(C entity, FieldGraph<F> graph, FieldsServiceHandler<C> handler); /** * Updates all modifiable fields in {@code entity} and pulls {@code graph} into it when done. * * @param entity entity to update and pull changes to * @param graph graph to pull into {@code entity} after modification */ default FieldsRequest modify(C entity, FieldGraph<F> graph, FieldsServiceHandler<C> handler) { return modify(entity, entity.cloneAll(), graph, handler); // NOTE: full clone is required (not cloneFlat or anything like that), because created patch may contain subentities that have to be stored, too } /** * <p>Updates fields in {@code entity} specified by {@code fields} and pulls {@code graph} when done.</p> * * <p>E.g. to update only field {@code bar} in entity {@code foo}, write something like:</p> * * <pre> * modify(foo, EnumSet.of(Foo.Field.bar), ...) * </pre> * * @param entity entity to update and pull changes to * @param fields fields from entity to update (only modifiable fields will be updated) * @param graph graph to pull into {@code entity} after modification */ default FieldsRequest modify(C entity, Set<F> fields, FieldGraph<F> graph, FieldsServiceHandler<C> handler) { C patch = entity.ref(); patch.pull(entity, fields); return modify(entity, patch, graph, handler); } /** * <p>Updates fields in {@code entity} specified by {@code patch} and pulls {@code graph} when done.</p> * * <p>E.g. to update only field {@code bar} in entity {@code foo}, write something like:</p> * * <pre> * modify(foo, foo.clone(FieldGraph.of(Foo.Field.bar)), ...) * </pre> * * @param entity entity to update and pull changes to * @param patch patch containing fields to update (only modifiable fields will be updated) * @param graph graph to pull into {@code entity} after modification */ default FieldsRequest modify(C entity, C patch, FieldGraph<F> graph, FieldsServiceHandler<C> handler) { return instance(entity).modify(patch, graph, handler); } @Override default FieldsRequest delete(C entity, FieldsServiceHandler<Void> handler) { return instance(entity).delete(handler); } FieldsRequest getAllFieldValues(S selector, Set<F> fields, FieldsServiceHandler<List<C>> handler); FieldsRequest count(S selector, FieldsServiceHandler<Integer> handler); FieldsRequest list(S selector, FieldGraph<F> graph, FieldsServiceHandler<List<C>> handler); InstanceCRUDFieldsAsyncService<I, C, F> instance(I id); default InstanceCRUDFieldsAsyncService<I, C, F> instance(C entity) { return instance(entity.getId()); } }
package fel_3; public class DateUtil { public static boolean leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return true; } return false; } public static boolean isValidDate(int year, int month, int day) { if (year <= 0) { return false; } if (month <= 0 || month > 12) { return false; } if (day < 1) { return false; } //February if (month == 2) { if (day > 29) { return false; } if (day == 29) { return leapYear(year); } return true; } int[] longMonths = {1, 3, 5, 7, 8, 10, 12}; for (int tempMonth : longMonths) { if (month == tempMonth) { if (day > 31) { return false; } return true; } } if (day > 30) { return false; } return true; } }
package wmsClient.layerList; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import wmsClient.layerTree.*; /** * Dies ist eine Klasse zur Reprsentation von der Layerliste */ public class LayerList extends JPanel implements ActionListener, LayerSelectionListener { private LayerListModel listModel; protected JList theList; protected JButton upButton = new JButton("Up"); protected JButton downButton = new JButton("Down"); protected JButton removeButton = new JButton("Delete"); protected JButton clearButton = new JButton("Clear"); public LayerList( ) { super(); listModel = new LayerListModel(); theList = new JList( (ListModel)listModel ); upButton.addActionListener( this ); downButton.addActionListener( this ); removeButton.addActionListener( this ); clearButton.addActionListener( this ); makeLayout(); } public ListModel getListModel() { return listModel; } /** * Hinzufgen eines Layers in die Liste * Implementiert fr LayerSelectionListener */ public void layerSelected( LayerInformation layerInfo ) { if ( ! listModel.contains( layerInfo ) ) listModel.add( 0, layerInfo ); listModel.fireListDataListenerContentsChanged(); } /** * Gibt eine Enumeration aller in der Liste befindlicher 'LayerInformation Objekte' zurck */ public Enumeration getLayers() { return listModel.elements(); } // Minimal bounds. // public float[] getLayerBounds() { float b[] = { -Float.MAX_VALUE,-Float.MAX_VALUE,Float.MAX_VALUE,Float.MAX_VALUE }; return getLayerBounds(b); } public float[] getLayerBounds(float x1, float y1, float x2, float y2) { float b[] = {x1,y2,x2,y2}; return getLayerBounds(b); } // Defer to funky interal presentation. // public float[] getLayerBounds(float b[]) { Enumeration x = getLayers(); if (b[0] > b[2]) { float f = b[0]; b[0]=b[2]; b[2]=f; } if (b[1] > b[3]) { float f = b[1]; b[1]=b[3]; b[3]=f; } while( x.hasMoreElements() ) { LayerInformation current = (LayerInformation)x.nextElement(); float[] latLin = current.getLatLonBoundingBox(); if ( latLin[0] > b[0]) b[0] = latLin[0]; // x1 if ( latLin[1] > b[1]) b[1] = latLin[1]; // y1 if ( latLin[2] < b[2]) b[2] = latLin[2]; // x2 if ( latLin[3] < b[3]) b[3] = latLin[3]; // y2 } return b; } protected void makeLayout() { setLayout( new BorderLayout() ); //JPanel buttons = new JPanel( new GridLayout(1,3) ) ; Box buttons = Box.createHorizontalBox(); buttons.add( upButton ); buttons.add( downButton ); buttons.add( removeButton ); buttons.add( clearButton ); //add( new Label("Layer Auswahl"), BorderLayout.NORTH ); add( new JScrollPane( theList ), BorderLayout.CENTER ); JPanel buttonFrame = new JPanel( new BorderLayout() ); buttonFrame.add( buttons, BorderLayout.NORTH ); buttonFrame.add( Box.createVerticalGlue(), BorderLayout.CENTER ); add( buttonFrame, BorderLayout.SOUTH ); } public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj == clearButton) { listModel.clear( ); listModel.fireListDataListenerContentsChanged(); return; } int index = theList.getSelectedIndex(); if ( index < 0 || index > listModel.size() ) return; if (obj == upButton) { if ( index < 1 ) return; Object oldPrev = listModel.remove( index-1 ); listModel.add( index, oldPrev ); theList.setSelectedIndex( index-1 ); } else if (obj == downButton) { if ( ! (index < listModel.size()-1) ) return; Object curr = listModel.remove( index ); listModel.add( index+1, curr ); theList.setSelectedIndex( index+1 ); } else if (obj == removeButton) { Object[] entries = theList.getSelectedValues(); for ( int i=0; i<entries.length; i++) listModel.remove( entries[i] ); theList.setSelectedIndex( index-1 ); if ( theList.getSelectedIndex() < 0 ) theList.setSelectedIndex( listModel.size()-1 ); } listModel.fireListDataListenerContentsChanged(); } }
package com.airplanesoft.dms.ui; import com.airplanesoft.dms.ui.view.AboutView; import com.airplanesoft.dms.ui.view.ContactsView; import com.airplanesoft.dms.ui.view.UsersView; import com.vaadin.navigator.View; import com.vaadin.server.Page; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.server.VaadinRequest; import com.vaadin.annotations.Theme; import com.vaadin.spring.navigator.SpringNavigator; import com.vaadin.ui.*; import com.vaadin.ui.themes.ValoTheme; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashMap; import java.util.Map; import java.util.Optional; @Theme("valo") @SpringUI(path = "") public class AdminUI extends UI { private static Notification notification; private Map<Class<? extends View>, MenuBar.MenuItem> viewByRootItem = new HashMap<>(); private final SpringNavigator springNavigator; private final Log logger = LogFactory.getLog(getClass()); @Autowired public AdminUI(SpringNavigator springNavigator) { this.springNavigator = springNavigator; } @Override protected void init(VaadinRequest request) { logger.info("Init AdminUI."); if (notification != null) { notification.show(Page.getCurrent()); notification = null; } final VerticalLayout root = new VerticalLayout(); root.setSizeFull(); root.setMargin(true); root.setSpacing(true); setContent(root); final CssLayout navigationBar = new CssLayout(); navigationBar.addStyleName(ValoTheme.MENUBAR_SMALL); MenuBar menuBar = getMenuBar(); menuBar.addStyleName(ValoTheme.MENUBAR_BORDERLESS); Label logo = new Label("DCS"); logo.setStyleName(ValoTheme.LABEL_H1); HorizontalLayout header = new HorizontalLayout(); header.setWidth("100%"); header.addComponents(logo, menuBar); header.setComponentAlignment(logo, Alignment.MIDDLE_CENTER); header.setComponentAlignment(menuBar, Alignment.MIDDLE_CENTER); header.setExpandRatio(logo, 1); header.setExpandRatio(menuBar, 11); CssLayout main = new CssLayout(); main.setSizeFull(); root.addComponent(header); root.addComponent(main); root.setExpandRatio(header, 0.1f); root.setExpandRatio(main, 0.9f); springNavigator.init(this, main); springNavigator.addView("", UsersView.class); } private MenuBar getMenuBar() { MenuBar menuBar = new MenuBar(); menuBar.setWidth("100%"); MenuBar.MenuItem users = menuBar.addItem("Users", (MenuBar.Command) event -> AdminUI.this.getUI().getNavigator().navigateTo(UsersView.VIEW_NAME)); MenuBar.MenuItem about = menuBar.addItem("About", (MenuBar.Command) event -> AdminUI.this.getUI().getNavigator().navigateTo(AboutView.VIEW_NAME)); MenuBar.MenuItem contacts = menuBar.addItem("Contacts", (MenuBar.Command) event -> AdminUI.this.getUI().getNavigator().navigateTo(ContactsView.VIEW_NAME)); viewByRootItem.put(UsersView.class, users); viewByRootItem.put(AboutView.class, about); viewByRootItem.put(ContactsView.class, contacts); return menuBar; } public void putMenuState(View oldView, View newView) { Optional.ofNullable(oldView) .map(View::getClass) .map(viewByRootItem::get) .ifPresent(menuItem -> menuItem.setStyleName(null)); Optional.ofNullable(newView) .map(View::getClass) .map(viewByRootItem::get) .ifPresent(menuItem -> menuItem.setStyleName("highlight")); } }
package com.example.healthmanage.ui.activity.academicJournals.ui; import androidx.lifecycle.MutableLiveData; import com.example.healthmanage.base.BaseApplication; import com.example.healthmanage.base.BaseViewModel; import com.example.healthmanage.bean.UsersInterface; import com.example.healthmanage.bean.UsersRemoteSource; import com.example.healthmanage.data.network.exception.ExceptionHandle; import com.example.healthmanage.ui.activity.academicJournals.bean.AddPeriodicalBean; import com.example.healthmanage.ui.activity.academicJournals.bean.EditPeriodicalBean; import com.example.healthmanage.ui.activity.academicJournals.response.AddOrEditSucceedResponse; import com.example.healthmanage.ui.activity.academicJournals.response.PeriodicalInfoResponse; import com.example.healthmanage.ui.activity.academicJournals.response.PeriodicalListResponse; import com.example.healthmanage.ui.activity.qualification.response.UploadResponse; import java.io.File; import java.util.List; public class AcademicJournalsViewModel extends BaseViewModel { private UsersRemoteSource usersRemoteSource; //投稿期刊 public MutableLiveData<String> periodical = new MutableLiveData<>(); //个人简介 public MutableLiveData<String> personalInfo = new MutableLiveData<>(); //标题 public MutableLiveData<String> journalsTitle = new MutableLiveData<>(); //投稿栏目 public MutableLiveData<String> contributionColumn = new MutableLiveData<>(); public MutableLiveData<String> picUrl = new MutableLiveData<>(); public MutableLiveData<List<PeriodicalListResponse.DataBean>> periodicalLiveData = new MutableLiveData<>(); public MutableLiveData<Boolean> isAddSucceed = new MutableLiveData<>(); public MutableLiveData<Boolean> isAddDraftSucceed = new MutableLiveData<>(); public MutableLiveData<Boolean> isEditSucceed = new MutableLiveData<>(); public MutableLiveData<Boolean> isEditDraftSucceed = new MutableLiveData<>(); public MutableLiveData<PeriodicalInfoResponse.DataBean> infoLiveData = new MutableLiveData<>(); public AcademicJournalsViewModel() { usersRemoteSource = new UsersRemoteSource(); } public void getPicUrl(File file){ usersRemoteSource.getUploadIdCard(file, new UsersInterface.UpLoadIdCardCallback() { @Override public void sendSucceed(UploadResponse uploadResponse) { if (uploadResponse.getData()!=null){ picUrl.postValue(uploadResponse.getData()); }else { picUrl.postValue(null); } } @Override public void sendFailed(String msg) { } @Override public void error(ExceptionHandle.ResponseException e) { } }); } public void getPeriodicalList(int status){ usersRemoteSource.getPeriodicalList(BaseApplication.getToken(), status, new UsersInterface.GetPeriodicalListCallback() { @Override public void getSucceed(PeriodicalListResponse periodicalListResponse) { if (periodicalListResponse.getData()!=null && periodicalListResponse.getData().size()>0){ periodicalLiveData.setValue(periodicalListResponse.getData()); }else { periodicalLiveData.setValue(null); } } @Override public void getFailed(String msg) { periodicalLiveData.setValue(null); getUiChangeEvent().getToastTxt().setValue(msg); } @Override public void error(ExceptionHandle.ResponseException e) { periodicalLiveData.setValue(null); } }); } public void addDraftPeriodical(AddPeriodicalBean addPeriodicalBean){ usersRemoteSource.addPeriodical(addPeriodicalBean, new UsersInterface.AddPeriodicalCallback() { @Override public void addSucceed(AddOrEditSucceedResponse addOrEditSucceedResponse) { isAddDraftSucceed.setValue(true); } @Override public void addFailed(String msg) { getUiChangeEvent().getToastTxt().setValue(msg); isAddDraftSucceed.setValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { isAddDraftSucceed.setValue(false); } }); } public void addPeriodical(AddPeriodicalBean addPeriodicalBean){ usersRemoteSource.addPeriodical(addPeriodicalBean, new UsersInterface.AddPeriodicalCallback() { @Override public void addSucceed(AddOrEditSucceedResponse addOrEditSucceedResponse) { isAddSucceed.setValue(true); } @Override public void addFailed(String msg) { getUiChangeEvent().getToastTxt().setValue(msg); isAddSucceed.setValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { isAddSucceed.setValue(false); } }); } public void editPeriodical(EditPeriodicalBean editPeriodicalBean){ usersRemoteSource.editPeriodical(editPeriodicalBean, new UsersInterface.EditPeriodicalCallback() { @Override public void editSucceed(AddOrEditSucceedResponse addOrEditSucceedResponse) { isEditSucceed.setValue(true); } @Override public void editFailed(String msg) { getUiChangeEvent().getToastTxt().setValue(msg); isEditSucceed.setValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { isEditSucceed.setValue(false); } }); } public void editDraftPeriodical(EditPeriodicalBean editPeriodicalBean){ usersRemoteSource.editPeriodical(editPeriodicalBean, new UsersInterface.EditPeriodicalCallback() { @Override public void editSucceed(AddOrEditSucceedResponse addOrEditSucceedResponse) { isEditDraftSucceed.setValue(true); } @Override public void editFailed(String msg) { getUiChangeEvent().getToastTxt().setValue(msg); isEditDraftSucceed.setValue(false); } @Override public void error(ExceptionHandle.ResponseException e) { isEditDraftSucceed.setValue(false); } }); } public void getPeriodical(int id){ usersRemoteSource.getPeriodical(BaseApplication.getToken(), id, new UsersInterface.GetPeriodicalCallback() { @Override public void getSucceed(PeriodicalInfoResponse periodicalInfoResponse) { if (periodicalInfoResponse.getData()!=null){ infoLiveData.setValue(periodicalInfoResponse.getData()); }else { infoLiveData.setValue(null); } } @Override public void getFailed(String msg) { getUiChangeEvent().getToastTxt().setValue(msg); infoLiveData.setValue(null); } @Override public void error(ExceptionHandle.ResponseException e) { infoLiveData.setValue(null); } }); } }
package com.example.bookmanager_ph06542.adapter; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.bookmanager_ph06542.ListNguoiDungActivity; import com.example.bookmanager_ph06542.R; import com.example.bookmanager_ph06542.dao.SachDAO; import com.example.bookmanager_ph06542.model.Sach; import java.util.List; public class SachAdapter extends BaseAdapter implements Filterable { private EditText masach, tenSach, soLuong, giaBia, spinnerMaTheLoai; private Button btnAdd, btnList; private SachDAO sachDAO; List<Sach> listSach; List<Sach> listSort; Activity context; private LayoutInflater inflater; public SachAdapter(Activity context, List<Sach> listSach) { super(); this.listSach = listSach; this.listSort = listSach; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.context = context; sachDAO = new SachDAO(context); } @Override public int getCount() { return listSach.size(); } @Override public Object getItem(int position) { return listSach.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final Sach sach = listSach.get(position); ViewHolder holder; if (convertView == null) { holder = new SachAdapter.ViewHolder(); convertView = inflater.inflate(R.layout.item_sach, parent, false); holder.maSach = convertView.findViewById(R.id.tv_masachh); holder.tenSach = convertView.findViewById(R.id.tv_tensach); holder.imgDelete = convertView.findViewById(R.id.img_delete); holder.imgEdit = convertView.findViewById(R.id.img_edit); holder.imgEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Edit nguoi dung"); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View viewDialog = inflater.inflate(R.layout.activity_edit_sach, null); masach = viewDialog.findViewById(R.id.edt_maSach); spinnerMaTheLoai = viewDialog.findViewById(R.id.edt_matheloai); tenSach = viewDialog.findViewById(R.id.edt_tensach); soLuong = viewDialog.findViewById(R.id.edt_soluong); giaBia = viewDialog.findViewById(R.id.edt_gia); masach.setText(listSach.get(position).getMaSach()); spinnerMaTheLoai.setText(listSach.get(position).getMaTheloai()); tenSach.setText(listSach.get(position).getTenSach()); soLuong.setText(listSach.get(position).getSoLuong()); giaBia.setText(listSach.get(position).getGiaBia()); builder.setPositiveButton("SAVE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String maS = masach.getText().toString(); String maTheloai = spinnerMaTheLoai.getText().toString(); String ten = tenSach.getText().toString(); String soluong = soLuong.getText().toString(); String gia = giaBia.getText().toString(); Sach sach1 = null; try { sach1 = new Sach(maS, maTheloai, ten, soluong, gia); } catch (Exception e) { e.printStackTrace(); } if (sachDAO.updateSach(sach) > 0) { Toast.makeText(context, "Add successfully", Toast.LENGTH_SHORT).show(); notifyDataSetChanged(); context.finish(); context.startActivity(new Intent(context, ListNguoiDungActivity.class)); } } }); builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.setView(viewDialog); builder.show(); } }); } return null; } @Override public Filter getFilter() { return null; } public class ViewHolder { TextView tenSach, maSach; ImageView imgEdit, imgDelete; } }
package com.victorsaico.practicarealm.activities.fragments; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.design.internal.BottomNavigationItemView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.victorsaico.practicarealm.R; public class MessagesFragment extends Fragment { private BottomNavigationItemView bnve; private TextView txtfragment; public MessagesFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @SuppressLint({"WrongConstant", "RestrictedApi"}) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_messages, container, false); txtfragment = view.findViewById(R.id.txtfragment); bnve = view.findViewById(R.id.bnve); final Fragment homeFragment = new HomeFragment(); final FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); txtfragment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content, homeFragment ).commit(); } }); return view; } }
package fr.polytech.lechat.moviereview.list; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import fr.polytech.lechat.moviereview.R; import fr.polytech.lechat.moviereview.categories.CategoriesActivity; public class MovieListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_list); RecyclerView recyclerView = findViewById(R.id.movie_list_recycler); recyclerView.setAdapter(new ListAdapter(this)); recyclerView.setLayoutManager(new LinearLayoutManager(this)); findViewById(R.id.backBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); final MovieListActivity activity = this; findViewById(R.id.list_cat_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, CategoriesActivity.class); activity.startActivity(intent); } }); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import f.a.a.b; import java.util.LinkedList; public final class th extends a { public ts rwE; public ti rwF; protected final int a(int i, Object... objArr) { int fS; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.rwE == null) { throw new b("Not all required fields were included: BannerSummary"); } else if (this.rwF == null) { throw new b("Not all required fields were included: BannerImg"); } else { if (this.rwE != null) { aVar.fV(1, this.rwE.boi()); this.rwE.a(aVar); } if (this.rwF == null) { return 0; } aVar.fV(2, this.rwF.boi()); this.rwF.a(aVar); return 0; } } else if (i == 1) { if (this.rwE != null) { fS = f.a.a.a.fS(1, this.rwE.boi()) + 0; } else { fS = 0; } if (this.rwF != null) { fS += f.a.a.a.fS(2, this.rwF.boi()); } return fS; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fS = a.a(aVar2); fS > 0; fS = a.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } if (this.rwE == null) { throw new b("Not all required fields were included: BannerSummary"); } else if (this.rwF != null) { return 0; } else { throw new b("Not all required fields were included: BannerImg"); } } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; th thVar = (th) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; byte[] bArr; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); ts tsVar = new ts(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = tsVar.a(aVar4, tsVar, a.a(aVar4))) { } thVar.rwE = tsVar; } return 0; case 2: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); ti tiVar = new ti(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = tiVar.a(aVar4, tiVar, a.a(aVar4))) { } thVar.rwF = tiVar; } return 0; default: return -1; } } } }
package com.sunproservices.TimeCard.Data; import java.math.BigDecimal; import java.sql.Date; import java.sql.Time; import java.util.ArrayList; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sunproservices.Database.DataSource; import com.sunproservices.Database.Database; import com.sunproservices.Database.SQL; import com.sunproservices.Sunpro.SunproUser; import com.sunproservices.Sunpro.Table; /** * DataSource class used to retrieve data that Form_TimeCardInput * uses */ public class TimeCard_DataSource implements DataSource{ private String EmployeeNumber; private SunproUser employee; private Table<Object> empl; // private Table<Object> private Table<Object> currentTime; private Table<Object> previousTime; private Table<Object> previousTime2; private Table<Object> currentProjectTime; private Table<Object> previousProjectTime; private Vector<Object> projectNumber; private SQL sqlConn; private Database connection; private Database previous_Connection; private final Logger logger = LoggerFactory.getLogger(TimeCard_DataSource.class); public TimeCard_DataSource() { } public void setSQL(SQL sqlConn) { this.sqlConn = sqlConn; } public void setConnection(Database conn) { if (connection != null) previous_Connection = connection; // logger.info("setting Connection to {}",conn.name()); sqlConn.setConnection(conn); connection = conn; } private void revertConnection() { if (previous_Connection != null) { // logger.info("reverting Connection to {} from {}",previous_Connection.name(),connection.name()); sqlConn.setConnection(previous_Connection); previous_Connection = null; } } public Table<Object> getEmpl() { return empl; } public void setEmpl(Table<Object> empl) { this.empl = empl; } public Table<Object> getCurrentTime() { return currentTime; } public Table<Object> getPreviousTime() { return previousTime; } public Table<Object> getPreviousTime2() { return previousTime2; } public Vector<Object> getProjectNumber() { return projectNumber; } public void setEmployeeNumber(String employeeNumber) { EmployeeNumber = employeeNumber; } public void setEmployee(SunproUser employee) { this.employee = employee; } public SunproUser getEmployee() { return employee; } public Table<Object> getCurrentProjectTime() { return currentProjectTime; } public Table<Object> getPreviousProjectTime() { return previousProjectTime; } public String retrieveEmployeeNumber() { String empNum = "null"; try { empNum = (String) sqlConn.executeQueryTable( "SELECT * FROM EMPL WHERE UPPER([UserID]) = '" + employee.getUsername().toUpperCase() + "'").getCell(1, 2); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } return empNum; } public float getAccruedPPL() { float accuredPPL = 0; setConnection(Database.Cas_Sunpro); // sqlConn.setConnection(Database.Cas_Sunpro); Table<Object> Vacation = sqlConn.executeQueryTable("SELECT accrual.employee_no, accrual.accrual_no," + " accrual.date_booked, accrual.hours, Empl.first_name, Empl.middle_initial, Empl.last_name, Empl.date_terminated, " + " Empl.PartTime, Empl.division_account_no, Empl.dept_no, Empl.date_hired" + " FROM his_accrual AS accrual INNER JOIN"// Cas_Sunpro.dbo.his_accrual + " Empl ON accrual.employee_no = Empl.employee_no WHERE accrual.employee_no='"// Cas_Sunpro.dbo.Empl + EmployeeNumber + "' and (accrual.accrual_no = 'VAC') AND (Empl.date_terminated IS NULL)" + " AND (Empl.PartTime = 'FULL TIME') OR (accrual.accrual_no = 'VAC2')" + " ORDER BY accrual.employee_no, accrual.date_booked"); for (int r = 1; r < Vacation.getRowCount(); r++) accuredPPL += ((BigDecimal) Vacation.getCell(r, 4)).floatValue(); revertConnection(); // /sqlConn.setConnection(Database.TimeCardSQL); return accuredPPL; } public void retrieveTimeData() { // the try / catch statements are their in case the query doesnt return // any results setConnection(Database.TimeCardSQL); try { this.currentTime = sqlConn .executeQueryTable("SET DATEFIRST 1; select * from Date WHERE ((Date > { fn NOW() } - DATEPART(dw,{ fn NOW() }) ) " + "AND (Date <= { fn NOW() } - DATEPART(dw,{ fn NOW() }) + 7)) AND Emp_No = '" + EmployeeNumber + "'"); this.currentTime.addColumn("Worked"); } catch (IndexOutOfBoundsException e) { currentTime = null; } catch (NullPointerException e) { currentTime = null; } try { this.previousTime = sqlConn .executeQueryTable("SET DATEFIRST 1; SELECT * FROM Date WHERE (Date > { fn NOW() } - DATEPART(dw,{ fn NOW() }) - 7)" + "AND (Date <= { fn NOW() } - DATEPART(dw,{ fn NOW() })) AND Emp_No = '" + EmployeeNumber + "'"); this.previousTime.addColumn("Worked"); } catch (IndexOutOfBoundsException e) { previousTime = null; } catch (NullPointerException e) { previousTime = null; } try { this.previousTime2 = sqlConn .executeQueryTable("SET DATEFIRST 1; SELECT * FROM Date WHERE (Date > { fn NOW() } - DATEPART(dw,{ fn NOW() }) - 14) " + "AND (Date <= { fn NOW() } - DATEPART(dw,{ fn NOW() }) - 7) AND Emp_No = '" + EmployeeNumber + "'"); this.previousTime2.addColumn("Worked"); } catch (IndexOutOfBoundsException e) { previousTime2 = null; } catch (NullPointerException e) { previousTime2 = null; } revertConnection(); } public void retrieveProjectTimeData() { setConnection(Database.Foundation_Documentation); try { this.currentProjectTime = sqlConn .executeQueryTable("SELECT DATEPART(dw,DateWorked) AS Day, SchedTime, EmployeeNo, Project, DateWorked, Start, BreakStart, BreakEnd, EndTime AS [End], " + "(DATEDIFF(mi,Start,EndTime)/60)-(DATEDIFF(mi,BreakStart, BreakEnd)/60) AS Worked, Callout, InitialResponse, Trade " + "FROM LaborDates WHERE (DateWorked >{fn NOW()}+1) AND (DateWorked < {fn NOW()} - DATEPART(dw,{fn NOW()})+7) AND BreakStart is not null AND BreakEnd is not null " + "UNION SELECT DATEPART(dw,DateWorked) AS Day, SchedTime, EmployeeNo, Project, DateWorked, Start, BreakStart, BreakEnd, EndTime AS [End], " + "(DATEDIFF(mi,Start,EndTime)/60) AS Worked, Callout, InitialResponse, Trade " + "FROM LaborDates WHERE (DateWorked >{fn NOW()}+1) AND (DateWorked < {fn NOW()} - DATEPART(dw,{fn NOW()})+7) AND BreakStart is null AND BreakEnd is null ORDER BY DateWorked, Start"); this.currentProjectTime.addColumn("Worked"); } catch (IndexOutOfBoundsException e) { currentProjectTime = null; } catch (NullPointerException e) { currentProjectTime = null; } catch (Exception e2) { e2.printStackTrace(); } try { this.previousProjectTime = sqlConn .executeQueryTable("SELECT DATEPART(dw,DateWorked) AS Day, SchedTime, EmployeeNo, Project, DateWorked, Start, BreakStart, BreakEnd, EndTime AS [End], " + "(DATEDIFF(mi,Start,EndTime)/60)-(DATEDIFF(mi,BreakStart, BreakEnd)/60) AS Worked, Callout, InitialResponse, Trade " + "FROM LaborDates WHERE (DateWorked >{fn NOW()}-6) AND (DateWorked < {fn NOW()} - DATEPART(dw,{fn NOW()})+1) AND BreakStart is not null AND BreakEnd is not null " + "UNION SELECT DATEPART(dw,DateWorked) AS Day, SchedTime, EmployeeNo, Project, DateWorked, Start, BreakStart, BreakEnd, EndTime AS [End], " + "(DATEDIFF(mi,Start,EndTime)/60) AS Worked, Callout, InitialResponse, Trade " + "FROM LaborDates WHERE (DateWorked >{fn NOW()}-6) AND (DateWorked < {fn NOW()} - DATEPART(dw,{fn NOW()})+1) AND BreakStart is null AND BreakEnd is null ORDER BY DateWorked, Start"); this.previousProjectTime.addColumn("Worked"); } catch (IndexOutOfBoundsException e) { previousProjectTime = null; } catch (NullPointerException e) { previousProjectTime = null; } catch (Exception e2) { e2.printStackTrace(); } revertConnection(); } public boolean checkTimeOverlap(Date date, Time start, Time end) { setConnection(Database.TimeCardSQL); boolean overlap; if (sqlConn.execute("" + "Declare @date date = '"+date.toString()+"' " + "Declare @start time = '"+start.toString()+"' " + "Declare @end time = '"+end.toString()+"' " + "select * from dbo.CurrentProjectTime As CPT where CPT.DateWorked = cast(@date as datetime) and CPT.Start = cast(@start as datetime) and CPT.EndTime = cast(@end as datetime)") != null) overlap=true; overlap=false; revertConnection(); return overlap; } public void retrieveListData() { try { this.projectNumber = sqlConn .executeQueryVector("SELECT job_no FROM Cas_Sunpro.dbo.jobs WHERE (job_status = 'A' OR job_status = 'C') ORDER BY job_no"); } catch (NullPointerException e) { projectNumber = null; } } /** * * @param period * - period of time | Either current , prev, or prev2 */ public float getHours(Table<?> tbl, int row) { float hrs = 0; if (!tbl.isEmpty()) if (tbl.getCell(row, "Start") != null && tbl.getCell(row, "BreakStart") == null) hrs = (float) ((double) sqlConn.executeQueryTable( "select cast((DATEDIFF(mi,'" + tbl.getCell(row, "Start") + "','" + tbl.getCell(row, "End") + "')/60.0)as float)") .getCell(1, 1)); else if (tbl.getCell(row, "Start") != null && tbl.getCell(row, "BreakStart") != null) hrs = (float) ((double) sqlConn.executeQueryTable( "select cast((DATEDIFF(mi,'" + tbl.getCell(row, "Start") + "','" + tbl.getCell(row, "End") + "')/60.0)as float) - cast((DATEDIFF(mi,'" + tbl.getCell(row, "BreakStart") + "','" + tbl.getCell(row, "BreakEnd") + "')/60.0)as float)").getCell(1, 1)); return hrs; } /* * DateID,Emp_No,Name,Project,Date,Start,BreakStart,BreakEnd,End,O/HTypeNo, * CallOut,SchedTime,Trade, Notes,ApprovedBy,ApprovedDate,Lunch,Manual * Entry,InitialRespons,Approved,PPLType,TimeOffTypeID * TimeOffNotes,ModifiedBy,ModifiedOn */ public void updateTimeCard(Table tbl) { ArrayList<String> statements = new ArrayList<>(); String stat; for (int row = 1; row < tbl.getRowCount(); row++) for (int column = 1; column < tbl.getColumnCount(); column++) statements.add("MERGE "); int[] affected = sqlConn.batchUpdate((String[]) statements.toArray()); logger.info("Rows affected by statement : {}", affected.toString()); } public void updateData(Table tbl,int row) { sqlConn.setConnection(Database.TimeCardSQL); Object dateID = tbl.getCell(row,"DateID"); String sqlString =""; String rowString = tbl.getCustomRowString(row,new String[]{"Date","Project","Start","BreakStart","BreakEnd","End","O/HTypeNo","Trade","Notes"}); rowString = rowString.replaceAll("'", ""); logger.info(rowString); if(dateID == null) sqlString = "insert into dbo.Date (Emp_No,Date,Project,Start,BreakStart,BreakEnd,[End],[O/HTypeNo],Trade,Notes) " + "values ('"+EmployeeNumber+"',"+rowString+")"; else sqlString ="declare @id int = "+tbl.getCell(row, "DateID")+" " + "update dbo.Date " + "set Date,Project,Start,BreakStart,BreakEnd,[End],[O/HTypeNo],Trade,Notes " + "where [DateID] = @id "; sqlConn.update(sqlString); revertConnection(); } public void updateTimeCardData(Table tbl, int row) { } }
package sample; public class Foot { public Integer size; public Shoe shoe; public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public Shoe getShoe() { return shoe; } public void setShoe(Shoe shoe) { this.shoe = shoe; } }
package icn.core; import icn.core.ContentDesc.Location; import icn.core.Utils.DeviceType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.util.AppCookie; import net.floodlightcontroller.devicemanager.IDevice; import net.floodlightcontroller.forwarding.Forwarding; import net.floodlightcontroller.packet.Data; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.IPv4; import net.floodlightcontroller.packet.TCP; import net.floodlightcontroller.routing.IRoutingDecision; import net.floodlightcontroller.routing.Route; import net.floodlightcontroller.routing.RoutingDecision; import net.floodlightcontroller.topology.NodePortTuple; import org.projectfloodlight.openflow.protocol.OFFactories; import org.projectfloodlight.openflow.protocol.OFFlowModCommand; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.match.Match; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.DatapathId; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.IPv4Address; import org.projectfloodlight.openflow.types.IpProtocol; import org.projectfloodlight.openflow.types.OFPort; import org.projectfloodlight.openflow.types.TransportPort; import org.projectfloodlight.openflow.types.U64; import org.python.modules.sre.SRE_REPEAT; public class IcnEngine extends IcnForwarding { public static IcnEngine instance = null; private int actual = 49152; public static IcnEngine getInstance() { if (instance == null) instance = new IcnEngine(); return instance; } public void handleTcp(IOFSwitch sw, OFMessage msg, Ethernet eth, IPv4 ipv4, TCP tcp, FloodlightContext cntx) { String payload = new String(((Data) tcp.getPayload()).serialize()); String srcIp = ipv4.getSourceAddress().toString(); // ContentRequest if (ipv4.getDestinationAddress().equals(IcnModule.VIP)) { if (payload.contains("HTTP") && payload.contains("GET")) { // HTTP IcnModule.logger.info(payload); // GET = String contentFlowId = srcIp; int flowId = getFlowId(contentFlowId); String contentSourceUrl; try { contentSourceUrl = getContentSource( Utils.getContentId(payload), srcIp, flowId); contentSourceUrl = contentSourceUrl.replace("$flowId$", Integer.toString(flowId)); // contentSourceUrl = contentSourceUrl.replace(":$flowId$", // ""); OFUtils.redirectHttpRequest(sw, msg, ipv4, eth, tcp, srcIp, contentSourceUrl); } catch (ContentNotFoundException e) { OFUtils.returnHttpResponse(sw, msg, ipv4, eth, tcp, OFUtils.HTTP_NOTFOUND); } catch (NoNetworkResourcesException e) { IcnModule.logger.info("503 SERVICE UNAVAILABLE!!!"); OFUtils.returnHttpResponse(sw, msg, ipv4, eth, tcp, OFUtils.HTTP_SERVICE_UNAVAILABLE); } } else if (payload.contains("HTTP") && payload.contains("PUT")) { IcnModule.logger.info(payload); } else if (tcp.getFlags() == 2 // If TCP SYN to Virtual IP is // received // on port 80 && ipv4.getDestinationAddress().equals(IcnModule.VIP) && tcp.getDestinationPort().equals(TransportPort.of(80))) { OFUtils.sendSynAck(sw, msg, ipv4, eth, tcp); } else if (tcp.getFlags() == OFUtils.FIN_ACK_FLAG) { OFPacketIn pi = (OFPacketIn) msg; OFPort inPort = (pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi .getInPort() : pi.getMatch().get(MatchField.IN_PORT)); byte[] resp = OFUtils.generateTCPResponse(eth, ipv4, tcp, OFUtils.ACK_FLAG, null); OFUtils.sendPacketOut(sw, inPort, resp); } } else { String contentFlowId = ipv4.getSourceAddress().toString(); // IcnModule.logger.info(Monitoring.getInstance() // .getFlowIds(contentFlowId).toString()); if (Monitoring.getInstance().getFlowIds(contentFlowId) .contains(tcp.getDestinationPort().getPort())) { IcnModule.logger.info(tcp.getSourcePort() + " " + tcp.getDestinationPort()); setNatFlow(sw, msg, ipv4.getSourceAddress(), ipv4.getDestinationAddress(), tcp.getSourcePort(), tcp.getDestinationPort()); } else { Forwarding forw = new Forwarding(); forw.setRoutingEngineService(routingService); forw.setSwitchService(switchService); OFPacketIn pi = (OFPacketIn) msg; forw.doForwardFlow(sw, pi, cntx, false, SwitchListener.devices .get(ipv4.getSourceAddress().toString()), SwitchListener.devices.get(ipv4.getDestinationAddress() .toString())); forw.doForwardFlow(sw, pi, cntx, false, SwitchListener.devices .get(ipv4.getDestinationAddress().toString()), SwitchListener.devices.get(ipv4.getDestinationAddress() .toString())); } } } private Integer getFlowId(String contentFlowId) { int start = 49152; int stop = 65535; if (actual >= stop) actual = start; for (int i = actual; i < stop; i++) { if (!Monitoring.getInstance().getFlowIds(contentFlowId).contains(i)) { actual = i; break; } } return actual; // int flowId = 0; // do { // Random rn = new Random(); // int range = 65535 - 49152 + 1; // flowId = rn.nextInt(range) + 49152; // // } while (flowId == 0 // || Monitoring.getInstance().getFlowIds(contentFlowId) // .contains(flowId)); // return flowId; } private String getContentSource(String contentId, String srcIp, int flowId) throws ContentNotFoundException, NoNetworkResourcesException { ContentDesc contentDesc = Utils.getContentDesc(contentId); if (contentDesc == null) throw new ContentNotFoundException(); Location bestSource = calculateBestSource(contentDesc.getLocations(), srcIp, contentDesc.getBandwidth(), flowId); return bestSource.getIpAddr() + ":$flowId$/" + bestSource.getLocalPath(); } private Location calculateBestSource(List<Location> locations, String srcIp, int minBandwidth, int flowId) throws NoNetworkResourcesException { IDevice srcDev = Utils.getDevice(srcIp, Utils.DeviceType.SRC); IDevice dstDev = null; List<KeyValuePair<Location, Route>> bestSources = new ArrayList<IcnEngine.KeyValuePair<Location, Route>>(); List<Location> potentials = new ArrayList<ContentDesc.Location>(); for (Location location : locations) { if (location.isLoaded() == false) { potentials.add(location); } } Map<Location, List<Route>> locAndRoutes = new HashMap<ContentDesc.Location, List<Route>>(); for (Location potential : potentials) { dstDev = Utils.getDevice(potential.getIpAddr(), Utils.DeviceType.DST); IcnModule.logger.info("DST & SRC: " + dstDev + " " + srcDev); List<Route> rs = IcnModule.mpathRoutingService.getAllRoutes( srcDev.getAttachmentPoints()[0].getSwitchDPID(), srcDev.getAttachmentPoints()[0].getPort(), dstDev.getAttachmentPoints()[0].getSwitchDPID(), dstDev.getAttachmentPoints()[0].getPort(), minBandwidth, IcnConfiguration.getInstance().getMaxShortestRoutes(), IcnConfiguration.getInstance().getRouteLengthDelta()); IcnModule.logger.info("here 1"); if (rs.size() != 0) locAndRoutes.put(potential, rs); } if (locAndRoutes.size() == 0) throw new NoNetworkResourcesException(); double selectionCost = 0; // IcnModule.logger.info("All possibilities: \n"); for (Entry<Location, List<Route>> entry : locAndRoutes.entrySet()) { IcnModule.logger.info("To location: " + entry.getKey()); for (Route r : entry.getValue()) { double tmpCost = calculateSelectionCost(r.getPath().size(), r.getBottleneckBandwidth()); if (tmpCost > selectionCost) { bestSources.clear(); bestSources .add(new KeyValuePair<ContentDesc.Location, Route>( entry.getKey(), r)); selectionCost = tmpCost; } else if (tmpCost == selectionCost) { bestSources .add(new KeyValuePair<ContentDesc.Location, Route>( entry.getKey(), r)); } IcnModule.logger.info("Route: Cost=" + tmpCost + ", via: " + Utils.routeToString(r)); } } IcnModule.logger.info("here 2"); KeyValuePair<ContentDesc.Location, Route> bestSource = getBestSource(bestSources); IcnModule.logger.info("Best source=" + bestSource.getKey()); if (bestSource.getKey() != null && bestSource.getValue() != null) { if (Monitoring.flows.containsKey(srcIp)) Monitoring.flows.get(srcIp).add(new ContentFlow(flowId)); else { ConcurrentLinkedQueue<ContentFlow> cFlows = new ConcurrentLinkedQueue<ContentFlow>(); cFlows.add(new ContentFlow(flowId)); Monitoring.flows.put(srcIp, cFlows); } prepareRoute(bestSource.getValue(), srcDev, Utils.getDevice( bestSource.getKey().getIpAddr(), DeviceType.DST), TransportPort.of(flowId)); IcnModule.logger.info("here 3"); } return bestSource.getKey(); } private KeyValuePair<Location, Route> getBestSource( List<KeyValuePair<Location, Route>> bestSources) { Random rand = new Random(); return bestSources.get(rand.nextInt(bestSources.size())); } private Double calculateSelectionCost(int hops, int bottleneckBandwidth) { hops = hops / 2; double x = IcnConfiguration.getInstance() .getPathLenghtReservationLevel() - IcnConfiguration.getInstance().getPathLengthAspirationLevel(); double cost1 = (IcnConfiguration.getInstance() .getPathLenghtReservationLevel() - hops) / x; double y = IcnConfiguration.getInstance() .getBandwidthReservationLevel() - IcnConfiguration.getInstance().getBandwidthAspirationLevel(); double cost2 = (IcnConfiguration.getInstance() .getBandwidthReservationLevel() - bottleneckBandwidth) / y; if (cost2 == 0) return cost1; return Math.min(cost1, cost2); } private void prepareRoute(Route route, IDevice srcDevice, IDevice dstDevice, TransportPort srcTcpPort) { DatapathId srcSwId = srcDevice.getAttachmentPoints()[0].getSwitchDPID(); DatapathId dstSwId = dstDevice.getAttachmentPoints()[0].getSwitchDPID(); ContentFlow flow = null; for (ContentFlow f : Monitoring.flows .get(srcDevice.getIPv4Addresses()[0].toString())) { if (f.getFlowId() == srcTcpPort.getPort()) { flow = f; } } flow.setRoute(route.getPath()); Match.Builder forwardMatch = OFFactories.getFactory(OFVersion.OF_13) .buildMatch().setExact(MatchField.ETH_TYPE, EthType.IPv4) .setExact(MatchField.IP_PROTO, IpProtocol.TCP) .setExact(MatchField.IPV4_SRC, srcDevice.getIPv4Addresses()[0]) .setExact(MatchField.IPV4_DST, dstDevice.getIPv4Addresses()[0]) .setExact(MatchField.TCP_SRC, srcTcpPort) .setExact(MatchField.TCP_DST, TransportPort.of(80)); Match.Builder reverseMatch = OFFactories.getFactory(OFVersion.OF_13) .buildMatch().setExact(MatchField.ETH_TYPE, EthType.IPv4) .setExact(MatchField.IP_PROTO, IpProtocol.TCP) .setExact(MatchField.IPV4_SRC, dstDevice.getIPv4Addresses()[0]) .setExact(MatchField.IPV4_DST, srcDevice.getIPv4Addresses()[0]) .setExact(MatchField.TCP_DST, srcTcpPort) .setExact(MatchField.TCP_SRC, TransportPort.of(80)); flow.setFlowMatch(forwardMatch.build()); IcnModule.logger.info("Pushing route: " + Utils.routeToString(route.getPath())); pushRoute(route.getPath(), forwardMatch.build(), AppCookie.makeCookie(2, 0), OFFlowModCommand.ADD, srcSwId); List<NodePortTuple> revRoute = Utils.reverse(route.getPath()); IcnModule.logger .info("Pushing route: " + Utils.routeToString(revRoute)); pushRoute(revRoute, reverseMatch.build(), AppCookie.makeCookie(2, 0), OFFlowModCommand.ADD, srcSwId); } public class KeyValuePair<K, V> implements Map.Entry<K, V> { private K key; private V value; @Override public String toString() { return "KeyValuePair [key=" + key + ", value=" + value + "]"; } public KeyValuePair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return this.key; } public V getValue() { return this.value; } public K setKey(K key) { return this.key = key; } public V setValue(V value) { return this.value = value; } } }
import java.awt.geom.Ellipse2D; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Boid implements Drawable{ /* the boid has a position and a vector which are used to determine the behaviour of the sourounding boids . the update functions use those. after the update function is done the boid has a new position and a new vector which are used to alter the position of the boid in the next frame. */ private cartesian_point boid_position; private cartesian_point new_position;//the next position of the boid after the update. this is so that all boids change position simultaneously private polar_vector boid_vector; private polar_vector new_boid_vector;//used to find the new position. //TODO refactor "allignment" to "alignment" , spelling reasons private polar_vector allignment_vector = new polar_vector(0,0,true);//the vector due to allignment private polar_vector seperation_vector = new polar_vector(0,0,true);//the vector due to seperation private polar_vector cohesion_vector = new polar_vector(0,0,true);//the vector due to cohesion private polar_vector obstacle_vector = new polar_vector(0,0,true);// vector to avoid obstacles and simulation borders private polar_vector food_vector = new polar_vector(0,0,true);//vector to stear towards food (optional) //the minimum desired seperation between the boids. private static double Desired_Seperation = 10;//all boids share this value. it is set via settings in the gui or uses default values private static double Detection_distance = 50;//the distance for which the boid detects other boids. private static double Boid_radius = 5 ; // the radius of the circle representing the boid. private static Settings SimSettings; //TODO write a function to update statics List<Boid> Detected_List = Collections.synchronizedList(new ArrayList<Boid>()); //TODO obstacle list and functions. public cartesian_point getBoid_position() { return boid_position; } public polar_vector getBoid_vector() { return boid_vector; } /* allignment is when the boid takes the average vector of all the boids in its detection radius and adds it to its own vector. */ private void calculate_allignment() { //reset alignment vector so that if boid list is empty, alignment has no effect. allignment_vector = new polar_vector(0,0,true); //add vectors of all nearby boids for(Boid boid: Detected_List) { allignment_vector = Boid_Maths.vector_addition(boid.getBoid_vector(),allignment_vector); } //divide resultant vector by the number of boids to obtain the average vector //TODO make this a method in Boid_Maths allignment_vector.setXcomponent(allignment_vector.getXcomponent() / Detected_List.size()); allignment_vector.setYcomponent(allignment_vector.getYcomponent()/ Detected_List.size()); //add the resulting vector } /* add a vector to the boids vector which points away from boids that are too close. */ private void calculate_seperation() { //calculating the numerator of the equation used to calculate the separation vector, same for all boids this.seperation_vector = new polar_vector(0,0,true);//resetting separation vector double numerator = 2*Boid_radius + Desired_Seperation; for(Boid boid:this.Detected_List) { //calculate separation between this boid and the current boid ( denominator of equation ): double actual_separation = Boid_Maths.Distance_between_points(this.boid_position,boid.boid_position); //TODO make this a Boid_Maths method (find angle between points ) /* to find the angle of boid relative to this boid i use this boid as a reference. I archive this by substracting the position of this.boid from boid. this will give me the x and y difference between the boids. i can then use these to calculate the angle.the angle will be used later. */ double boidXseparation = boid.getBoid_position().Get_X_double() - this.getBoid_position().Get_X_double(); double boidYseparation = boid.getBoid_position().Get_Y_double() - this.getBoid_position().Get_Y_double(); double angle_between_boids = Boid_Maths.find_anticlockwise_angle(boidXseparation,boidYseparation); //calculating the magnitude of the separation vector. /* numerator contains the desired seperation between boids. if actual separation < numerator , the fraction will be >> 1 this is further amplified by raising the fraction to the third power and taking the exponential of that. this results in a larger magnitude the closer the boids get. */ double seperation_magnitude = Math.pow(numerator / actual_separation, 5); //using the magnitude and angle to create a vector polar_vector Temp_seperation_vector = new polar_vector(seperation_magnitude,angle_between_boids,true); //at the moment the temp seperation vector is pointing towards the other boid, so i have to invert it, Temp_seperation_vector.Invert_Vector(); //Now i can add it to the separation vector this.seperation_vector = Boid_Maths.vector_addition(seperation_vector,Temp_seperation_vector); } } private void calculate_cohesion() { cohesion_vector = new polar_vector(0,0,true);//reset cohesion vector //find the average position of nearby boids cartesian_point average_position = Boid_Maths.Calculate_average_boid_position(Detected_List); //find the distance between this boid and the average position double distance = Boid_Maths.Distance_between_points(this.boid_position,average_position); //TODO (find angle between points ) double angle_between_points = Boid_Maths.find_anticlockwise_angle(average_position.Get_X_double() - this.boid_position.Get_X_double(),average_position.Get_Y_double()-this.boid_position.Get_Y_double()); //create vector cohesion_vector = new polar_vector(distance,angle_between_points,true); } private void calculate_obstacle_vector() { } private void calculate_food_vector() { } @Override public void Draw(Graphics2D g) { //<editor-fold desc="Instantiate variables"> int Xpos = this.getBoid_position().Get_X_int(); int Ypos = this.getBoid_position().Get_Y_int(); /* this draws an oval which fits into a rectangle starting at pos x,y with side lengths width and heigh. this means some adjustment has to be made so it is centred on the boid position */ Ellipse2D.Double circle = new Ellipse2D.Double(boid_position.Get_X_int() - (int)Boid_radius,boid_position.Get_Y_int()- (int)Boid_radius,2*(int)Boid_radius,2*(int)Boid_radius); //</editor-fold> //<editor-fold desc="Drawing the boid and vectors"> //drawing the boid if(SimSettings.Show_Boid) { if(this.Detected_List.size() == 0){ g.setColor(Color.red); } else{ g.setColor(Color.green); } g.fill(circle); } //drawing the boid vector if(SimSettings.Show_Boid_vector) { //boid vector end point pos int bvecX = Xpos + (int)this.getBoid_vector().getXcomponent(); int bvecY = Ypos + (int)this.getBoid_vector().getYcomponent(); g.setColor(Color.red); g.drawLine(Xpos,Ypos,bvecX,bvecY); } if(SimSettings.Show_cohesion_vector) { //boid cohesion vector end point pos; int CvecX = Xpos + (int)this.cohesion_vector.getXcomponent(); int CvecY = Ypos + (int)this.cohesion_vector.getYcomponent(); //draw cohesion vector g.setColor(Color.blue); g.drawLine(Xpos,Ypos,CvecX,CvecY); } if(SimSettings.Show_allignment_vector) { //boid allignment vector end point pos int AvecX = Xpos + (int)this.allignment_vector.getXcomponent(); int AvecY = Ypos + (int)this.allignment_vector.getYcomponent(); //draw allignment vector g.setColor(Color.green); g.drawLine(Xpos,Ypos,AvecX,AvecY); } if(SimSettings.Show_seperation_vector) { //boid sparation vector end point pos int SvecX = Xpos + (int)this.seperation_vector.getXcomponent(); int SvecY = Ypos + (int)this.seperation_vector.getYcomponent(); //draw Separation vector g.setColor(Color.black); g.drawLine(Xpos,Ypos,SvecX,SvecY); } if(SimSettings.Show_Boids_nearby) { int xposition = this.getBoid_position().Get_X_int(); int yposition = this.getBoid_position().Get_Y_int(); g.setColor(Color.orange); List<Boid> TempList = new ArrayList<Boid>(); TempList.addAll(Detected_List); for(Boid Boidnearby: TempList) { g.drawLine(xposition,yposition,Boidnearby.getBoid_position().Get_X_int(),Boidnearby.getBoid_position().Get_Y_int()); } } if(SimSettings.Show_Detection_circle){ Ellipse2D.Double Detection_circle = new Ellipse2D.Double(boid_position.Get_X_int() - this.Detection_distance,boid_position.Get_Y_int()- this.Detection_distance,2*this.Detection_distance,2*this.Detection_distance); g.setColor(Color.black); g.draw(Detection_circle); } //</editor-fold> } //update the boid public void Update(double deltaT , List<Boid> Boid_list) { //Update Boid values: e.g. detection distance this.Detection_distance = SimSettings.getDetection_Distance(); //<editor-fold desc="Check which boids are in the detection region and ad them to Detected_List"> this.Detected_List.clear(); for(Boid boid1:Boid_list) { //check which boids are in the detection distance double distance_between_boids = Boid_Maths.Distance_between_points(this.boid_position,boid1.getBoid_position()); if(distance_between_boids < this.Detection_distance) { //preventing the boid adding itself to the boid_nearby list if(boid1 != this) { //TODO make math function BROKEN double Xdistance = this.getBoid_position().Get_X_double() - boid1.getBoid_position().Get_X_double(); double Ydistance = this.getBoid_position().Get_Y_double() - boid1.getBoid_position().Get_Y_double(); polar_vector vector_between_points = new polar_vector(Xdistance,Ydistance,false); vector_between_points.Invert_Vector(); double angle_between_boids = Math.abs(this.boid_vector.getAngle_rad() - vector_between_points.getAngle_rad() ); if(angle_between_boids <= 2*Math.PI*((double)SimSettings.getDetectionAngle()/100))//TODO something is wrong with angle between boids { Detected_List.add(boid1); } } } } //</editor-fold> //<editor-fold desc="Vector calculations"> //do vector calculations if(!SimSettings.Flocking_Enabled) { cohesion_vector = new polar_vector(0,0,false); allignment_vector = new polar_vector(0,0,false); } else { calculate_allignment(); calculate_cohesion(); } calculate_seperation(); //debuff vectors; cohesion_vector = new polar_vector(cohesion_vector.getXcomponent()*SimSettings.getCohesion_multiplier()/this.Detected_List.size(),cohesion_vector.getYcomponent()*SimSettings.getCohesion_multiplier()/this.Detected_List.size(),false);//TODO add /this.Detected_List.size() allignment_vector = new polar_vector(allignment_vector.getXcomponent()*SimSettings.getAlignment_multiplier(),allignment_vector.getYcomponent()*SimSettings.getAlignment_multiplier(),false); //find the new boid vector polar_vector TempVec = new polar_vector(boid_vector.getXcomponent(),boid_vector.getYcomponent(),false); new_boid_vector = Boid_Maths.vector_addition(TempVec,seperation_vector,cohesion_vector,allignment_vector,obstacle_vector); //if the boid is not affected by other vectors it should maintain its velocity if (new_boid_vector.getMagnitude() > 200){ new_boid_vector.setMagnitude(200); } //randomize heading if (Detected_List.size() == 0 && Boid_Maths.RandomDouble()>0.51){ new_boid_vector.setAngle_rad(new_boid_vector.getAngle_rad()-0.01); } else if(Detected_List.size() == 0 && Boid_Maths.RandomDouble()<0.49){ new_boid_vector.setAngle_rad(new_boid_vector.getAngle_rad()+0.01); } //</editor-fold> //<editor-fold desc="set new boid position and ensure its not outside the screen"> double new_X = new_boid_vector.getXcomponent()*deltaT + this.boid_position.Get_X_double(); if (new_X > this.SimSettings.getScreenDimension().width) { new_X = new_X - this.SimSettings.getScreenDimension().width; } else if (new_X < 0) { new_X = this.SimSettings.getScreenDimension().width + new_X; } double new_Y = new_boid_vector.getYcomponent()*deltaT + this.boid_position.Get_Y_double(); if (new_Y > this.SimSettings.getScreenDimension().height) { new_Y = new_Y - this.SimSettings.getScreenDimension().height; } else if (new_Y < 0) { new_Y = this.SimSettings.getScreenDimension().height + new_Y; } new_position = new cartesian_point(new_X,new_Y); //</editor-fold> } //once every boid has ran through update, the boids assume their new positions and vectors public void UpdateComplete() { this.boid_position = this.new_position; this.boid_vector = this.new_boid_vector; } //constructor creating boid with random position and vector public Boid(int maxVector_magnitude,Settings SimSett) { this.SimSettings = SimSett; boid_position = Boid_Maths.RandomPosition(SimSettings.getScreenDimension().width,SimSettings.getScreenDimension().height);//TODO dimensions boid_vector = Boid_Maths.RandomVector(maxVector_magnitude); } }