text
stringlengths
10
2.72M
package uk.ac.aber.dcs.blockmotion.transformer; import uk.ac.aber.dcs.blockmotion.model.IFrame; /** * @author Charlie * @version 16.4.17 */ public class SlideRight extends Transform implements Transformer { @Override public void transform(IFrame frame) { super.initialize(frame.getNumRows(), frame); for (int i = 0; i<super.numRows; i++){ for (int j =0; j<super.numRows; j++){ if (j-1<super.leftMostColumn){ frame.setChar(i, j, super.tempFrame.getChar(i, super.rightMostColumn)); }else { frame.setChar(i, j, super.tempFrame.getChar(i, j - 1)); } } } } }
package me.ewriter.art_chapter2.manager; /** * Created by Zubin on 2016/6/21. */ public class UserManager { public static int sUserId = 1; }
package com.swethasantosh.countriescapitals; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class QuizActivity extends Navigation_main { TextView text; RadioGroup rgroup; RadioButton r1,r2,r3; Button nextbutton; String[] q1 = {"Finland Capital?","China Capital?","India Capital?"}; String[] ans = {"Helsinki","Beizing","Delhi"}; String[] opt ={"Helsinki","Beizing","Delhi", "Helsinki","Beizing","Delhi", "Helsinki","Beizing","Delhi"}; String[] q2 = {"Afghanistan Capital?","Albania Capital?","Algeria Capital?"}; String[] ans2 = {"Kabul","Tirana","Algiers"}; String[] opt2 ={"Kabul","Beizing","Delhi", "Tirana","Beizing","Delhi", "Helsinki","Algiers","Delhi"}; int index =0; public static int marks,correct,wrong; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_quiz); FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.framelayout); //Remember this is the FrameLayout area within your activity_main.xml getLayoutInflater().inflate(R.layout.activity_asia_adapter, contentFrameLayout); getSupportActionBar().setDisplayHomeAsUpEnabled(true); text = (TextView)findViewById(R.id.quetion); nextbutton = (Button)findViewById(R.id.nextquestion); rgroup = (RadioGroup)findViewById(R.id.radiogroup); r1 = (RadioButton)findViewById(R.id.ans1); r2 = (RadioButton)findViewById(R.id.ans2); r3 = (RadioButton)findViewById(R.id.ans3); text.setText(q1[index]); r1.setText(opt[0]); r2.setText(opt[1]); r3.setText(opt[2]); nextbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RadioButton uanswer = (RadioButton)findViewById(rgroup.getCheckedRadioButtonId()); if(rgroup.getCheckedRadioButtonId() == -1) { Toast.makeText(getApplicationContext(),"Choose an answer",Toast.LENGTH_LONG).show(); } else { String anstext = uanswer.getText().toString(); if (anstext.equalsIgnoreCase(ans[index])) { correct++; } else { wrong++; } index++; rgroup.clearCheck(); if (index < q1.length) { text.setText(q1[index]); r1.setText(opt[index * 3]); r2.setText(opt[(index * 3) + 1]); r3.setText(opt[(index * 3) + 2]); } else { marks = correct; Intent intent = new Intent(getApplicationContext(), ResultActivity.class); intent.putExtra("activity", "QuizActivity"); startActivity(intent); } } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_quiz, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package io.dcbn.backend.graph.converters; import io.dcbn.backend.graph.Graph; import io.dcbn.backend.graph.NodeDependency; import io.dcbn.backend.graph.Position; import io.dcbn.backend.graph.StateType; import io.dcbn.backend.utils.Pair; import lombok.NoArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * This class is a converter for the Genie file format (.xdsl) */ @NoArgsConstructor public class GenieConverter { private static final String ID = "id"; private static final List<io.dcbn.backend.graph.Node> EMPTY_NODE_LIST = new ArrayList<>(); private static final Position ZERO_POSITION = new Position(0.0, 0.0); private static final String DYNAMIC = "dynamic"; private static final String COLOR = "color"; private static final String PARENT = "parents"; /** * This method takes a .xdsl file (in the genie format) and converts it to a {@link Graph}. * * @param file the .xdsl file (in the genie format). * @return the converted {@link Graph}. */ public Graph fromGenieToDcbn(InputStream file) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); doc.getDocumentElement().normalize(); Element root = doc.getDocumentElement(); List<Node> nodesFile = extractChildren(root.getElementsByTagName("nodes").item(0), "cpt"); NodeList nodesAttributes = root.getElementsByTagName("node"); List<io.dcbn.backend.graph.Node> dcbnNodes = new ArrayList<>(); //Creating all nodes to avoid reference problems for (Node node : nodesFile) { String nodeID = node.getAttributes().getNamedItem(ID).getNodeValue(); io.dcbn.backend.graph.Node dcbnNode = new io.dcbn.backend.graph.Node(nodeID, null, null, null, null, null, ZERO_POSITION); dcbnNodes.add(dcbnNode); } for (Node node : nodesFile) { String nodeID = node.getAttributes().getNamedItem(ID).getNodeValue(); Node nodeAttribute = getNodeWithID(nodesAttributes, nodeID, false); //------Setting the state for this node------- List<Node> states = extractChildren(node, "state"); //copy states to array List<String> statesNameList = new ArrayList<>(); states.forEach(state -> statesNameList.add(state.getAttributes().getNamedItem(ID).getNodeValue())); String[] statesNameArray = new String[states.size()]; statesNameList.toArray(statesNameArray); StateType stateType; if (statesNameArray.length == 2 && statesNameArray[0].equals("false") && statesNameArray[1].equals("true")) { throw new IllegalArgumentException("The states True and False are inverted. Please put True first, then false"); } else if (statesNameArray.length == 2) { stateType = StateType.BOOLEAN; } else { throw new IllegalArgumentException("The DBN in the document contains nodes that have different states" + " as the only ones supported by the backend"); } //-------Setting the probabilities for the node dependencies--------- //Creating the probability array for Time 0 double[][] probabilitiesT0 = extractProbabilities(node, statesNameArray.length); //Creating the probability array for Time T Node dynamicNode = getNodeWithID(root.getElementsByTagName(DYNAMIC).item(0).getChildNodes(), nodeID, true); double[][] probabilitiesTT; if (dynamicNode == null) { probabilitiesTT = probabilitiesT0; } else { probabilitiesTT = extractProbabilities(dynamicNode, statesNameArray.length); } //----------Creating the Parents-------------- List<io.dcbn.backend.graph.Node> parents; extractParentNodes(node, dcbnNodes); parents = extractParentNodes(node, dcbnNodes); List<io.dcbn.backend.graph.Node> parentsTm1; if (dynamicNode == null) { parentsTm1 = EMPTY_NODE_LIST; } else { extractParentNodes(dynamicNode, dcbnNodes); parentsTm1 = extractParentNodes(dynamicNode, dcbnNodes); } //-----------Creating the node dependencies------------- NodeDependency timeZeroDependency = new NodeDependency(parents, EMPTY_NODE_LIST, probabilitiesT0); NodeDependency timeTDependency = new NodeDependency(parents, parentsTm1, probabilitiesTT); //-----Getting color of the node---------- String color = extractChildren(nodeAttribute, "interior") .get(0).getAttributes().getNamedItem(COLOR).getNodeValue(); //--------Getting the position------------ String[] positionsString = extractChildren(nodeAttribute, "position") .get(0).getTextContent().split(" "); int[] positionInt = new int[positionsString.length]; for (int j = 0; j < positionsString.length; j++) { positionInt[j] = Integer.parseInt(positionsString[j]); } Position position = new Position((positionInt[0] + positionInt[2]) / 2.0, ((positionInt[1] + positionInt[3]) / 2.0)); //---------Creating the Node----------- io.dcbn.backend.graph.Node dcbnNode = findDcbnNodeByName(dcbnNodes, nodeID); dcbnNode.setTimeZeroDependency(timeZeroDependency); dcbnNode.setTimeTDependency(timeTDependency); dcbnNode.setColor("#" + color); dcbnNode.setStateType(stateType); dcbnNode.setPosition(position); } int timeSlices; Node dynamicItem = root.getElementsByTagName(DYNAMIC).item(0); if (dynamicItem == null) { timeSlices = 1; } else { timeSlices = Integer.parseInt(dynamicItem.getAttributes().getNamedItem("numslices").getNodeValue()); } //--------Setting the real names for the nodes--------- for (Node node : nodesFile) { String nodeID = node.getAttributes().getNamedItem(ID).getNodeValue(); Node nodeAttribute = getNodeWithID(nodesAttributes, nodeID, false); String name = extractChildren(nodeAttribute, "name").get(0).getTextContent(); findDcbnNodeByName(dcbnNodes, nodeID).setName(name); } String name = root.getElementsByTagName("genie").item(0).getAttributes().getNamedItem("name").getNodeValue(); return new Graph(name, timeSlices, dcbnNodes); } public String fromDcbnToGenie(Graph graph) throws ParserConfigurationException, TransformerException { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); documentFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); document.setXmlVersion("1.0"); //Creating structure of document Element root = document.createElement("smile"); root.setAttribute("version", "1.0"); root.setAttribute("id", "Network1"); root.setAttribute("numsamples", "10000"); root.setAttribute("discsamples", "10000"); document.appendChild(root); Element nodesElement = document.createElement("nodes"); root.appendChild(nodesElement); Element dynamicElement = document.createElement(DYNAMIC); dynamicElement.setAttribute("numslices", "" + graph.getTimeSlices()); root.appendChild(dynamicElement); Element extensionsElement = document.createElement("extensions"); root.appendChild(extensionsElement); Element genieElement = document.createElement("genie"); genieElement.setAttribute("version", "1.0"); genieElement.setAttribute("app", "GeNIe 2.2.2601.0 ACADEMIC"); genieElement.setAttribute("name", graph.getName()); genieElement.setAttribute("faultnameformat", "nodestate"); extensionsElement.appendChild(genieElement); Element plateElement = document.createElement("plate"); plateElement.setAttribute("leftwidth", "120"); plateElement.setAttribute("rightwidth", "120"); Position platePosition = findOutMaxPos(graph.getNodes()); int plateX = platePosition.getX().intValue() + 200; //200 is default offset int plateY = platePosition.getY().intValue() + 200; //200 is default offset plateElement.setTextContent("0 0 " + plateX + " " + plateY); genieElement.appendChild(plateElement); List<io.dcbn.backend.graph.Node> sortedNodes = sortNodesAfterNumberOfParents(graph); for (io.dcbn.backend.graph.Node node : sortedNodes) { String nodeID = node.getName().replace(" ", "_"); //------------Creating node attribute---------------- Element nodeElement = document.createElement("node"); nodeElement.setAttribute("id", nodeID); genieElement.appendChild(nodeElement); //Setting the name Element nameElement = document.createElement("name"); nameElement.setTextContent(node.getName()); nodeElement.appendChild(nameElement); //Setting the color Element interiorElement = document.createElement("interior"); interiorElement.setAttribute(COLOR, node.getColor().replace("#", "")); nodeElement.appendChild(interiorElement); //Setting default outline color Element outlineElement = document.createElement("outline"); outlineElement.setAttribute(COLOR, "000080"); nodeElement.appendChild(outlineElement); //Setting default font settings Element fontElement = document.createElement("font"); fontElement.setAttribute(COLOR, "000000"); fontElement.setAttribute("name", "Arial"); fontElement.setAttribute("size", "8"); nodeElement.appendChild(fontElement); //Setting position with default size Element positionElement = document.createElement("position"); double nodeX = node.getPosition().getX(); double nodeY = node.getPosition().getY(); //default sizes double xTopL = nodeX + 24; double xBotR = nodeX - 24; double yTopL = nodeY + 15; double yBotR = nodeY - 15; positionElement.setTextContent((int) xTopL + " " + (int) yTopL + " " + (int) xBotR + " " + (int) yBotR); nodeElement.appendChild(positionElement); //Setting default barchart settings Element barchartElement = document.createElement("barchart"); barchartElement.setAttribute("active", "true"); barchartElement.setAttribute("width", "128"); barchartElement.setAttribute("height", "78"); nodeElement.appendChild(barchartElement); //-------------Creating the Conditional Probability Tables-------------------- //----For Time 0---- NodeDependency timeZeroDependency = node.getTimeZeroDependency(); Element cptElement = document.createElement("cpt"); //Creating cpt element cptElement.setAttribute("id", nodeID); cptElement.setAttribute(DYNAMIC, "plate"); nodesElement.appendChild(cptElement); //Setting states for (String state : node.getStateType().getStates()) { Element stateElement = document.createElement("state"); stateElement.setAttribute("id", state); cptElement.appendChild(stateElement); } //Setting the probabilities createProbString(document, cptElement, timeZeroDependency); //Setting the parents StringBuilder parentsString = new StringBuilder(); if (!timeZeroDependency.getParents().isEmpty()) { for (io.dcbn.backend.graph.Node parent : timeZeroDependency.getParents()) { parentsString.append(parent.getName().replace(" ", "_")).append(" "); } Element parentsElement = document.createElement(PARENT); parentsElement.setTextContent(parentsString.toString()); cptElement.appendChild(parentsElement); } //-----For Time T------ NodeDependency timeTDependency = node.getTimeTDependency(); if (!timeTDependency.getParentsTm1().isEmpty()) { //Creating the cpt element Element cptElementTime = document.createElement("cpt"); cptElementTime.setAttribute("id", nodeID); cptElementTime.setAttribute("order", "1"); dynamicElement.appendChild(cptElementTime); //Setting the parents StringBuilder parentsStringTime = new StringBuilder(); for (io.dcbn.backend.graph.Node parent : timeTDependency.getParentsTm1()) { parentsStringTime.append(parent.getName().replace(" ", "_")).append(" "); } Element parentsElementTime = document.createElement(PARENT); parentsElementTime.setTextContent(parentsStringTime.toString()); cptElementTime.appendChild(parentsElementTime); //Setting the probabilities createProbString(document, cptElementTime, timeTDependency); } } StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); transformer.transform(new DOMSource(document), new StreamResult(sw)); return sw.toString(); } /** * This method sorts a {@link List<io.dcbn.backend.graph.Node>} by the number * of parents (direct and indirectly linked) * * @param graph The graph containing the nodes * @return the {@link List<io.dcbn.backend.graph.Node>} sorted by the number * parents (direct and indirectly linked) */ private List<io.dcbn.backend.graph.Node> sortNodesAfterNumberOfParents(Graph graph) { List<io.dcbn.backend.graph.Node> nodes = graph.getNodes(); List<Pair<io.dcbn.backend.graph.Node, Integer>> sortedNodePair = new ArrayList<>(); sortedNodePair.add(new Pair<>(nodes.get(0), getNumberOfParents(nodes.get(0)))); for (int j = 1; j < nodes.size(); j++) { int numberOfParents = getNumberOfParents(nodes.get(j)); boolean inserted = false; for (int i = 0; i < sortedNodePair.size(); i++) { if (sortedNodePair.get(i).getValue() > numberOfParents) { sortedNodePair.add(i, new Pair<>(nodes.get(j), numberOfParents)); inserted = true; break; } } if (!inserted) { sortedNodePair.add(new Pair<>(nodes.get(j), numberOfParents)); } } List<io.dcbn.backend.graph.Node> sortedNodes = new ArrayList<>(); for (Pair<io.dcbn.backend.graph.Node, Integer> pair : sortedNodePair) { sortedNodes.add(pair.getKey()); } return sortedNodes; } /** * This method returns the number of parents (direct and indirect) of th given {@link io.dcbn.backend.graph.Node} * * @param node the {@link io.dcbn.backend.graph.Node} * @return returns the number of parents (direct and indirect) */ private int getNumberOfParents(io.dcbn.backend.graph.Node node) { List<io.dcbn.backend.graph.Node> queue = new ArrayList<>(); int numberOfParents = 0; queue.add(node); while (!queue.isEmpty()) { io.dcbn.backend.graph.Node actualNode = queue.get(0); List<io.dcbn.backend.graph.Node> parents = actualNode.getTimeTDependency().getParents(); numberOfParents += parents.size(); for (io.dcbn.backend.graph.Node parent : parents) { if (!queue.contains(parent)) { queue.add(parent); } } queue.remove(0); } return numberOfParents; } /** * This returns a new {@link Position} with the maximum x and y value of the nodes {@link Position} * * @param nodes the {@link List<io.dcbn.backend.graph.Node>} to inspect * @return A new {@link Position} with the maximum x and y value of the nodes {@link Position} */ private Position findOutMaxPos(List<io.dcbn.backend.graph.Node> nodes) { double maxX = 0; double maxY = 0; for (io.dcbn.backend.graph.Node node : nodes) { Position position = node.getPosition(); if (position.getX() > maxX) { maxX = position.getX(); } if (position.getY() > maxY) { maxY = position.getY(); } } return new Position(maxX, maxY); } /** * Creates the probability string to insert to the {@link Document}. * * @param document the {@link Document} * @param cptElement the {@link Element} the probabilities belongs to. * @param timeTDependency the {@link NodeDependency} where the probabilities are defined. */ private void createProbString(Document document, Element cptElement, NodeDependency timeTDependency) { StringBuilder probabilitiesStringTime = new StringBuilder(); double[][] probabilitiesTime = timeTDependency.getProbabilities(); for (double[] doubles : probabilitiesTime) { for (double aDouble : doubles) { probabilitiesStringTime.append(aDouble).append(" "); } } Element probabilitiesElementTime = document.createElement("probabilities"); probabilitiesElementTime.setTextContent(probabilitiesStringTime.toString()); cptElement.appendChild(probabilitiesElementTime); } /** * Returns the {@link Node} with the given id. * * @param nodeList the List of node to search into. * @param id the id to search after. * @return the {@link Node} with the given id. */ private Node getNodeWithID(NodeList nodeList, String id, boolean isDynamic) { for (int i = 0; i < nodeList.getLength(); i++) { if (nodeList.item(i).hasAttributes() && nodeList.item(i).getAttributes().getNamedItem(ID).getNodeValue().equals(id)) { return nodeList.item(i); } } if (isDynamic) { return null; } else { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Import failed (ExtractChildren returned null, Node not found)"); } } /** * Returns the children of the {@link Node} that have the given tag. returns null if no children was found. * * @param node the {@link Node} to inspect. * @param nodeName the tag of the {@link Node}. * @return the children of the {@link Node} that have the given tag. returns null if no children was found. */ private List<Node> extractChildren(Node node, String nodeName) { NodeList children = node.getChildNodes(); List<Node> nodes = new ArrayList<>(); for (int i = 0; i < children.getLength(); i++) { if (children.item(i).getNodeName().equals(nodeName)) { nodes.add(children.item(i)); } } return nodes; } /** * This method extracts the text content of the "probabilities" child node of the given {@link Node} * and parses it to a corresponding double[][]. * * @param node the {@link Node} to inspect * @param states the number of states the {@link io.dcbn.backend.graph.Node} can have. * @return a corresponding double[][] of the probabilities. */ private double[][] extractProbabilities(Node node, int states) { List<Node> probabilities = extractChildren(node, "probabilities"); String[] arrayOfProbs = probabilities.get(0).getTextContent().split(" "); double[][] condiProbTable = new double[arrayOfProbs.length / states][states]; int indexOfOldArray = 0; for (int j = 0; j < condiProbTable.length; j++) { for (int k = 0; k < condiProbTable[j].length; k++) { condiProbTable[j][k] = Double.parseDouble(arrayOfProbs[indexOfOldArray]); indexOfOldArray++; } } return condiProbTable; } /** * It returns the {@link List<io.dcbn.backend.graph.Node>} of parents described in the "parent" sub node of the given {@link Node}. * * @param node the {@link Node} to inspect. * @param existingDcbnNodes a {@link List<io.dcbn.backend.graph.Node>} of the already existing {@link io.dcbn.backend.graph.Node} objects. * @return the {@link List<io.dcbn.backend.graph.Node>} of parents described in the "parent" sub node of the given {@link Node}. */ private List<io.dcbn.backend.graph.Node> extractParentNodes(Node node, List<io.dcbn.backend.graph.Node> existingDcbnNodes) { if (!extractChildren(node, PARENT).isEmpty()) { String[] parentsT0TTString = extractChildren(node, PARENT) .get(0).getTextContent().split(" "); List<io.dcbn.backend.graph.Node> parentNodes = new ArrayList<>(); for (String s : parentsT0TTString) { parentNodes.add(findDcbnNodeByName(existingDcbnNodes, s)); } return parentNodes; } return new ArrayList<>(); } /** * Returns the {@link io.dcbn.backend.graph.Node} with the given name. * * @param nodes the {@link List<io.dcbn.backend.graph.Node>} to search into * @param name the name to search after. * @return The {@link io.dcbn.backend.graph.Node} with the given name. */ private io.dcbn.backend.graph.Node findDcbnNodeByName(List<io.dcbn.backend.graph.Node> nodes, String name) { List<io.dcbn.backend.graph.Node> nodeToReturn = nodes.stream() .filter(node -> node.getName().equals(name)).collect(Collectors.toList()); return nodeToReturn.get(0); } }
package de.scads.gradoop_service.server.helper.grouping.functions; import org.apache.flink.api.common.functions.GroupReduceFunction; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.util.Collector; import java.util.HashSet; import java.util.Set; /** * Reduce the Dataset of properties, represented as tuples3 of label of vertices with this * property, property key and a boolean specifying if it is numerical into one tuple3 with all * vertex labels in the first field. */ public class LabelGroupReducer implements GroupReduceFunction< Tuple3<String, String, Boolean>, Tuple3<Set<String>, String, Boolean>> { /** * {@inheritDoc} */ @Override public void reduce( Iterable<Tuple3<String, String, Boolean>> iterable, Collector<Tuple3<Set<String>, String, Boolean>> collector) throws Exception { Tuple3<Set<String>, String, Boolean> result = new Tuple3<>(); result.f0 = new HashSet<>(); for (Tuple3<String, String, Boolean> tuple : iterable) { result.f0.add(tuple.f0); result.f1 = tuple.f1; result.f2 = tuple.f2; } collector.collect(result); } }
package com.visenze.productcat.android.api; import com.visenze.productcat.android.ImageSearchParams; import com.visenze.productcat.android.ProductCat; import com.visenze.productcat.android.TextSearchParams; /** * Search operations interface. */ public interface SearchOperations { public void imageSearch(ImageSearchParams params, final ProductCat.ResultListener resultListener); public void textSearch(TextSearchParams params, ProductCat.ResultListener mListener); public void setRetryPolicy(int timeout, int retryCount); }
package fr.ucbl.disp.vfos.controller.physic; import fr.ucbl.disp.vfos.controller.data.AData; import fr.ucbl.disp.vfos.controller.data.DistanceData1D; import fr.ucbl.disp.vfos.controller.data.UltraSonicData; import fr.ucbl.disp.vfos.controller.sensor.ASensor; import fr.ucbl.disp.vfos.controller.sensor.distance.UltraSonicSensorByGPIO; import fr.ucbl.disp.vfos.controller.sensor.listner.SensorProcessedDataListener; import fr.ucbl.disp.vfos.controller.sensor.listner.SensorRawDataListener; import fr.ucbl.disp.vfos.util.configurator.SensorConfiguration; public class USfilter extends APhysicFilter { protected UltraSonicData data; protected boolean processed = true; private double sigma; public USfilter(SensorConfiguration sensorConfig) { sigma=sensorConfig.getSigma(); } protected void fireData(AData data) { for(SensorProcessedDataListener listener : getProcessedSensorListener()) { if(listener instanceof SensorProcessedDataListener){ //System.out.println("fireDataFiltre "+data.toString()); ((SensorProcessedDataListener) listener).receiveSensorProcessedData(data); } } } public void run() { // TODO Auto-generated method stub try { while (!Thread.currentThread().isInterrupted()){ if(!this.processed){ this.processed = true; this.fireData(new DistanceData1D(this.data.getDistance(), this.data.getEmitter())); this.data=null; this.processed= true; } Thread.sleep(60) ; } } catch (InterruptedException e) { Thread.currentThread(); Thread.interrupted() ; } } // static boolean newDetection(double oldValue, double newValue) // { // if(oldValue>100 && newValue<20 && Math.abs(oldValue - newValue)>20) // // { // return true;} // else // return false; // } public void cancel() { Thread.currentThread().interrupt() ; } public void receiveSensorRawData( AData data) { if(data instanceof UltraSonicData){ this.processed = false; this.data = (UltraSonicData) data; } } }
package payroll; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.security.access.prepost.PreAuthorize; @PreAuthorize("hasRole('ROLE_MANAGER')") //restricts access to people with ROLE_MANAGER. public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> { // Spring Data REST provides paging support: PagingAndSortingRepository //... which adds extra options to set page size and adds navigational links to hop from page to page //On save(), either the employee’s manager is null (initial creation of a new employee when no manager has been assigned), // ...or the employee’s manager’s name matches the currently authenticated user’s name @Override @PreAuthorize("#employee?.manager == null or #employee?.manager?.name == authentication?.name") Employee save(@Param("employee") Employee employee); //On delete(), the method either has access to only an id (or the next PreAuthorize), it must find the employeeRepository in the application context, perform a findOne(id), //...and check the manager against the currently authenticated user. @Override @PreAuthorize("@employeeRepository.findById(#id)?.manager?.name == authentication?.name") void deleteById(@Param("id") Long id); //"....or the method has access to the employee " @Override @PreAuthorize("#employee?.manager?.name == authentication?.name") void delete(@Param("employee") Employee employee); } // '?.' property navigator to handle null checks. //@Param(…) on the arguments to link HTTP operations with the methods. /* The @PreAuthorize expressions applied to your repository are access rules. These rules are for nought without a security policy: SecurityConfiguration.java */
/* * Copyright 2002-2018 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.resource; import reactor.core.publisher.Mono; import org.springframework.core.io.Resource; /** * A {@code VersionStrategy} that relies on a fixed version applied as a request * path prefix, e.g. reduced SHA, version name, release date, etc. * * <p>This is useful for example when {@link ContentVersionStrategy} cannot be * used such as when using JavaScript module loaders which are in charge of * loading the JavaScript resources and need to know their relative paths. * * @author Rossen Stoyanchev * @author Brian Clozel * @since 5.0 * @see VersionResourceResolver */ public class FixedVersionStrategy extends AbstractPrefixVersionStrategy { private final Mono<String> versionMono; /** * Create a new FixedVersionStrategy with the given version string. * @param version the fixed version string to use */ public FixedVersionStrategy(String version) { super(version); this.versionMono = Mono.just(version); } @Override public Mono<String> getResourceVersion(Resource resource) { return this.versionMono; } }
package collection; import java.io.*; import java.util.*; // Arrays class contains various methods for manipulating arrays // - fill // - equals // - binarySearch // - sort // It also contains a static factory that allows arrays to be viewed as lists // - List asList (Object[] a); // All methods of Arrays are static public class ArraysDemo { public static void main(String[] args) { final int MAX = 10000; final int SIZE = 50; int i, k, p; int[] a = new int[SIZE]; for (i = 0; i < SIZE; i++) { a[i] = (int) (Math.random() * MAX); } Arrays.sort(a); for (i = 0; i < SIZE; i++) { System.out.print(" " + a[i]); } BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\n\nEnter key: "); try { k = Integer.parseInt(br.readLine()); p = Arrays.binarySearch(a, k); if (p < 0) { System.out.println("Find not match!"); } else { System.out.println("Found in " + (p + 1) + " position"); } } catch (IOException e) { } } }
package com.engin.service; import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.support.annotation.Nullable; import android.widget.Toast; import com.engin.utils.LogUtil; /** * @Description: * @Author: ZhaoNingqiang * @Time 2016/07/28 下午6:10 */ public class LocalServiceByMessenger extends Service { class LocalService extends Handler{ @Override public void handleMessage(Message msg) { Toast.makeText(LocalServiceByMessenger.this, "LL", Toast.LENGTH_SHORT).show(); LogUtil.d("TTTT s "+Thread.currentThread().getName()); } } Messenger messenger = new Messenger(new LocalService()); @Override public void onCreate() { LogUtil.d("LocalServiceByMessenger onCreate"); super.onCreate(); } @Nullable @Override public IBinder onBind(Intent intent) { return messenger.getBinder(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package summultiple; import java.util.Scanner; import java.util.HashSet; /** * * @author venom */ public class SumMultiple { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here HashSet multiples = new HashSet(); int multiplex = 3; int multipley = 5; while(multiplex < 1000) { multiples.add(multiplex); multiplex += 3; } while(multipley < 1000) { multiples.add(multipley); multipley += 5; } int sum = 0; for (Object x : multiples) { sum += (int)x; } System.out.println(sum); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package userInterface.SystemAdminWorkArea; import Business.MunicipalCorporation.MunicipalCorporation; import Business.FedGoverment; import Business.Organization.Organization; import Business.StateGoverment.StateGoverment; import java.awt.CardLayout; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; /** * * @author User */ public class SystemAdminWorkAreaJPanel extends javax.swing.JPanel { /** * Creates new form SystemAdminWorkAreaJPanel */ private JPanel userProcessContainer; private FedGoverment fedGoverment; public SystemAdminWorkAreaJPanel(JPanel userProcessContainer,FedGoverment fedGoverment) { initComponents(); this.userProcessContainer=userProcessContainer; this.fedGoverment=fedGoverment; populateTree(); } public void populateTree(){ DefaultTreeModel model = (DefaultTreeModel) SystemTree.getModel(); ArrayList<StateGoverment> stateGovermentList = fedGoverment.getStateGovermentList(); ArrayList<MunicipalCorporation> departmentList; ArrayList<Organization> organizationList; StateGoverment stateGoverment; MunicipalCorporation department; Organization organization; DefaultMutableTreeNode stateGoverments = new DefaultMutableTreeNode("StateGoverments"); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); root.removeAllChildren(); root.insert(stateGoverments, 0); DefaultMutableTreeNode stateGovermentNode; DefaultMutableTreeNode departmentNode; DefaultMutableTreeNode organizationNode; for (int i = 0; i < stateGovermentList.size(); i++) { stateGoverment = stateGovermentList.get(i); stateGovermentNode = new DefaultMutableTreeNode(stateGoverment.getName()); stateGoverments.insert(stateGovermentNode, i); departmentList = stateGoverment.getMunicipalCorporationDirectory().getMunicipalCorporationList(); for (int j = 0; j < departmentList.size(); j++) { department = departmentList.get(j); departmentNode = new DefaultMutableTreeNode(department.getName()); stateGovermentNode.insert(departmentNode, j); organizationList = department.getOrganizationDirectory().getOrganizationList(); for (int k = 0; k < organizationList.size(); k++) { organization = organizationList.get(k); organizationNode = new DefaultMutableTreeNode(organization.getName()); departmentNode.insert(organizationNode, k); } } } model.reload(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); SystemTree = new javax.swing.JTree(); jPanel2 = new javax.swing.JPanel(); btnManageStateGoverment = new javax.swing.JButton(); btnManageDepartment = new javax.swing.JButton(); btnDeptAdmin = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jSplitPane1.setDividerLocation(130); SystemTree.setBackground(new java.awt.Color(153, 153, 248)); javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Federal Goverment"); SystemTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1)); jScrollPane1.setViewportView(SystemTree); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 801, Short.MAX_VALUE) ); jSplitPane1.setLeftComponent(jPanel1); jPanel2.setLayout(null); btnManageStateGoverment.setFont(new java.awt.Font("Calibri", 1, 14)); // NOI18N btnManageStateGoverment.setText("Manage State Goverment"); btnManageStateGoverment.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnManageStateGovermentActionPerformed(evt); } }); jPanel2.add(btnManageStateGoverment); btnManageStateGoverment.setBounds(330, 140, 240, 70); btnManageDepartment.setFont(new java.awt.Font("Calibri", 1, 14)); // NOI18N btnManageDepartment.setText("Manage Municipal Corporation"); btnManageDepartment.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnManageDepartmentActionPerformed(evt); } }); jPanel2.add(btnManageDepartment); btnManageDepartment.setBounds(330, 250, 240, 70); btnDeptAdmin.setFont(new java.awt.Font("Calibri", 1, 14)); // NOI18N btnDeptAdmin.setText("Manage MC Admin"); btnDeptAdmin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeptAdminActionPerformed(evt); } }); jPanel2.add(btnDeptAdmin); btnDeptAdmin.setBounds(330, 370, 240, 70); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sysadmin.jpg"))); // NOI18N jPanel2.add(jLabel1); jLabel1.setBounds(0, 0, 1300, 800); jSplitPane1.setRightComponent(jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1083, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 803, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void btnManageStateGovermentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManageStateGovermentActionPerformed // TODO add your handling code here: ManageStateGovermentJPanel msg=new ManageStateGovermentJPanel(userProcessContainer, fedGoverment); userProcessContainer.add("Manage State Goverment", msg); CardLayout layout=(CardLayout)userProcessContainer.getLayout(); layout.next(userProcessContainer); }//GEN-LAST:event_btnManageStateGovermentActionPerformed private void btnManageDepartmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnManageDepartmentActionPerformed // TODO add your handling code here: ManageMunicipalCorpJPanel mdj=new ManageMunicipalCorpJPanel(userProcessContainer, fedGoverment); userProcessContainer.add("Manage Department", mdj); CardLayout layout=(CardLayout)userProcessContainer.getLayout(); layout.next(userProcessContainer); }//GEN-LAST:event_btnManageDepartmentActionPerformed private void btnDeptAdminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeptAdminActionPerformed // TODO add your handling code here: MunicipalCorpAdminJPanel dpa=new MunicipalCorpAdminJPanel(userProcessContainer, fedGoverment); userProcessContainer.add("Dept Admin", dpa); CardLayout layout=(CardLayout)userProcessContainer.getLayout(); layout.next(userProcessContainer); }//GEN-LAST:event_btnDeptAdminActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTree SystemTree; private javax.swing.JButton btnDeptAdmin; private javax.swing.JButton btnManageDepartment; private javax.swing.JButton btnManageStateGoverment; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSplitPane jSplitPane1; // End of variables declaration//GEN-END:variables }
package dubstep; //@Author - Anunay Rao import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jsqlparser.eval.Eval; import net.sf.jsqlparser.expression.PrimitiveValue; import net.sf.jsqlparser.schema.Column; public class Evaluator extends Eval { //private HashMap<String, HashMap<String, ColumnInfo>> dbMap; public PrimitiveValue[] tuple; public Evaluator(PrimitiveValue[] tuple){ //this.schema = schema; this.tuple = tuple; //this.dbMap = dbMap; } @Override public PrimitiveValue eval(Column c) throws SQLException { if(ConfigureVariables.beforejoin) { String tableName=""; String colName = c.getColumnName().toLowerCase(); //System.out.println(colName); int b = 0; if(c.getTable().getName()==null) { for(String key : ConfigureVariables.tablecol.keySet()) { for(String q : ConfigureVariables.tablecol.get(key)) { if(q.equals(colName.toLowerCase())) { tableName = key; //System.out.println("NAME:"+tableName); b = 1; break; } } if(b==1) break; } } else { tableName = c.getTable().getName(); //System.out.println(tableName); /* if(ConfigureVariables.tablealias.containsKey(tableName.toUpperCase())) { tableName = ConfigureVariables.tablealias.get(tableName).toLowerCase(); }*/ //int wt = 1; for(String s : ConfigureVariables.tablealias.keySet()) { if(tableName.equals(ConfigureVariables.tablealias.get(s))) { tableName = s.toLowerCase(); //System.out.println("Here"+tableName); break; } } } //System.out.println(colName); //System.out.println(tableName); int index = -1; /* if(ConfigureVariables.dbMap.containsKey(tableName)) { HashMap<String, ColumnInfo> key = ConfigureVariables.dbMap.get(tableName); int i = 0; for (Map.Entry<String, ColumnInfo> entry1 : key.entrySet()) { String s1 = entry1.getKey().toLowerCase(); System.out.println(s1); //ColumnInfo c1 = entry1.getValue(); if(s1.equals(colName)){ index=i; break; } i++; //System.out.println(s+":"+s1 +" : "+ c1.colNo +":"+c1.colDataType ); } } ////////////// if(ConfigureVariables.tablecol.containsKey(tableName)) { //HashMap<String, String> key = ConfigureVariables.tablecol.get(tableName); int i = 0; for (Map.Entry<String, String> entry1 : ConfigureVariables.tablecol.entrySet()) { String s1 = entry1.getValue().toLowerCase(); System.out.println(s1); //ColumnInfo c1 = entry1.getValue(); if(s1.equals(colName)){ index=i; //break; } i++; //System.out.println(s+":"+s1 +" : "+ c1.colNo +":"+c1.colDataType ); } } */ int i =0; //System.out.println(tableName); //System.out.println(colName); if(ConfigureVariables.delete) { tableName = tableName.toLowerCase(); // Since not handling any aliases for now for Delete } if(ConfigureVariables.tablecol.containsKey(tableName)) { ArrayList<String> str = ConfigureVariables.tablecol.get(tableName); for ( int a =0; a<str.size();a++) { if((str.get(a)).equals(colName)) { //System.out.println("index"+":"+colName+":"+i); //ConfigureVariables.countcheck = ConfigureVariables.countcheck +1; index = i; break; } i++; } } //System.out.println("INDEX:"+index); //System.out.println(tuple[0]); //System.out.println("evaluator"+index); return tuple[index]; } else { String col = c.toString(); //System.out.println(col); for(int i =0; i<ConfigureVariables.afterjoincol.size();i++) { if(col.equals(ConfigureVariables.afterjoincol.get(i))) { //System.out.println(i); /* if(col.equalsIgnoreCase("LINEITEM.EXTENDEDPRICE")) { System.out.println("LINEITEM.EXTENDEDPRICE::"+ i); } if(col.equalsIgnoreCase("LINEITEM.DISCOUNT")) { System.out.println("LINEITEM.DISCOUNT::"+i); }*/ return tuple[i]; } } } return null; } }
package com.packt.jdeveloper.cookbook.hr.components.model.application.common; import oracle.jbo.ApplicationModule; import oracle.jbo.domain.Number; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Mon Nov 03 18:21:32 EST 2014 // --------------------------------------------------------------------- public interface HrComponentsAppModule extends ApplicationModule { void adjustCommission(Number commissionPctAdjustment); void refreshEmployees(); void removeEmployeeFromCollection(); }
package com.yang.springboot.config; import com.yang.springboot.Filter.Myfilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; @Configuration public class mvcConfiguration extends WebMvcConfigurationSupport { // @Bean // public FilterRegistrationBean filterRegistrationBean() // { // FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean(); // filterRegistrationBean.setFilter(new Myfilter()); // filterRegistrationBean.setUrlPatterns(Arrays.asList("/*","/jsp/login.jsp")); // return filterRegistrationBean; // } @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addRedirectViewController("/","jsp/login.jsp"); } // @Override // protected void addResourceHandlers(ResourceHandlerRegistry registry) { // super.addResourceHandlers(registry); // } @Bean public LocaleResolver localeResolver(){ return new loacleResolver(); } @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptor(){ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(request.getRequestURI()); if(request.getRequestURI().equals("/controller/hello")) { System.out.println("拦截器生效"); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { if(request.getRequestURI().equals("/controller/hello")) { System.out.println("拦截后面的"); } } }).addPathPatterns().excludePathPatterns();//配置拦截路径和不拦截路径 } }
package com.api.model; public class ChiTietDonHangModel2 { private int id; private String Name; private int Price; private String Image; private int SoLuong ; private int ThanhTien ; public ChiTietDonHangModel2() { super(); // TODO Auto-generated constructor stub } public ChiTietDonHangModel2(int id, String name, int price, String image, int soLuong, int thanhTien) { super(); this.id = id; Name = name; Price = price; Image = image; SoLuong = soLuong; ThanhTien = thanhTien; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getPrice() { return Price; } public void setPrice(int price) { Price = price; } public String getImage() { return Image; } public void setImage(String image) { Image = image; } public int getSoLuong() { return SoLuong; } public void setSoLuong(int soLuong) { SoLuong = soLuong; } public int getThanhTien() { return ThanhTien; } public void setThanhTien(int thanhTien) { ThanhTien = thanhTien; } }
package com.example.demo.battery; public interface RechargeableBattery extends Battery{ public void printBatteryStatus(); }
package common.util.web; import java.text.DateFormat; import java.util.Date; import javax.xml.bind.annotation.adapters.XmlAdapter; public class XDateAdapter extends XmlAdapter<String, Date>{ private static final DateFormat sdf = common.util.DateUtil.getDateFormat("yyyy-MM-dd"); @Override public String marshal(Date arg0) throws Exception { return sdf.format(arg0); } @Override public Date unmarshal(String arg0) throws Exception { return sdf.parse(arg0); } }
package com.example.realsense_native_example; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.intel.realsense.librealsense.DeviceListener; import com.intel.realsense.librealsense.RsContext; public class MainActivity extends AppCompatActivity { private static final int MY_PERMISSIONS_REQUEST_CAMERA = 0; private RsContext mRsContext; // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //RsContext.init must be called once in the application's lifetime before any interaction with physical RealSense devices. //For multi activities applications use the application context instead of the activity context RsContext.init(getApplicationContext()); printMessage(); //Register to notifications regarding RealSense devices attach/detach events via the DeviceListener. mRsContext = new RsContext(); mRsContext.setDevicesChangedCallback(new DeviceListener() { @Override public void onDeviceAttach() { printMessage(); } @Override public void onDeviceDetach() { printMessage(); } }); // Android 9 also requires camera permissions if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.O && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } } private void printMessage(){ // Example of a call to native methods int cameraCount = nGetCamerasCountFromJNI(); final String version = nGetLibrealsenseVersionFromJNI(); final String cameraCountString; if(cameraCount == 0) cameraCountString = "No cameras are currently connected."; else cameraCountString = "Camera is connected"; runOnUiThread(new Runnable() { @Override public void run() { TextView tv = (TextView) findViewById(R.id.sample_text); tv.setText("This app use librealsense: " + version + "\n" + cameraCountString); } }); } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ private static native String nGetLibrealsenseVersionFromJNI(); private static native int nGetCamerasCountFromJNI(); }
package de.varylab.discreteconformal.unwrapper.quasiisothermic; import static java.lang.Math.PI; import static java.lang.Math.cos; import static java.lang.Math.sin; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Set; import de.jreality.math.Rn; import de.jtem.halfedge.Edge; import de.jtem.halfedge.Face; import de.jtem.halfedge.HalfEdgeDataStructure; import de.jtem.halfedge.Vertex; import de.jtem.halfedgetools.adapter.AdapterSet; import de.jtem.halfedgetools.adapter.type.TexturePosition; import de.jtem.halfedgetools.adapter.type.generic.TexturePosition4d; public class QuasiisothermicLayout { private static double INITIAL_LENGTH = 1E-1; /** * Calculates the layout of a mesh from given edge angles * @param hds * @param angleMap * @param orientationMap TODO * @param a */ public static < V extends Vertex<V, E, F>, E extends Edge<V, E, F>, F extends Face<V, E, F>, HDS extends HalfEdgeDataStructure<V, E, F> > void doTexLayout(HDS hds, Map<E, Double> angleMap, Map<F, Double> orientationMap, AdapterSet aSet) { Map<E, Double> lengthMap = new HashMap<E, Double>(); Set<V> visited = new HashSet<V>(hds.numVertices()); Queue<V> Qv = new LinkedList<V>(); Queue<E> Qe = new LinkedList<E>(); Queue<Double> Qa = new LinkedList<Double>(); // start at boundary edge if there is one E e0 = hds.getEdge(0); E e1 = e0.getOppositeEdge(); Double e0a = angleMap.get(e0); V v1 = e0.getStartVertex(); V v2 = e0.getTargetVertex(); // queued data Qv.offer(v1); Qv.offer(v2); Qe.offer(e1); Qe.offer(e0); Qa.offer(e0a + PI); Qa.offer(e0a); // vertices double l = INITIAL_LENGTH; lengthMap.put(e0, l); lengthMap.put(e1, l); aSet.set(TexturePosition.class, v1, new double[] {-cos(e0a)*INITIAL_LENGTH/2, -sin(e0a)*INITIAL_LENGTH/2, 0, 1}); aSet.set(TexturePosition.class, v2, new double[] {cos(e0a)*INITIAL_LENGTH/2, sin(e0a)*INITIAL_LENGTH/2, 0, 1}); visited.add(v1); visited.add(v2); while (!Qv.isEmpty() && hds.numVertices() > visited.size()) { V v = Qv.poll(); E inE = Qe.poll(); Double a = Qa.poll(); E outE = inE.getOppositeEdge(); double[] tp = aSet.getD(TexturePosition4d.class, v); E e = inE.getNextEdge(); Double globalAngle = a + PI; while (e != outE) { V nearVertex = e.getTargetVertex(); E next = e.getNextEdge(); if (e.getLeftFace() == null) { // a boundary edge //TODO do layout in the other direction too break; // alpha = 2*PI - calculateAngleSum(v, angleMap); } double alpha = QuasiisothermicUtility.getOppositeBeta(next, angleMap); alpha *= orientationMap.get(next.getLeftFace()); globalAngle -= alpha; if (!lengthMap.containsKey(e)) { double prevLength = lengthMap.get(e.getPreviousEdge()); l = QuasiisothermicUtility.getEdgeLength(e, prevLength, angleMap); lengthMap.put(e, l); lengthMap.put(e.getOppositeEdge(), l); } if (!visited.contains(nearVertex)) { visited.add(nearVertex); Qv.offer(nearVertex); Qe.offer(e); Qa.offer(globalAngle); double[] dif = {cos(globalAngle), sin(globalAngle), 0.0, 1.0}; Rn.times(dif, l, dif); double[] t = Rn.add(null, tp, dif); t[3] = 1.0; aSet.set(TexturePosition.class, nearVertex, t); } e = e.getOppositeEdge().getNextEdge(); } } // assert (visited.size() == hds.numVertices()); } public static void setInitialLength(double l) { INITIAL_LENGTH = l; } }
package ut.ee.pank.var4; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class TestKontod { public static void main(String[] args) { Konto konto1 = new TavalineKonto("Mari", 1234, 40.0); Konto konto2 = new HoiusKonto("Jüri", 3452, 90, 33); Konto konto3 = new HoiusKonto("Madis", 2463, 40.0, 365); Konto konto4 = new TavalineKonto("Hannes", 1623); List<Konto> kontod = new ArrayList<>(); kontod.add(konto1); kontod.add(konto2); kontod.add(konto3); kontod.add(konto4); // Sorteerime kontod Collections.sort(kontod); prindiKontodeInfo(kontod); } // Meetod mis prindib välja kõik kontod // Vastavalt objekti tüübile kutsutakse välja toString igal objektil private static void prindiKontodeInfo(List<Konto> kontod) { for (Konto konto : kontod) { System.out.println(konto); } } }
package com.bnrc.util.collectwifi; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.baidu.location.BDLocation; import com.baidu.mapapi.model.LatLng; import com.bnrc.busapp.R; import com.bnrc.util.DataBaseHelper; import com.bnrc.util.LocationUtil; import com.umeng.analytics.MobclickAgent; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; public class MyDialogSelectBuslineActivity extends Activity { private EditText edt_input; private ImageView iv_delete; private Button btn_switch; private GridView gv_buslines; private List<Map<String, String>> mNearBuslineList;// 公交列表适配数据 private MySelectBuslineGridAdapter mGridAdapter = null; // private BeijingDBHelper mBeijingDBHelperInstance; private DataBaseHelper mDataBaseHelper = null; private CollectWifiDBHelper mCollectWifiDBHelperInstance = null; private LocationUtil mLocationUtilInstance = null; private BDLocation mBDLocation = null; private boolean IsWhole = false; private String sureMac = ""; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.setContentView(R.layout.dialog_selectbusline); System.out.println("onCreate"); Intent intent = getIntent(); sureMac = intent.getStringExtra("sureMac"); edt_input = (EditText) findViewById(R.id.edt_selectbusline_input); iv_delete = (ImageView) findViewById(R.id.iv_selectbusline_delete); btn_switch = (Button) findViewById(R.id.btn_selectbusline_search); gv_buslines = (GridView) findViewById(R.id.gv_selectbusline_buslinetable); mDataBaseHelper = DataBaseHelper.getInstance(getApplicationContext()); mCollectWifiDBHelperInstance = CollectWifiDBHelper .getInstance(getApplicationContext()); mLocationUtilInstance = LocationUtil .getInstance(getApplicationContext()); mBDLocation = mLocationUtilInstance.mLocation; mNearBuslineList = new ArrayList<Map<String, String>>(); mGridAdapter = new MySelectBuslineGridAdapter( MyDialogSelectBuslineActivity.this, mNearBuslineList); gv_buslines.setAdapter(mGridAdapter); btn_switch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { // TODO Auto-generated method stub if (IsWhole) { btn_switch.setText("全部公交"); IsWhole = false; } else { btn_switch.setText("附近公交"); IsWhole = true; } } }); iv_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub edt_input.setText(""); } }); edt_input.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(final Editable s) { String contentStr = s.toString().trim(); if (contentStr == null || contentStr.length() <= 0)// 判断contentStr是否为空,判断字符串是否为空典型写法 { Log.i("AUTO", "afterTextChanged null"); if (!IsWhole) { mNearBuslineList.clear(); LatLng myPoint = new LatLng(mBDLocation.getLatitude(), mBDLocation.getLongitude()); ArrayList<Map<String, String>> listData = mDataBaseHelper .getNearBusInfo(myPoint); for (Map<String, String> map : listData) { mNearBuslineList.add(map); } // gridAdapter.notifyDataSetChanged(); Log.i("TEXTCHANGE", "空+附近"); for (Map<String, String> map : mNearBuslineList) Log.i("TEXTCHANGE", map.get("线路") + "\n"); } else { mNearBuslineList.clear(); // gridAdapter.notifyDataSetChanged(); Log.i("TEXTCHANGE", "空+全局"); } } else { Log.i("AUTO", "afterTextChanged not null"); Cursor cursor = mDataBaseHelper .FindBusByKeyname(contentStr); if (IsWhole) { mNearBuslineList.clear(); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put("线路", cursor.getString(cursor .getColumnIndex("NAME"))); map.put("方向", cursor.getString(cursor .getColumnIndex("S_END"))); mNearBuslineList.add(map); } } else { mNearBuslineList.clear(); Pattern p = Pattern.compile("^[\u4e00-\u9fa5]*" + contentStr + "(.*)\\S{0,}"); LatLng myPoint = new LatLng(mBDLocation.getLatitude(), mBDLocation.getLongitude()); ArrayList<Map<String, String>> listData = mDataBaseHelper .getNearBusInfo(myPoint); for (Map<String, String> map : listData) { Matcher m = p.matcher(map.get("线路")); if (m.find()) { mNearBuslineList.add(map); } } } } mGridAdapter.notifyDataSetChanged(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // sure.setEnabled(false);// TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); gv_buslines.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Map<String, String> sureData = new HashMap<String, String>(); String[] wifiInfo = sureMac.split(";"); sureData.put("线路", mNearBuslineList.get(arg2).get("线路")); sureData.put("SSID", wifiInfo[1]); sureData.put("MAC", wifiInfo[0]); mCollectWifiDBHelperInstance.InsertSureData(sureData); NotifyAdmin.IsShow = false; InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); MyDialogSelectBuslineActivity.this.finish(); } }); loadBuslineInfo(); } private void loadBuslineInfo() { mNearBuslineList.clear(); LatLng myPoint = new LatLng(mBDLocation.getLatitude(), mBDLocation.getLongitude()); ArrayList<Map<String, String>> listData = mDataBaseHelper .getNearBusInfo(myPoint); for (Map<String, String> map : listData) { mNearBuslineList.add(map); } Log.i("CURSOR", mNearBuslineList.toString()); mGridAdapter.notifyDataSetChanged(); Toast.makeText(MyDialogSelectBuslineActivity.this, "系统确定到您正在乘坐公交车,请选择所乘坐的线路!!!!", 1000).show(); if (mNearBuslineList.size() != 0) { IsWhole = false; btn_switch.setEnabled(true); btn_switch.setText("所有公交"); } else IsWhole = true; } public void onResume() { super.onResume(); System.out.println("onResume"); MobclickAgent.onResume(this); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); System.out.println("onRestart"); } public void onStart() { super.onStart(); System.out.println("onStart"); } public void onStop() { super.onStop(); System.out.println("onStop"); } public void onPause() { super.onPause(); System.out.println("onPause"); } public void onDestroy() { super.onDestroy(); System.out.println("onDestroy"); NotifyAdmin.IsShow = false; } }
package com.iwanghang.flycotablayoutbywh; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void v1click(View view) { Intent intent = new Intent(view.getContext(), MainActivityV1.class); startActivity(intent); } public void v2click(View view) { Intent intent = new Intent(view.getContext(), MainActivityV2.class); startActivity(intent); } }
/** * Created by C0116289 on 2017/04/17. */ public class Student { String name; int score; }
import items.Tuner; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TunerTest { private Tuner tuner; @Before public void setUp() { tuner = new Tuner("Guitar", "electronic", 12.00, 7.00); } @Test public void hasInstrumentFor() { assertEquals("Guitar", tuner.getInstrumentFor()); } @Test public void hasType() { assertEquals("electronic", tuner.getType()); } @Test public void hasSellingPrice() { assertEquals(12.00, tuner.getSellingPrice(), 0.01); } @Test public void hasBuyingPrice() { assertEquals(7.00, tuner.getBuyingPrice(), 0.01); } }
package it.unical.dimes.processmining.bk; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.StandardOpenOption; /** * @author frank * * Created on 2013-08-01, 3:59:14 PM */ public class ExtractorManager { public void extractConstraints(WorkflowConstraintExtractor constrExtractor, int P_perc, int E_perc, int NP_perc, int NE_perc, int i) throws IOException { //"ExtractedConstraints.xml" File file = new File("Constraints_P_"+P_perc+"_E_"+E_perc+"_NP_"+NP_perc+"_NE_"+NE_perc+"_Run_"+i+".xml"); if (file.exists()) file.delete(); try { file.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } constrExtractor.setP_perc(P_perc); constrExtractor.setE_perc(E_perc); constrExtractor.setNP_perc(NP_perc); constrExtractor.setNE_perc(NE_perc); constrExtractor.extractConstraints(); String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Constraint_Set process_ID=\"idProcesso\"\n" + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "xsi:noNamespaceSchemaLocation=\"ConstraintSchema.xsd\">\n"; DependencySet sampled_trueDeps = constrExtractor.getSampled_trueDeps(); DependencySet sampled_negTrueDeps = constrExtractor.getSampled_negTrueDeps(); DependencySet sampled_truePathDeps = constrExtractor.getSampled_truePathDeps(); DependencySet sampled_negTruePathDeps = constrExtractor.getSampled_negTruePathDeps(); for(Dependency d : sampled_trueDeps) { content += "<Constraint type=\"Edge\">\n" +"<Head>"+d.getTo()+"</Head>\n" +"<Body>"+d.getFrom()+"</Body>\n" +"</Constraint>\n"; } for(Dependency d : sampled_truePathDeps) { content += "<Constraint type=\"Path\">\n" +"<Head>"+d.getTo()+"</Head>\n" +"<Body>"+d.getFrom()+"</Body>\n" +"</Constraint>\n"; } for(Dependency d : sampled_negTrueDeps) { content += "<Constraint type=\"notEdge\">\n" +"<Head>"+d.getTo()+"</Head>\n" +"<Body>"+d.getFrom()+"</Body>\n" +"</Constraint>\n"; } for(Dependency d : sampled_negTruePathDeps) { content += "<Constraint type=\"notPath\">\n" +"<Head>"+d.getTo()+"</Head>\n" +"<Body>"+d.getFrom()+"</Body>\n" +"</Constraint>\n"; } content += "</Constraint_Set>"; try { Files.write(FileSystems.getDefault().getPath(".", "Constraints_P_"+P_perc+"_E_"+E_perc+"_NP_"+NP_perc+"_NE_"+NE_perc+"_Run_"+i+".xml"), content.getBytes(), StandardOpenOption.APPEND); } catch (IOException ioe) { ioe.printStackTrace(); } } }
package net.darktrojan.smsecho; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; class SocketThread extends Thread { private static final String LOG_TAG = "SocketThread"; private Handler eventHandler; private ServerSocket serverSocket; private EventSource currentEventSource = null; private boolean keepListening; public SocketThread(Handler handler) { eventHandler = handler; } @Override public void run() { try { serverSocket = new ServerSocket(6900); Log.d(LOG_TAG, "Server opened."); } catch (IOException ex) { Log.e(LOG_TAG, "Failed to open server.", ex); return; } keepListening = true; listen(); } private void listen() { try { Socket clientSocket = serverSocket.accept(); Log.d(LOG_TAG, "Connection successful."); BufferedInputStream input = new BufferedInputStream(clientSocket.getInputStream()); // Adjust this if the total request size is likely to be bigger. byte[] buffer = new byte[4096]; int count = input.read(buffer); String request = new String(buffer, 0, count); String[] parts = request.split("\r\n\r\n", 2); String[] headers = parts[0].split("\r\n"); String requestLine = headers[0]; if (requestLine == null) { Log.d(LOG_TAG, "No request, wtf, socket: " + clientSocket.toString()); } else if (requestLine.equals("GET / HTTP/1.1")) { if (currentEventSource != null) { currentEventSource.close(); } currentEventSource = new EventSource(clientSocket); } else if (requestLine.equals("POST /send HTTP/1.1")) { Bundle bundle = new Bundle(); bundle.putStringArray("headers", headers); if (parts.length == 2) { bundle.putString("body", parts[1]); } Message message = eventHandler.obtainMessage(); message.setData(bundle); eventHandler.sendMessage(message); PrintWriter output = new PrintWriter(clientSocket.getOutputStream(), true); output.print("HTTP/1.1 206 No Content\r\n" + "Connection: close\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Access-Control-Allow-Methods: GET,POST\r\n" + "Access-Control-Allow-Headers: Content-Type\r\n" + "\r\n"); output.flush(); output.close(); clientSocket.close(); } else { Log.d(LOG_TAG, "Unknown request: " + requestLine); } } catch (IOException ex) { if (!ex.getMessage().equals("Socket closed")) { Log.e(LOG_TAG, "Failed to open server.", ex); } } if (keepListening) { listen(); } } public void sendMessage(String eventType, String eventData) { if (currentEventSource == null) { Log.d(LOG_TAG, "no currentEventSource"); } else { currentEventSource.sendMessage(eventType, eventData); } } public void close() { keepListening = false; try { if (currentEventSource != null) { currentEventSource.close(); } if (serverSocket != null && !serverSocket.isClosed()) { serverSocket.close(); } Log.d(LOG_TAG, "Server closed."); } catch (IOException ex) { Log.d(LOG_TAG, "Failed to close server.", ex); } } private class EventSource { Socket clientSocket; PrintWriter output; public EventSource(Socket socket) { clientSocket = socket; try { output = new PrintWriter(clientSocket.getOutputStream(), true); output.print("HTTP/1.1 200 OK\r\n"); output.print("Content-Type: text/event-stream\r\n"); output.print("Transfer-Encoding: identity\r\n"); output.print("Connection: keep-alive\r\n"); output.print("Access-Control-Allow-Origin: *\r\n"); output.print("Access-Control-Allow-Methods: GET\r\n"); output.print("Access-Control-Allow-Headers: Content-Type\r\n"); output.print("\r\n"); output.flush(); } catch (IOException ex) { if (!ex.getMessage().equals("Socket closed")) { Log.e(LOG_TAG, "Failed to open server.", ex); } } } public void sendMessage(String eventType, String eventData) { Log.v(LOG_TAG, "Sending " + eventType + " message"); if (serverSocket == null || serverSocket.isClosed() || output == null) { Log.e(LOG_TAG, "Connection not open."); return; } if (clientSocket.isClosed()) { Log.e(LOG_TAG, "Client closed connection."); output = null; this.close(); return; } output.write("event: " + eventType + "\n"); output.write("data: " + eventData + "\n"); output.write("\n"); output.flush(); } public void close() { try { if (output != null) { sendMessage("close", ""); output.close(); } if (clientSocket != null) { clientSocket.close(); } currentEventSource = null; } catch (IOException ex) { Log.d(LOG_TAG, "Failed to close server.", ex); } } } }
package com.corycharlton.bittrexapi.model; import com.google.gson.annotations.SerializedName; import java.util.Date; @SuppressWarnings("unused") public class Deposit { @SerializedName("Amount") private double _amount; @SerializedName("Confirmations") private long _confirmations; @SerializedName("CryptoAddress") private String _cryptoAddress; @SerializedName("Currency") private String _currency; @SerializedName("Id") private long _id; @SerializedName("LastUpdated") private Date _lastUpdated; @SerializedName("TxId") private String _txId; private Deposit() {} // Cannot be instantiated public double amount() { return _amount; } public long confirmations() { return _confirmations; } public String cryptoAddress() { return _cryptoAddress; } public String currency() { return _currency; } public long id() { return _id; } public Date lastUpdated() { return _lastUpdated; } public String txId() { return _txId; } }
// ********************************************************** // 1. 제 목: 교육그룹대상회사 DATA // 2. 프로그램명: GrcompData.java // 3. 개 요: // 4. 환 경: JDK 1.3 // 5. 버 젼: 0.1 // 6. 작 성: LeeSuMin 2003. 07. 21 // 7. 수 정: // // ********************************************************** package com.ziaan.course; public class GrcompData { private String grcode ; private String comp ; private String indate ; private String luserid ; private String ldate ; private String compnm ; private String groupsnm ; private String companynm ; private String gpmnm ; private String deptnm ; private String partnm ; private String groups ; private String company ; private String gpm ; private String dept ; private String part ; private int comptype ; public GrcompData() { }; /** * @return */ public String getComp() { return comp; } /** * @return */ public String getGrcode() { return grcode; } /** * @return */ public String getIndate() { return indate; } /** * @return */ public String getLdate() { return ldate; } /** * @return */ public String getLuserid() { return luserid; } /** * @param string */ public void setComp(String string) { comp = string; } /** * @param string */ public void setGrcode(String string) { grcode = string; } /** * @param string */ public void setIndate(String string) { indate = string; } /** * @param string */ public void setLdate(String string) { ldate = string; } /** * @param string */ public void setLuserid(String string) { luserid = string; } /** * @return */ public String getCompany() { return company; } /** * @return */ public String getCompanynm() { return companynm; } /** * @return */ public String getCompnm() { return compnm; } /** * @return */ public int getComptype() { return comptype; } /** * @return */ public String getDept() { return dept; } /** * @return */ public String getDeptnm() { return deptnm; } /** * @return */ public String getGpm() { return gpm; } /** * @return */ public String getGpmnm() { return gpmnm; } /** * @return */ public String getGroups() { return groups; } /** * @return */ public String getGroupsnm() { return groupsnm; } /** * @return */ public String getPart() { return part; } /** * @return */ public String getPartnm() { return partnm; } /** * @param string */ public void setCompany(String string) { company = string; } /** * @param string */ public void setCompanynm(String string) { companynm = string; } /** * @param string */ public void setCompnm(String string) { compnm = string; } /** * @param i */ public void setComptype(int i) { comptype = i; } /** * @param string */ public void setDept(String string) { dept = string; } /** * @param string */ public void setDeptnm(String string) { deptnm = string; } /** * @param string */ public void setGpm(String string) { gpm = string; } /** * @param string */ public void setGpmnm(String string) { gpmnm = string; } /** * @param string */ public void setGroups(String string) { groups = string; } /** * @param string */ public void setGroupsnm(String string) { groupsnm = string; } /** * @param string */ public void setPart(String string) { part = string; } /** * @param string */ public void setPartnm(String string) { partnm = string; } }
package com.amikom.two.jadwal; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.amikom.two.R; import com.amikom.two.model.Tugas; import com.amikom.two.room.TugasDatabase; import com.amikom.two.room.TugasRoom; @SuppressLint("Registered") public class TambahTugasActivity extends AppCompatActivity implements View.OnClickListener { EditText edtMatakuliah; EditText edtJenistugas; EditText edtKeterangan; EditText edtTanggalPengumpulan; EditText edtJamPengumpulan; Button btnTambah; Button btnHapus; TugasRoom tugasRoom; int id; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tambah_tugas); edtMatakuliah = findViewById(R.id.list_matakuliah); edtJenistugas = findViewById(R.id.list_jenistugas); edtKeterangan = findViewById(R.id.list_keterangan); edtTanggalPengumpulan = findViewById(R.id.list_tglkumpul); edtJamPengumpulan = findViewById(R.id.list_jamkumpul); btnTambah = findViewById(R.id.tugas_tambah); btnTambah.setOnClickListener(this); btnHapus = findViewById(R.id.tugas_hapus); tugasRoom = TugasDatabase.db(this).tugasRoom(); id = getIntent().getIntExtra("id", 0); if (id != 0) { Tugas tugas = tugasRoom.select(id); edtMatakuliah.setText(tugas.getMatakuliah()); edtJenistugas.setText(tugas.getJenistugas()); edtKeterangan.setText(tugas.getKeterangan()); edtTanggalPengumpulan.setText(tugas.getTanggalpengumpulan()); edtJamPengumpulan.setText(tugas.getJampengumpulan()); btnTambah.setText("Update Tugas"); btnHapus.setVisibility(View.VISIBLE); btnHapus.setOnClickListener(v -> { Tugas tugas1 = tugasRoom.select(id); tugasRoom.delete(tugas1); Intent result = new Intent(); setResult(Activity.RESULT_OK, result); finish(); }); } } @Override public void onClick(View v) { Intent result = new Intent(); Tugas tugas = new Tugas("","","","",""); if (id != 0) { tugas = tugasRoom.select(id); } tugas.setMatakuliah(edtMatakuliah.getText().toString()); tugas.setJenistugas(edtJenistugas.getText().toString()); tugas.setKeterangan(edtKeterangan.getText().toString()); tugas.setTanggalpengumpulan(edtTanggalPengumpulan.getText().toString()); tugas.setJampengumpulan(edtJamPengumpulan.getText().toString()); if (id != 0) { tugasRoom.update(tugas); } else { tugasRoom.insert(tugas); } setResult(Activity.RESULT_OK, result); finish(); } }
package nl.kolkos.photoGallery; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; import nl.kolkos.photoGallery.dto.PhotoGalleryRegistrationDto; import nl.kolkos.photoGallery.dto.UserRegistrationDto; import nl.kolkos.photoGallery.entities.PhotoGalleryACL; import nl.kolkos.photoGallery.entities.User; import nl.kolkos.photoGallery.properties.FileStorageProperties; import nl.kolkos.photoGallery.services.PhotoGalleryACLService; import nl.kolkos.photoGallery.services.PhotoGalleryService; import nl.kolkos.photoGallery.services.PhotoService; import nl.kolkos.photoGallery.services.UserService; @SpringBootApplication @EnableAsync @EnableConfigurationProperties({ FileStorageProperties.class }) public class PhotoGalleryApplication { private static final Logger logger = LoggerFactory.getLogger(PhotoGalleryApplication.class); public static void main(String[] args) { SpringApplication.run(PhotoGalleryApplication.class, args); } private static String ADMIN_USER = "admin@localhost"; private static String MAIL_USER = "test@user.com"; private static String MAIL_USER2 = "another@user.com"; @Bean public CommandLineRunner createAdministrator(UserService userService) { return (args) -> { logger.debug("Creating Administrator"); UserRegistrationDto admin = new UserRegistrationDto(); admin.setEmail(ADMIN_USER); admin.setConfirmEmail(ADMIN_USER); admin.setFirstName("Administrator"); admin.setLastName("User"); admin.setPassword("admin"); admin.setConfirmPassword("admin"); admin.setTerms(true); userService.save(admin); logger.debug("Administrator created"); }; } @Bean public CommandLineRunner createAdditionalUsers(UserService userService) { return (args) -> { logger.debug("Creating demo users"); UserRegistrationDto user = new UserRegistrationDto(); user.setEmail(MAIL_USER); user.setConfirmEmail(MAIL_USER); user.setFirstName("Test"); user.setLastName("User"); user.setPassword("test123"); user.setConfirmPassword("test123"); user.setTerms(true); userService.save(user); UserRegistrationDto anotherUser = new UserRegistrationDto(); anotherUser.setEmail(MAIL_USER2); anotherUser.setConfirmEmail(MAIL_USER2); anotherUser.setFirstName("Another"); anotherUser.setLastName("User"); anotherUser.setPassword("test123"); anotherUser.setConfirmPassword("test123"); anotherUser.setTerms(true); userService.save(anotherUser); logger.debug("Demo users created"); }; } @Bean public CommandLineRunner createGalleries(PhotoGalleryService photoGalleryService, UserService userService) { return (args) -> { User testUser = userService.findByEmail(MAIL_USER); User adminUser = userService.findByEmail(ADMIN_USER); PhotoGalleryRegistrationDto photoGalleryRegistrationDto1 = new PhotoGalleryRegistrationDto(); photoGalleryRegistrationDto1.setName("Test album #1"); photoGalleryRegistrationDto1.setDescription("Another gallery created from a @bean"); PhotoGalleryRegistrationDto photoGalleryRegistrationDto2 = new PhotoGalleryRegistrationDto(); photoGalleryRegistrationDto2.setName("Test album #2"); photoGalleryRegistrationDto2.setDescription("Another gallery created from a @bean"); photoGalleryService.save(photoGalleryRegistrationDto1, testUser); photoGalleryService.save(photoGalleryRegistrationDto2, adminUser); }; } @Bean public CommandLineRunner getGalleriesForUser(PhotoGalleryService photoGalleryService, UserService userService, PhotoGalleryACLService photoGalleryACLService) { return (args) -> { User testUser = userService.findByEmail(MAIL_USER); User adminUser = userService.findByEmail(ADMIN_USER); List<PhotoGalleryACL> aclsAdminUser = photoGalleryACLService.findAclsForUser(adminUser); // for(PhotoGalleryACL acl : aclsAdminUser) { // PhotoGallery gallery = acl.getPhotoGallery(); // // // create a new acl // PhotoGalleryACL aclForTestUser = new PhotoGalleryACL(); // aclForTestUser.setUser(testUser); // aclForTestUser.setPhotoGallery(gallery); //// aclForTestUser.setReadPermission(true); //// aclForTestUser.setUpdatePermission(false); // // photoGalleryACLService.save(aclForTestUser); // } List<PhotoGalleryACL> aclsTestUser = photoGalleryACLService.findAclsForUser(testUser); for(PhotoGalleryACL acl : aclsTestUser) { logger.debug("{}", acl.toString()); } PhotoGalleryACL defaultAcl = photoGalleryACLService.findDefaultGalleryForUser(testUser); logger.debug("DEFAULT: {}", defaultAcl.toString()); }; } @Bean public CommandLineRunner cleaner(PhotoService photoService) { return (args) -> { photoService.uploadsCleaner(); }; } }
package july21; import java.text.SimpleDateFormat; import java.util.Date; public class ConstellationByShine { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String[] consteList={"白羊座","金牛座","双子座","巨蟹座","狮子座","处女座", "天秤座","天蝎座","射手座","摩羯座","水瓶座","双鱼座"}; String[] adviceList={"和朋友去吃饭!","约个会吧!","睡觉睡到自然醒!", "不要对着电脑发呆!","去吃巧克力!","和家人聊天!", "勇敢去表白吧!","学习该努力啦!","多喝水!", "多睡觉!","准时吃饭!","玩会儿游戏吧!"}; Date date=new Date(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); String datestr=format.format(date); System.out.println("时间:"+ datestr); System.out.println("-----------------星 座 运 势------------------"); for(int i=0;i<consteList.length;i++){ System.out.println(consteList[i] + " " + "运势: " + starOut()+ " \t" + "建议: " + adviceList[(int)(Math.random()*adviceList.length)] ); } } private static String starOut(){ int num=(int)(Math.random()*5+1); String star=""; for(int i=0;i<num;i++){ star+="★"; } return star; } }
package com.joaosakai.easybillings.api; import com.joaosakai.easybillings.service.RegistrationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author joao.sakai * */ @RestController @RequestMapping("/api") public class RegistrationAPI { @Autowired private RegistrationService registrationService; }
package entity; import java.sql.Date; public class Esame { private int id_esame; private String tipo; private Date date1; private Date date2; private Date date3; private int fk_id_corso; /** * @return the id_corso */ public Esame() { super(); // TODO Auto-generated constructor stub } /** * @return the fk_id_corso */ public int getFk_id_corso() { return fk_id_corso; } /** * @param fk_id_corso the fk_id_corso to set */ public void setFk_id_corso(int fk_id_corso) { this.fk_id_corso = fk_id_corso; } /** * @return the id_esame */ public int getId_esame() { return id_esame; } /** * @param id_esame the id_esame to set */ public void setId_esame(int id_esame) { this.id_esame = id_esame; } /** * @return the tipo */ public String getTipo() { return tipo; } /** * @param tipo the tipo to set */ public void setTipo(String tipo) { this.tipo = tipo; } /** * @return the date1 */ public Date getDate1() { return date1; } /** * @param date1 the date1 to set */ public void setDate1(Date date1) { this.date1 = date1; } /** * @return the date2 */ public Date getDate2() { return date2; } /** * @param date2 the date2 to set */ public void setDate2(Date date2) { this.date2 = date2; } /** * @return the date3 */ public Date getDate3() { return date3; } /** * @param date3 the date3 to set */ public void setDate3(Date date3) { this.date3 = date3; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Esame : [id_esame=" + id_esame + ", tipo=" + tipo + ", date1=" + date1 + ", date2=" + date2 + ", date3=" + date3 + ", fk_id_corso=" + fk_id_corso + "]\n"; } }
package com.git.cloud.cloudservice.dao; import java.sql.SQLException; import java.util.List; import com.git.cloud.cloudservice.model.po.CloudServiceAttrPo; import com.git.cloud.cloudservice.model.vo.CloudServiceAttrVo; import com.git.cloud.cloudservice.model.vo.QueryDataVo; import com.git.cloud.common.dao.ICommonDAO; import com.git.cloud.common.exception.RollbackableBizException; import com.git.cloud.common.support.Pagination; import com.git.cloud.common.support.PaginationParam; public interface ICloudServiceAttrDao extends ICommonDAO { public CloudServiceAttrPo save(CloudServiceAttrPo cloudServiceAttrPo) throws RollbackableBizException; public void update(CloudServiceAttrPo cloudServiceAttrPo) throws RollbackableBizException; public CloudServiceAttrPo findById(String id) throws RollbackableBizException; public Pagination<CloudServiceAttrPo> queryPagination(PaginationParam pagination); public void deleteById(String[] ids) throws RollbackableBizException; public Integer findCloudServiceAttrCount(CloudServiceAttrPo cloudServiceAttrPo) throws RollbackableBizException ; List<QueryDataVo> queryDynamicSQL(String listSql) throws SQLException; public String queryListSql(String listSqlId) throws SQLException; public List<CloudServiceAttrPo> cloudLeading(String serviceId) throws RollbackableBizException; }
package com.company.utils; import java.net.Socket; import java.util.ArrayList; import java.util.List; /** * @author WEN */ public class ConstantUtil { public static List<Socket> socketList = new ArrayList<>(); public static final int LOGIN_PORT = 8888; public static final int CHAT_PORT = 6666; public static final int LOGIN_LIMIT = 2; public static final String ADDRESS = "192.168.43.120"; }
/* ASCII Signature: AJM ,. ,. {^ \-"-/ ^} " """ " { <O> _ <O> } ==_ .:Y:. _== ."" `--^--' "". (,~-~."" "" ,~-~.) ------( )----( )----- ^-'-'-^ ^-'-'-^ _____________________________ |"""" /~.^.~\ """"| hjw ,i-i-i(""( i-i-i. `97 (o o o ))"")( o o o) \(_) /(""( \ (_)/ `--' \""\ `--' )"") (""/ `" ******************************************************************************** * Programmer: Amber Murphy * Course: CITP 190: Fall 2013 * Filename: Circle.java * Assignment: Workbook 7-2 * Summary: Calculate a circle's circumference and area. * Circle Class: Class that does the actual calculations and conversions * for the ClassApp application level programme. * Get the Circumference (C), format C into a 2 precision decimal * Get the Area (A), format A into a 2 precision decimal * Use a sub-method to format the number and pass it to the precision methods * Get an Object count for the number of Circle objects created. ******************************************************************************** */ package com.company; import java.text.NumberFormat; public class Circle { private double radius; private double circumference; private double area; private static int objectCount = 0; public Circle() { radius = 0; objectCount++; } public Circle(double radius, double circumference, double area) { this.radius = radius; this.circumference = circumference; this.area = area; } public void setRadius(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setCircumference(double circumference) { this.circumference = circumference; } public void setArea(double area) { this.area = area; } public double getCircumference() { circumference = Math.PI * Math.pow(radius,2); return circumference; } public String getFormattedCircumference() { String numberString = this.formatNumber(circumference); return numberString; } public double getArea() { area = 2 * Math.PI * radius; return area; } public String getFormattedArea() { String numberString = this.formatNumber(area); return numberString; } private String formatNumber(double x) { NumberFormat number = NumberFormat.getInstance(); number.setMaximumFractionDigits(2); String numberString = number.format(x); return numberString; } public static int getObjectCount() { return objectCount; } }
package com.dotech.core.db.util; /** * Clase para manejar mensajes de las clases tipo services */ public class ServiceResponse { private boolean estatus; private String mensaje; public ServiceResponse() { } public ServiceResponse(boolean estatus, String mensaje) { this.estatus = estatus; this.mensaje = mensaje; } public boolean isEstatus() { return estatus; } public void setEstatus(boolean estatus) { this.estatus = estatus; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } }
package cn.quickits.sewing.util; import java.io.File; public class FileUtils { public static String getFileName(File file) { return file.getName().substring(0, file.getName().lastIndexOf(".")); } public static String getFileExtension(File file) { return file.getName().substring(file.getName().lastIndexOf(".") + 1); } }
package interfaceExample; public class TestDiagram { public static void main(String[] args) { // TODO Auto-generated method stub Chicken hen = new Chicken(2,"hen",6,8,false); Dog Boxer = new Dog(35,"Boxer",5,4,false); Animal mypts=new Animal(20,"Boxer",5,4,false); } @Override public String communicate() { // TODO Auto-generated method stub return null; } }; Human h1 = new Human(4,"Moh",9,10,false,); House ho1=new House(9000); House ho2 = new House(8000); House ho3=new House(h1, Ematerial.Brick, 8888888); Human h2 = new Human(20, Boxer, 900000,ho1); Human h3 = new Human(5, Boxer, 696969, ho3); System.out.println(h2); System.out.println(ho2.compareTo(ho1)); } }
package com.ismail.contacts.entity; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the contactphone database table. * */ @Entity @NamedQueries({ @NamedQuery(name = "Contactphone.findAll", query = "SELECT c FROM Contactphone c")}) public class Contactphone implements Serializable { private static final long serialVersionUID = 1L; @Id private int contactphoneid; private String phonenumber; // bi-directional many-to-one association to Contact @ManyToOne @JoinColumn(name = "CONTACTID") private Contact contact; public Contactphone() { } public int getContactphoneid() { return this.contactphoneid; } public void setContactphoneid(int contactphoneid) { this.contactphoneid = contactphoneid; } public String getPhonenumber() { return this.phonenumber; } public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; } public Contact getContact() { return this.contact; } public void setContact(Contact contact) { this.contact = contact; } }
package com.thinkgem.jeesite.modules.sys.security.csrf; import java.sql.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.google.common.collect.Lists; import com.thinkgem.jeesite.common.mapper.JsonMapper; import com.thinkgem.jeesite.common.mapper.ResponseObject; import com.thinkgem.jeesite.common.utils.Collections3; import com.thinkgem.jeesite.common.utils.DateUtils; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.common.web.Servlets; import com.thinkgem.jeesite.modules.sys.utils.SettingsUtils; /** * * @author lsp * */ public class ApiControllInterceptor implements HandlerInterceptor { protected Logger logger = LoggerFactory.getLogger(getClass()); private String errorPage; @Autowired private CSRFTokenService csrfTokenService; /** * 失败跳转页 */ public void setErrorPage(String errorPage) { if (errorPage != null && !errorPage.startsWith("/")) { throw new IllegalArgumentException("errorPage must begin with '/'"); } this.errorPage = errorPage; } public void setCsrfTokenService(CSRFTokenService csrfTokenService) { this.csrfTokenService = csrfTokenService; } //验证和删除token @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; ApiControll apiControll = handlerMethod.getMethodAnnotation(ApiControll.class); if (apiControll == null) { apiControll = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), ApiControll.class); } // 如果加了注解 if (apiControll != null) { if (apiControll.needSetbackToken() && !"OPTIONS".equalsIgnoreCase(request.getMethod())) { String newToken = csrfTokenService.generateToken(getUserId(request)); logger.debug("newToken ------------> {}", newToken); request.setAttribute(csrfTokenService.getCsrfTokenParameterName(), newToken);// 在controller中获取request.getAttribute("Csrf-Token"),在页面中获取 ${requestScope['Csrf-Token']} response.addHeader(csrfTokenService.getCsrfTokenHeaderName(), newToken);// 在controller中获取response.getHeader("Csrf-Token"),在页面中获取 ${pageContext.response.getHeader('Csrf-Token')} } boolean isSupportedMethod = isSupportedMethod(request, apiControll); //logger.debug("isSupportedMethod ---> {} , request.getMethod() ---> {}", isSupportedMethod, request.getMethod()); if (!isSupportedMethod) { return true; } // 检查结果 boolean flag = true; // 检查请求方法 boolean checkExpectedMethods = checkExpectedMethods(request, apiControll.expectedMethods()); logger.debug("checkExpectedMethods ---> {}", checkExpectedMethods); flag = checkExpectedMethods; /* */ // TODO 测试时去掉检查 // 检查HTTP头部 if (flag) { boolean checkExpectedHeaders = checkExpectedHeaders(request, apiControll.expectedHeaders()); logger.debug("checkExpectedHeaders ---> {}", checkExpectedHeaders); //flag = checkExpectedHeaders; } // 检查csrf token if (flag) { if (apiControll.needVerifyToken()) { String requstCSRFToken = csrfTokenService.getRequstCSRFToken(request); logger.debug("提交 requstCSRFToken -----------> {}", requstCSRFToken); String userId = getUserId(request); //logger.debug("userId -----------> {}", userId); flag = csrfTokenService.verifyToken(userId, requstCSRFToken); logger.debug("verifyToken success ? -----------> {}", flag); } } if (!flag) { // response.sendError(403, "CSRF token error !"); if (!response.isCommitted()) { if (Servlets.isAjaxRequest(request)) { ResponseObject responseObject = ResponseObject.failure().msg("禁止访问"); String jsonString = JsonMapper.toJsonString(responseObject); //logger.debug("jsonString------------>{}", jsonString); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(jsonString); response.setStatus(403); } else { if (errorPage != null) { response.setStatus(HttpStatus.FORBIDDEN.value()); RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage); dispatcher.forward(request, response); } else { response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase()); } } } } return flag; } } return true; } private boolean checkExpectedMethods(HttpServletRequest request, RequestMethod[] expectedMethods) { logger.debug("expectedMethods==>{}, request.getMethod()==>{}", StringUtils.join(expectedMethods, ","), request.getMethod()); if (expectedMethods == null || expectedMethods.length < 1) { return true; } return containsMethod(expectedMethods, request.getMethod()); } private boolean containsMethod(RequestMethod[] methods, String method) { if (methods != null && methods.length > 0) { for (RequestMethod requestMethod : methods) { if (requestMethod.name().equalsIgnoreCase(method)) { return true; } } } return false; } /** * 检查HTTP头 */ private boolean checkExpectedHeaders(HttpServletRequest request, String[] expectedHeaders) { if (expectedHeaders == null || expectedHeaders.length < 1) { return true; } // Map<String, String> map = new HashMap<>(); map.put("basePath", Servlets.getBasePath()); // {"a=b","c=","d"} for (String expectedHeader : expectedHeaders) { expectedHeader = StringUtils.trimToEmpty(expectedHeader); if (StringUtils.isBlank(expectedHeader)) { continue; } // a=b String[] items = expectedHeader.split("="); String headerName = items[0]; // a logger.debug("检查headerName ------->> {}", headerName); Enumeration<String> headerValueEnumeration = request.getHeaders(headerName); List<String> headerValueList = headerValueEnumerationToList(headerValueEnumeration); logger.debug("headerName对应值 : {} <------> {}", headerName, StringUtils.join(headerValueList, " , ")); // headerName必须存在 if (Collections3.isEmpty(headerValueList)) { // ajax跨域时,服务器端获取不到http头“X-Requested-With” // TODO 测试的时候不检查 if (isApiTest()) { if ("X-Requested-With".equals(headerName)) { continue; } } logger.warn("headerValueEnumeration 不存在[headerName = {}],X-Requested-With--->{}", headerName, request.getHeader("X-Requested-With")); return false; } // 如果要求提供value,进行比较 if (items.length > 1 && StringUtils.isNotBlank(items[1])) { String definedHeaderValue = items[1]; logger.debug("definedHeaderValue ------->> {}", definedHeaderValue); definedHeaderValue = replaceProperties(definedHeaderValue, map); logger.debug("replaceProperties definedHeaderValue ------->> {}", definedHeaderValue); boolean flag = false; for (String hv : headerValueList) { logger.debug("hv ------->> {}", hv); if (StringUtils.isNotBlank(hv)) { flag = compare(headerName, hv, definedHeaderValue, request); if (flag) { break; } } } if (!flag) { return false; } } } return true; } private List<String> headerValueEnumerationToList(Enumeration<String> headerValueEnumeration) { List<String> list = Lists.newArrayList(); if (headerValueEnumeration == null) { return list; } while (headerValueEnumeration.hasMoreElements()) { list.add(headerValueEnumeration.nextElement()); } return list; } /** * */ private boolean checkRequestedTime(HttpServletRequest request, String headerValue) { logger.debug("requestedTime ----------> {}", headerValue); try { long time = Long.valueOf(headerValue); Date date = new Date(time); logger.debug("date ----------> {}", DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss")); if (System.currentTimeMillis() < time) { return false; } } catch (NumberFormatException e) { return false; } return true; } private boolean compare(String headerName, String headerValue, String definedHeaderValue, HttpServletRequest request) { logger.debug(" headerName ---> {}, headerValue ---> {}, definedHeaderValue ---> {}", headerName, headerValue, definedHeaderValue); boolean localhost = localhost(request); if ("Host".equals(headerName)) { // if (localhost) { return true; } if (!request.getRemoteHost().equals(headerValue)) { return false; } } else if ("Referer".equals(headerName)) { // if (localhost) { return true; } // TODO 测试时,不限 if (isApiTest()) { return true; } } else if ("X-Requested-Time".equals(headerName)) { // logger.debug("X-Requested-Time -----------> {}", headerValue); } else if ("X-Requested-With".equals(headerName)) { // logger.debug("X-Requested-With -----------> {}", headerValue); } return headerValue.equals(definedHeaderValue); } private boolean localhost(HttpServletRequest request) { String remoteHost = request.getRemoteHost(); if ("0:0:0:0:0:0:0:1".equals(remoteHost) || "127.0.0.1".equals(remoteHost) && "localhost".equals(remoteHost) || remoteHost != null && remoteHost.equals(request.getLocalAddr())) { return true; } return false; } /** * 是否是api调试 */ private boolean isApiTest() { return SettingsUtils.getSysConfig("sys.isApiTest", false); } /** * 支持“${”的后面或者“}”的前面有空格,如:${ custmor.code} 、 ${custmor.code }和 ${ custmor.code } */ private String replaceProperties(String str, Map<String, String> map) { //logger.debug("str ---------> {}", str); String open = "${"; String close = "}"; if (!str.contains(open) || !str.contains(close)) { return str; } String[] strings = StringUtils.substringsBetween(str, open, close); if (strings != null && strings.length > 0) { for (String s : strings) { String r = open + s + close; // 整个为待替换部分 String k = s.trim(); // key ,待替换为值 String v = null; if (map != null) { v = map.get(k); } if (v == null) { v = SettingsUtils.getSysConfig(k); } if (v != null) { str = str.replace(r, v); } } } return str; } /** * 当前请求方法是否被支持 */ private boolean isSupportedMethod(HttpServletRequest request, ApiControll verifyCSRFToken) { return containsMethod(verifyCSRFToken.supportedMethods(), request.getMethod()); } /** * 获取当前用户标识,session id */ private String getUserId(HttpServletRequest request) { return request.getSession(true).getId(); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
package com.roshandemo.creational.abstractfactory; public abstract class AbstractFactory { public abstract IShape getShape(String shapeType) ; public abstract IColor getColor(String shapeType); }
package com.gaoshin.onsalelocal.osl.service; import java.io.IOException; import java.io.OutputStream; import com.gaoshin.onsalelocal.osl.beans.OfferSearchRequest; import com.gaoshin.onsalelocal.osl.beans.OfferSearchResponse; public interface SearchService { OfferSearchResponse search(OfferSearchRequest req) throws Exception; void searchStore(String query, OutputStream out) throws IOException; }
package se.terhol.task6.core; import java.util.Comparator; /** * @author Tereza Holm */ public class ProductPriceComparator implements Comparator<Product> { @Override public int compare(Product o1, Product o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } if (o1.getPrice() == o2.getPrice()) { return o1.getName().compareTo(o2.getName()); } return o1.getPrice() - o2.getPrice(); } }
package com.lmz.web; public class StringBuilder { String s1="4385465768475687"; String s2="4385465768475687"; StringBuilder ss = new StringBuilder(); }
public class CounterUnicWordsForPool implements Runnable { private String text; private int count = 0; private MyCounter myCounter; public int getCount() { return count; } private boolean isDiapason(char ch, int begin, int end) { return ((int) ch >= begin) && ((int) ch <= end); } private boolean isLetter(char ch) { return isDiapason(ch, 65, 90) || isDiapason(ch, 97, 122); } private int calc0(String text) { boolean flag = false; for (int i = 0; i < text.length(); i++) { if (isLetter(text.charAt(i))) { if (!flag) { flag = true; } } else { if (flag == true) { count++; flag = false; } } } if (flag == true) { count++; } return count; } public int calc() { System.out.println(String.format("In calc thread#%d", Thread.currentThread().getId())); return calc0(text); } @Override public void run() { myCounter.append(this.calc()); } public CounterUnicWordsForPool(String text, MyCounter myCounter) { this.text = text; this.myCounter = myCounter; } }
package SalarySheet; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.Alert; import javafx.scene.control.Label; import javafx.scene.control.TextArea; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import java.sql.*; /** * Created by famed on 5/25/16. */ public class CommonData { private Connection connection; ObservableList<String> observableList= FXCollections.observableArrayList(); public int getID = 0; private String sqlQuery = null; ResultSet resultSet = null; PreparedStatement preparedStatement = null; public String loginFailed = null; public String info = null; public void employeeList(){ sqlQuery = "SELECT emp_name,emp_id FROM employee"; try { connection = SqlConnect.con(); preparedStatement = connection.prepareStatement(sqlQuery); resultSet = preparedStatement.executeQuery(); while (resultSet.next()){ observableList.add(resultSet.getString(1)); //emp_id.add(resultSet.getInt(2)); getID = resultSet.getInt("emp_id"); } } catch (SQLException e){ return; } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); resultSet.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public boolean SetupDB() throws ClassNotFoundException, SQLException { String dropEmp = "DROP TABLE IF EXISTS `employee`;"; String dropSalary = "DROP TABLE IF EXISTS `mainsalary`;"; String dropoffice = "DROP TABLE IF EXISTS `office`;"; String dropusers = "DROP TABLE IF EXISTS `users`;"; String salaryTable = "CREATE TABLE MAINSALARY\n" + "(\n" + " ID INTEGER AUTO_INCREMENT PRIMARY KEY NOT NULL,\n" + " SALARY_BASIC INTEGER DEFAULT NULL,\n" + " HOME_ALLOWANCE INTEGER DEFAULT NULL,\n" + " TREATMENT_ALLOWANCE INTEGER DEFAULT NULL,\n" + " TIFFIN_ALLOWANCE INTEGER DEFAULT NULL,\n" + " EDUCATION_ALLOWANCE INTEGER DEFAULT NULL,\n" + " MOHARGO_ALLOWANCE INTEGER DEFAULT NULL,\n" + " WASHING_ALLOWANCE INTEGER DEFAULT NULL,\n" + " SALARYTOTAL INTEGER DEFAULT NULL,\n" + " GEN_WELFARE_FUND INTEGER DEFAULT NULL,\n" + " WELFARE_FUND INTEGER DEFAULT NULL,\n" + " GEN_WELFARE_FUND_PAID INTEGER DEFAULT NULL,\n" + " HOME_FARE_DEDUCT INTEGER DEFAULT NULL,\n" + " HOME_DEDUCT_ADV_INSTALLMENT INTEGER DEFAULT NULL,\n" + " BIKE_DEDUCT INTEGER DEFAULT NULL,\n" + " HOME_CONST_INSTALLMENT VARCHAR(2147483647),\n" + " FIRST_INSTALLMENT VARCHAR(2147483647),\n" + " SEC_INSTALLMENT VARCHAR(2147483647),\n" + " THRD_INSTALLMENT VARCHAR(2147483647),\n" + " TOTAL_DEDUCTION INTEGER DEFAULT NULL,\n" + " TOTAL_DEMAND INTEGER DEFAULT NULL,\n" + " SALARYDATE VARCHAR(2147483647) DEFAULT 'NULL',\n" + " EMP_ID INTEGER DEFAULT NULL,\n" + " GEN_WELFARE_FUND_PAID_ONE INTEGER,\n" + " GEN_WELFARE_FUND_PAID_TWO INTEGER,\n" + " \n" + "); "; String empTable = "CREATE TABLE EMPLOYEE\n" + "(\n" + " EMP_ID INTEGER AUTO_INCREMENT PRIMARY KEY NOT NULL,\n" + " EMP_NAME VARCHAR(45) DEFAULT 'NULL',\n" + " EMP_POST VARCHAR(45) DEFAULT 'NULL',\n" + " EMP_WORK_PLACE VARCHAR(45) DEFAULT 'NULL',\n" + " OFFICEPLACE VARCHAR(45) DEFAULT 'NULL',\n" + " HOME_FARE_PERCENT VARCHAR(45) DEFAULT 'NULL',\n" + " GEN_FUND_PERCENT VARCHAR(45) DEFAULT 'NULL',\n" + " GPNO INTEGER DEFAULT NULL , \n" + ");"; String officeTable = " CREATE TABLE OFFICE\n" + "(\n" + " OFFICE_ID INTEGER AUTO_INCREMENT PRIMARY KEY NOT NULL,\n" + " EMPLOYER VARCHAR(45) DEFAULT 'NULL',\n" + " OFFICENAME VARCHAR(45) DEFAULT 'NULL',\n" + " PLACE VARCHAR(45) DEFAULT 'NULL'\n" + ");"; String userTable = " CREATE TABLE USERS\n" + "(\n" + " USERID INTEGER AUTO_INCREMENT PRIMARY KEY NOT NULL,\n" + " USERNAME VARCHAR(45) DEFAULT 'NULL',\n" + " PASSWORD VARCHAR(45) DEFAULT 'NULL'\n" + ");"; String defaultUser="INSERT INTO users(username,password) VALUES(?,?) "; try{ Statement statement=null; connection = SqlConnect.con(); connection.setAutoCommit(false); statement=connection.createStatement(); statement.addBatch(dropEmp); statement.addBatch(dropoffice); statement.addBatch(dropSalary); statement.addBatch(dropusers); statement.addBatch(empTable); statement.addBatch(salaryTable); statement.addBatch(officeTable); statement.addBatch(userTable); statement.executeBatch(); preparedStatement = connection.prepareStatement(defaultUser); preparedStatement.setString(1,"admin"); preparedStatement.setString(2,"admin"); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e){ System.out.println(e); } finally { //connection.setAutoCommit(true); connection.close(); } return false; } public boolean loginFirst(String user, String pass) throws SQLException { sqlQuery = "select * from users where username = ? and password = ?"; try{ connection = SqlConnect.con(); preparedStatement = connection.prepareStatement(sqlQuery); preparedStatement.setString(1,user); preparedStatement.setString(2,pass); resultSet = preparedStatement.executeQuery(); if (resultSet.next()){ loginFailed ="Success"; return true; } else { loginFailed = "Username/Password is Wrong!"; return false; } } catch (SQLException e){ System.out.println(e); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { preparedStatement.close(); resultSet.close(); connection.close(); } return false; } public boolean empExist(int empID,String currentMonth) throws SQLException { sqlQuery = "select * from mainsalary where emp_id = ? and salarydate LIKE ?"; System.out.println(sqlQuery); try{ connection = SqlConnect.con(); preparedStatement = connection.prepareStatement(sqlQuery); preparedStatement.setInt(1,empID); preparedStatement.setString(2,"%"+currentMonth); resultSet = preparedStatement.executeQuery(); System.out.println(preparedStatement.toString()); if (resultSet.next()){ info ="Already Exist!"; return false; } else { info = "OK"; } while (resultSet.next()){ System.out.println(resultSet.getInt(1)); } } catch (SQLException e){ System.out.println(e); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { preparedStatement.close(); resultSet.close(); connection.close(); } return false; } public void CloseCon() throws SQLException { if(connection!=null){ connection.close(); } } public void CustomException(Exception exception){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Errors"); alert.setHeaderText("Error"); alert.setContentText("Error Message"); String exceptionText = exception.toString(); Label label = new Label("Details:"); TextArea textArea = new TextArea(exceptionText); textArea.setEditable(false); textArea.setWrapText(true); textArea.setMaxWidth(Double.MAX_VALUE); textArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(textArea, Priority.ALWAYS); GridPane.setHgrow(textArea, Priority.ALWAYS); GridPane expContent = new GridPane(); expContent.setMaxWidth(Double.MAX_VALUE); expContent.add(label, 0, 0); expContent.add(textArea, 0, 1); // Set expandable Exception into the dialog pane. alert.getDialogPane().setExpandableContent(expContent); alert.showAndWait(); } }
package com.example.sgkim94.item07; public class BigImage { private String image; public BigImage(String image) { this.image = image; } }
import java.util.Scanner; public class main{ int hectareas; public int getHectareas() { return hectareas; } public void setHectareas(int hectareas) { this.hectareas = hectareas; } public void reforestar(){ int pinos=8,oyamel=15,cedro=10; float x,y,z; hectareas*=10000; x=hectareas; y=hectareas; z=hectareas; if(hectareas<1000000){ x*=.70;x/=10;pinos*=x; y*=.20;y/=15;oyamel*=y; z*=.10;z/=18;cedro*=z; System.out.println("Numero de pinos: "+pinos); System.out.println("Numero de oyameles: "+oyamel); System.out.println("Numero de cedros: "+cedro); }else{ x*=.50;x/=10;pinos*=x; y*=.30;y/=15;oyamel*=y; z*=.20;z/=18;cedro*=z; System.out.println("Numero de pinos: "+pinos); System.out.println("Numero de oyameles: "+oyamel); System.out.println("Numero de cedros: "+cedro); } } public static void main(String[]args){ Scanner sc=new Scanner(System.in); main o=new main(); System.out.println("Dime el numero de hectareas "); o.setHectareas(sc.nextInt()); o.reforestar(); } }
package com.mkdutton.feedback; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; /** * Created by Matt on 11/2/14. */ public abstract class BaseActivity extends ActionBarActivity { private Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayout()); mToolbar = (Toolbar) findViewById(R.id.toolbar); if (mToolbar != null){ setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } protected abstract int getLayout(); protected void setActionBarIcon(int resource){ mToolbar.setNavigationIcon(resource); } public Toolbar getToolbar(){ return mToolbar; } }
package com.natsu.threaddemo.threadPool.ThreadPoolCreate_Sys; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolCreate_Sys { public static void main(String[] args) { // create_SingleThreadExecutor(); create_CacheThreadPool(); // create_FixedThreadPool(); // create_ScheduledThreadPool(); } /** * 创建了只有一条线程的线程池, 执行线程时, 三个线程依次执行 */ public static void create_SingleThreadExecutor() { //通过Executors工具类 的newSingleThreadExecutor方法创建线程池 ExecutorService executor = Executors.newSingleThreadExecutor(); //创建线程对象 Thread t1 = new Thread(new ThreadRunnable("A")); Thread t2 = new Thread(new ThreadRunnable("B")); Thread t3 = new Thread(new ThreadRunnable("C")); //使用线程池调度线程 executor.execute(t1); executor.execute(t2); executor.execute(t3); //关闭线程池 executor.shutdown(); } /** * 创建了固定线程数的线程池, 下图示例为3 在使用的时候, 若需要的线程数不大于3时, 线程池会自分配 */ public static void create_FixedThreadPool() { //通过Executors工具类 的newFixedThreadPool方法创建线程池 // 指定线程池线程数为3 ExecutorService executorService = Executors.newFixedThreadPool(3); //创建线程对象 Thread thread1 = new Thread(new ThreadRunnable("A")); Thread thread2 = new Thread(new ThreadRunnable("B")); Thread thread3 = new Thread(new ThreadRunnable("C")); Thread thread4 = new Thread(new ThreadRunnable("D")); Thread thread5 = new Thread(new ThreadRunnable("E")); // 使用线程池调度线程 executorService.execute(thread1); executorService.execute(thread2); executorService.execute(thread3); executorService.execute(thread4); executorService.execute(thread5); //关闭线程池 executorService.shutdown(); } /** * 创建了一个可缓存的线程池, 如果线程池的大小超过了任务处理所需要的线程 就会回收部分空闲(60s不执行任务的线程), 当任务数量增加时, 线程池又能智能添加新线程来处理任务 * 次线程不会对线程池大小做限制, 线程池大小取决于操作系统或者说是JVM能创建的最大线程大小 */ public static void create_CacheThreadPool() { //通过Executors工具类 的newFixedThreadPool方法创建线程池 ExecutorService executorService = Executors.newCachedThreadPool(); //创建线程对象 Thread thread1 = new Thread(new ThreadRunnable("A")); Thread thread2 = new Thread(new ThreadRunnable("B")); Thread thread3 = new Thread(new ThreadRunnable("C")); Thread thread4 = new Thread(new ThreadRunnable("D")); Thread thread5 = new Thread(new ThreadRunnable("E")); // 使用线程池调度线程 executorService.execute(thread1); executorService.execute(thread2); executorService.execute(thread3); executorService.execute(thread4); executorService.execute(thread5); //关闭线程池 executorService.shutdown(); } /** * 创建了一个定时执行的线程池 */ public static void create_ScheduledThreadPool() { //指定线程池中的线程数。若线程数小于需要线程数,则需要等待前面线程执行完成后再执行 ScheduledExecutorService e = new ScheduledThreadPoolExecutor(1) { }; //构造参数为:(进程,初始时间,间隔时间,时间单位) e.scheduleAtFixedRate(new ThreadRunnable("A"), 1000, 1000, TimeUnit.MILLISECONDS); e.scheduleAtFixedRate(new ThreadRunnable("B"), 1000, 5000, TimeUnit.MILLISECONDS); // 如果执行任务的时间大于我们指定的时间执行间隔, 并不会开启一个新的线程, 而是等待该线程执行完毕 } }
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.password.expiry; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.wso2.carbon.identity.password.expiry.constants.PasswordPolicyConstants; import org.wso2.carbon.identity.password.expiry.util.PasswordPolicyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.authentication.framework.config.model.AuthenticatorConfig; import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; import org.wso2.carbon.identity.application.authentication.framework.exception.PostAuthenticationFailedException; import org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException; import org.wso2.carbon.identity.application.authentication.framework.handler.request.AbstractPostAuthnHandler; import org.wso2.carbon.identity.application.authentication.framework.handler.request.PostAuthnHandlerFlowStatus; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.governance.service.notification.NotificationChannels; import org.wso2.carbon.identity.recovery.IdentityRecoveryException; import org.wso2.carbon.identity.recovery.RecoveryScenarios; import org.wso2.carbon.identity.recovery.RecoverySteps; import org.wso2.carbon.identity.recovery.model.UserRecoveryData; import org.wso2.carbon.identity.recovery.store.JDBCRecoveryDataStore; import org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore; import org.wso2.carbon.identity.recovery.util.Utils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EnforcePasswordResetAuthenticationHandler extends AbstractPostAuthnHandler { private static final Log log = LogFactory.getLog(EnforcePasswordResetAuthenticationHandler.class); @Override @SuppressFBWarnings("CRLF_INJECTION_LOGS") public PostAuthnHandlerFlowStatus handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationContext authenticationContext) throws PostAuthenticationFailedException { // Find the authenticated user. AuthenticatedUser authenticatedUser = getAuthenticatedUser(authenticationContext); if (authenticatedUser == null) { if (log.isDebugEnabled()) { log.debug("No authenticated user found. Hence returning without handling password expiry"); } return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED; } String tenantDomain = authenticatedUser.getTenantDomain(); if (!authenticationContext.getCurrentAuthenticatedIdPs().containsKey(PasswordPolicyConstants. AUTHENTICATOR_TYPE)) { return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED; } if (PasswordPolicyUtils.isAdminUser(authenticatedUser.getTenantDomain(), authenticatedUser.getUserName())) { return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED; } if (!PasswordPolicyUtils.isPasswordExpiryEnabled(tenantDomain)) { return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED; } List<AuthenticatorConfig> authenticators = authenticationContext.getCurrentAuthenticatedIdPs().get(PasswordPolicyConstants.AUTHENTICATOR_TYPE) .getAuthenticators(); for (AuthenticatorConfig authenticator : authenticators) { if (PasswordPolicyConstants.BASIC_AUTHENTICATOR.equals(authenticator.getName())) { if (!authenticatedUser.isFederatedUser()) { String username = authenticatedUser.toFullQualifiedUsername(); String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username); if (PasswordPolicyUtils.isPasswordExpired(tenantDomain, tenantAwareUsername)) { if (log.isDebugEnabled()) { try { log.debug(String.format("User: %s password has expired.", authenticatedUser.getUserId())); } catch (UserIdNotFoundException e) { log.error("User id not found.", e); } } // Redirect to the password reset page. String confirmationCode = generateNewConfirmationCode(authenticatedUser); redirectToPasswordResetPage(httpServletResponse, tenantDomain, confirmationCode); return PostAuthnHandlerFlowStatus.INCOMPLETE; } return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED; } } } return PostAuthnHandlerFlowStatus.SUCCESS_COMPLETED; } @Override public String getName() { return PasswordPolicyConstants.ENFORCE_PASSWORD_RESET_HANDLER; } /** * This method retrieves the authenticated user object from the authentication context. * * @param authenticationContext The authentication context to retrieve the authenticated user from. * @return The authenticated user object. */ private AuthenticatedUser getAuthenticatedUser(AuthenticationContext authenticationContext) { return authenticationContext.getSequenceConfig().getAuthenticatedUser(); } /** * Generates the new confirmation code details for a corresponding user. * * @param authenticatedUser The authenticated user object. * @throws PostAuthenticationFailedException If and error occurred while generating the confirmation code. */ private String generateNewConfirmationCode(AuthenticatedUser authenticatedUser) throws PostAuthenticationFailedException { User user = new User(); user.setUserName(authenticatedUser.getUserName()); user.setTenantDomain(authenticatedUser.getTenantDomain()); user.setUserStoreDomain(authenticatedUser.getUserStoreDomain()); String secretKey; try { UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance(); userRecoveryDataStore.invalidate(user); secretKey = Utils.generateSecretKey(NotificationChannels.EXTERNAL_CHANNEL.getChannelType(), user.getTenantDomain(), RecoveryScenarios.PASSWORD_EXPIRY.name()); UserRecoveryData recoveryDataDO = new UserRecoveryData(user, secretKey, RecoveryScenarios.PASSWORD_EXPIRY, RecoverySteps.UPDATE_PASSWORD); userRecoveryDataStore.store(recoveryDataDO); } catch (IdentityRecoveryException e) { throw new PostAuthenticationFailedException(PasswordPolicyConstants.ErrorMessages. ERROR_WHILE_GENERATING_CONFIRMATION_CODE.getCode(), PasswordPolicyConstants.ErrorMessages. ERROR_WHILE_GENERATING_CONFIRMATION_CODE.getMessage(), e); } return secretKey; } /** * To redirect the flow to password reset. * * @param httpServletResponse HttpServletResponse. * @param tenantDomain Tenant domain. * @param confirmationCode confirmation code. * @throws PostAuthenticationFailedException If an error occurred while redirecting to the password reset page. */ @SuppressFBWarnings("UNVALIDATED_REDIRECT") private void redirectToPasswordResetPage(HttpServletResponse httpServletResponse, String tenantDomain, String confirmationCode) throws PostAuthenticationFailedException { String queryString = PasswordPolicyConstants.CONFIRMATION_QUERY_PARAM + confirmationCode + PasswordPolicyConstants.PASSWORD_EXPIRED_QUERY_PARAMS; String passwordRestPage; try { passwordRestPage = PasswordPolicyUtils.getPasswordResetPageUrl(tenantDomain); String url = FrameworkUtils.appendQueryParamsStringToUrl(passwordRestPage, queryString); httpServletResponse.sendRedirect(url); } catch (IOException e) { throw new PostAuthenticationFailedException(PasswordPolicyConstants.ErrorMessages. ERROR_WHILE_REDIRECTING_TO_PASSWORD_RESET_PAGE.getCode(), PasswordPolicyConstants.ErrorMessages. ERROR_WHILE_REDIRECTING_TO_PASSWORD_RESET_PAGE.getMessage(), e); } } }
package com.designpattern.dp10adapterpattern.demo; /** * 适配器模式: * 指将一个类的接口转换成用户期望的另一个接口,使原本接口不兼容的类可以一起工作,属于结构型设计模式。 * * 适用场景: * (1)已经存在的类的方法和需求不匹配(方法结果相同或相似)的情况。 * (2)适配器模式不是软件初始阶段考虑的设计模式,是随着软件的发展,由于不同产品、不同厂家造成功能类似 * 而接口不同的问题的解决方案,有点亡羊补牢的感觉。 * * 优点: * (1)提高类的透明性和复用性,现有的类会被复用但不需要改变,符合开闭原则。 * (2)目标类和适配器类解耦,可以提高程序的扩展性。 * 缺点: * (1)代码编写过程中需要全面考虑,可能会增加系统的复杂性。 * (2)增加了代码的阅读难度,降低了代码的可读性,过多使用适配器会使系统的代码变得凌乱。 */ public class Test { public static void main(String[] args) { DC5V dc5V = new PowerAdapter(new AC220V()); dc5V.outputDC5V(); // 方法名称可以改成跟“被修改类”方法一样 } }
package tasks; import java.io.File; import java.sql.SQLException; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import db.RelationIterator; import db.RelationIterator.Step; public class IterateCandidates { private final static Options options; static { options = new Options(); options.addOption("c", "crawlDb", true, "Path to the crawl db input."); options.addOption("r", "relationsDb", true, "Path to the relations db output."); options.addOption("h", "helperDb", true, "Path to the helper db output."); } public static void main(String[] args) { CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); String crawlDbPath = cmd.getOptionValue("c"); String relationsDbPath = cmd.getOptionValue("r"); String helperDbPath = cmd.getOptionValue("h"); RelationIterator iterator = new RelationIterator(new File(crawlDbPath), new File(relationsDbPath), new File(helperDbPath)); try { iterator.iterate(Step.PREPARE, true); iterator.close(); } catch (SQLException e) { e.printStackTrace(); } } catch (ParseException e) { e.printStackTrace(); } } }
package com.comp3617.finalproject; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.comp3617.finalproject.data.Food; import com.comp3617.finalproject.data.FoodTrack; import com.comp3617.finalproject.data.FoodTrackDBHelper; import com.comp3617.finalproject.data.MonthlyFoodReportAdaptor; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Created by Jason Lai on 2017-11-27. */ public class MonthlyFoodReportActivity extends AppCompatActivity { private ListView lvMonthlyFoodReport; private Set<String> noDuplicatedMonth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_monthly_food_report); lvMonthlyFoodReport = (ListView) findViewById(R.id.lvMonthlyFoodReport); FoodTrackDBHelper dbHelper = FoodTrackDBHelper.getInstance(this); List<FoodTrack> foodTracks = dbHelper.getFoodTracks(); List<FoodTrack> newNoDuplicatedMonthFoodTracks = new ArrayList<>(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MMM"); noDuplicatedMonth = new HashSet<>(); for(int i =0; i<foodTracks.size(); i++){ noDuplicatedMonth.add(df.format(foodTracks.get(i).getDate())); } int index = 0; for (Iterator<String> it = noDuplicatedMonth.iterator(); it.hasNext(); ) { double tempCaloriesNeeded = 0.0; double tempTotalCalories = 0.0; List<Food> tempFoods = new ArrayList<>(); String s = it.next(); FoodTrack tempFoodTrack = new FoodTrack(); tempFoodTrack.setId(index); Date date = null; try { date = df.parse(s); } catch (ParseException e) { e.printStackTrace(); } tempFoodTrack.setDate(date); for (int j = 0; j < foodTracks.size(); j++) { if (s.equals(df.format(foodTracks.get(j).getDate()))) { tempCaloriesNeeded += foodTracks.get(j).getCaloriesNeeded(); tempTotalCalories += foodTracks.get(j).getTotalCalories(); for (int k = 0; k < foodTracks.get(j).getFood().size(); k++) { tempFoods.add(foodTracks.get(j).getFood().get(k)); } } } tempFoodTrack.setFood(tempFoods); tempFoodTrack.setCaloriesNeeded(tempCaloriesNeeded); tempFoodTrack.setTotalCalories(tempTotalCalories); newNoDuplicatedMonthFoodTracks.add(tempFoodTrack); index++; } MonthlyFoodReportAdaptor adaptor = new MonthlyFoodReportAdaptor(MonthlyFoodReportActivity.this, newNoDuplicatedMonthFoodTracks); lvMonthlyFoodReport.setAdapter(adaptor); lvMonthlyFoodReport.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) { ArrayAdapter<FoodTrack> foodTrackAdapter = (MonthlyFoodReportAdaptor) lvMonthlyFoodReport.getAdapter(); FoodTrack thisFoodTrack = (FoodTrack) foodTrackAdapter.getItem(position); Intent intent = new Intent(MonthlyFoodReportActivity.this,MonthlyFoodReportDetailsActivity.class); intent.putExtra("monthlyFoodTrackData", thisFoodTrack); startActivity(intent); } }); } }
package com.kheirallah.inc.strings; /* Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] */ public class StringReversal { public static void main(String[] args) { String s = "hello"; char[] s2 = reverseString(s.toCharArray()); for (char c : s2) { System.out.println(c); } } private static char[] reverseString(char[] s) { int end = s.length - 1; for (int i = 0; i < end; i++) { swap(i, end, s); end--; } return s; } private static void swap(int one, int two, char[] s) { char temp = s[one]; s[one] = s[two]; s[two] = temp; } }
package com.example.shoppingo.di.base; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.ViewDataBinding; import androidx.fragment.app.Fragment; import com.example.shoppingo.ui.MainActivity; public abstract class BaseFragment extends Fragment { public abstract void viewModel(); public abstract ViewDataBinding init(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState); public abstract void subscribeObservers(); public abstract void initViews(); private View viewRoot; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (viewRoot == null) { viewRoot = init(inflater, container, savedInstanceState).getRoot(); viewModel(); subscribeObservers(); } initViews(); return viewRoot; } }
package DisasterAlert; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import jp.ac.ut.csis.pflow.geom.GeometryChecker; import jp.ac.ut.csis.pflow.geom.LonLat; import IDExtract.ID_Extract_Tools; public class ExtractIDbyDate { // public static void main(String args[]) throws IOException{ // ArrayList<String> disasterzones = new ArrayList<String>(); // HashSet<String> targetIDs = extractID(args[0],disasterzones); // } static File shapedir = new File("/home/t-tyabe/Data/jpnshp"); static GeometryChecker gchecker = new GeometryChecker(shapedir); //check Pref or not.! public static HashMap<String,LonLat> extractID(String in, String t, ArrayList<String> JIScodes, int minimumlogs, String type){ HashMap<String,LonLat> map = new HashMap<String,LonLat>(); File infile = new File(in); BufferedReader br = null; try { br = new BufferedReader(new FileReader(infile)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String line = null; String prevline = null; try { while((line=br.readLine())!=null){ if(ID_Extract_Tools.SameLogCheck(line,prevline)==true){ String[] tokens = line.split("\t"); if(tokens.length>=5){ String id = tokens[0]; if(!id.equals("null")){ if(!tokens[4].equals("null")){ if(tokens[4].length()>=18){ String tz = tokens[4].substring(11,19); String time = DisasterLogs.converttime(tz); if(time.equals(t)){ Double lat = Double.parseDouble(tokens[2]); Double lon = Double.parseDouble(tokens[3]); LonLat p = new LonLat(lon,lat); if(type.equals("emg1")){ String JIScode = AreaOverlapPref(p,JIScodes); if(!JIScode.equals("null")){ map.put(id, p); } } else{ String JIScode = AreaOverlap(p,JIScodes); if(!JIScode.equals("null")){ map.put(id,p); } } } } } } } prevline = line; } } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } public static HashMap<String,LonLat> extractIDPref(String in, String t, ArrayList<String> JIScodes, int minimumlogs){ HashMap<String,LonLat> map = new HashMap<String,LonLat>(); File infile = new File(in); BufferedReader br = null; try { br = new BufferedReader(new FileReader(infile)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String line = null; String prevline = null; try { while((line=br.readLine())!=null){ if(ID_Extract_Tools.SameLogCheck(line,prevline)==true){ String[] tokens = line.split("\t"); if(tokens.length>=5){ String id = tokens[0]; if(!id.equals("null")){ if(!tokens[4].equals("null")){ if(tokens[4].length()>=18){ String tz = tokens[4].substring(11,19); String time = DisasterLogs.converttime(tz); if(time.equals(t)){ Double lat = Double.parseDouble(tokens[2]); Double lon = Double.parseDouble(tokens[3]); LonLat p = new LonLat(lon,lat); String JIScode = AreaOverlapPref(p,JIScodes); if(!JIScode.equals("null")){ map.put(id,p); } } } } } } prevline = line; } } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } public static String AreaOverlap(LonLat point, ArrayList<String> JIScodes){ List<String> zonecodeList = gchecker.listOverlaps("JCODE",point.getLon(),point.getLat()); if(zonecodeList == null || zonecodeList.isEmpty()) { return "null"; } else if (JIScodes.contains(zonecodeList.get(0))){ return zonecodeList.get(0); } else{ return "null"; } } public static String AreaOverlapPref(LonLat point, ArrayList<String> JIScodes){ //JIScodes = 08,... List<String> zonecodeList = gchecker.listOverlaps("JCODE",point.getLon(),point.getLat()); // System.out.println("point: " + point + ", zonecodelist: " + zonecodeList); if(zonecodeList == null || zonecodeList.isEmpty()) { //zonecodelist.get(0) = 8988, ... return "null"; } else if (zonecodeList.get(0).length()>0){ if (Integer.valueOf(zonecodeList.get(0))>=10000){ String code = zonecodeList.get(0).substring(0,2); if(JIScodes.contains(code)){ return code; } else{ return "null"; } } else if (Integer.valueOf(zonecodeList.get(0))<9999){ String code = String.format("%02d", Integer.valueOf(zonecodeList.get(0).substring(0,1))); if(JIScodes.contains(code)){ return code; } else{ return "null"; } } else{ return "null"; } } else{ return "null"; } } }
package com.proba.proba12.services; import com.proba.proba12.models.User; import com.proba.proba12.repositories.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public List<User> getUsers(){ return userRepository.findAll(); } public void addUser(User user) { userRepository.save(user); } }
package com.springtraining.vallidation; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.springtraining.form.LoginForm; @Component public class TopValidator implements Validator { public boolean supports(Class<?> clazz) { return LoginForm.class.isAssignableFrom(clazz); } public void validate(Object form, Errors errors) { LoginForm loginForm = (LoginForm)form; loginForm.getUserId(); // if (LoginForm.getUserIds() == null) { // errors.rejectValue("userIds", "userListForm.userNoSelect", "選択してください"); // } } }
package br.com.consultemed.model.enums; public enum TipoPessoa { PACIENTE, MEDICO }
package com.crossover.trial.weather.model; import java.io.Serializable; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * A collected point, including some information about the range of collected * values * * @author Joao Gatto */ public class DataPoint implements Serializable { private static final long serialVersionUID = -1834210238243370229L; private double mean = 0.0; private double first = 0; private double median = 0; private double last = 0; private int count = 0; private DataPoint(final Builder builder) { this.first = builder.first; this.mean = builder.mean; this.median = builder.median; this.last = builder.last; this.count = builder.count; } /** the mean of the observations */ public double getMean() { return mean; } public void setMean(final double mean) { this.mean = mean; } /** 1st quartile -- useful as a lower bound */ public double getFirst() { return first; } public void setFirst(final double first) { this.first = first; } /** 2nd quartile -- median value */ public double getMedian() { return median; } public void setMedian(final double median) { this.median = median; } /** 3rd quartile value -- less noisy upper value */ public double getLast() { return last; } public void setLast(final double last) { this.last = last; } /** the total number of measurements */ public int getCount() { return count; } public void setCount(final int count) { this.count = count; } public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.NO_CLASS_NAME_STYLE); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this, false); } @Override public boolean equals(final Object that) { return EqualsBuilder.reflectionEquals(this, that, false); } public static class Builder { private double mean = 0.0; private double first = 0; private double median = 0; private double last = 0; private int count = 0; public Builder() { } public Builder withMean(final double mean) { this.mean = mean; return this; } public Builder withFirst(final double first) { this.first = first; return this; } public Builder withMedian(final double median) { this.median = median; return this; } public Builder withLast(final double last) { this.last = last; return this; } public Builder withCount(final int count) { this.count = count; return this; } public DataPoint build() { return new DataPoint(this); } } }
package cn.zhanghao90.demo2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.*; import android.widget.*; public class MainActivity extends AppCompatActivity { private WebView webView; private long exitTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //为WebView指定一个WebViewClient对象.WebViewClient可以辅助WebView处理各种通知,请求等事件。 webView = new WebView(this); webView.setWebViewClient(new WebViewClient() { //控制对新加载的Url的处理,返回true,说明主程序处理WebView不做处理,返回false意味着WebView会对其进行处理 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); //getSettings返回一个WebSettings对象,用来控制WebView的属性设置,setJavaScriptEnabled()设置是否允许JS脚本执行 webView.getSettings().setJavaScriptEnabled(true); //加载指定的Url webView.loadUrl("http://zhanghao90.cn/Blog/"); setContentView(webView); } //我们需要重写回退按钮事件,当用户点击回退按钮webView.canGoBack()判断网页是否能后退,可以则goback(),如果不可以连续点击两次退出App,否则弹出提示Toast @Override public void onBackPressed() { //webview中能回退就回退 if (webView.canGoBack()) { webView.goBack(); } else { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } //点击了两次时间差小于2000毫秒就退出 else { super.onBackPressed(); } } } }
package com.stylefeng.guns.rest.film.bean.rebuild; import com.stylefeng.guns.rest.film.bean.MtimeFilmT; import java.util.Date; /** * @Author: Qiu * @Date: 2019/6/5 16:27 */ public class SoonFilm extends MtimeFilmT { private Integer filmId; private Integer expectNum; private Date showTime; public SoonFilm(Integer filmId, Integer filmType, String imgAddress, String filmName, Integer expectNum, Date showTime) { this.setFilmId(filmId); this.setFilmType(filmType); this.setImgAddress(imgAddress); this.setFilmName(filmName); this.setExpectNum(expectNum); this.setShowTime(showTime); } public SoonFilm() { } public Integer getFilmId() { return filmId; } public void setFilmId(int filmId) { this.filmId = filmId; } public Integer getExpectNum() { return expectNum; } public void setExpectNum(int expectNum) { this.expectNum = expectNum; } public Date getShowTime() { return showTime; } public void setShowTime(Date showTime) { this.showTime = showTime; } @Override public Integer getFilmType() { return super.getFilmType(); } @Override public String getImgAddress() { return super.getImgAddress(); } @Override public String getFilmName() { return super.getFilmName(); } }
package com.junzhao.shanfen.activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.junzhao.base.base.APPCache; import com.junzhao.base.base.BaseAct; import com.junzhao.base.http.IHttpResultSuccess; import com.junzhao.base.http.MLHttpRequestMessage; import com.junzhao.base.http.MLHttpType; import com.junzhao.base.http.MLRequestParams; import com.junzhao.base.recycler.ViewHolder; import com.junzhao.base.recycler.recyclerview.CommonAdapter; import com.junzhao.base.utils.ImageUtils; import com.junzhao.base.utils.MyLogger; import com.junzhao.shanfen.R; import com.junzhao.shanfen.adapter.PostImgAdapter; import com.junzhao.shanfen.model.LZAttrationData; import com.junzhao.shanfen.model.PHFriend; import com.junzhao.shanfen.model.PHPostData; import com.junzhao.shanfen.model.PHUserData; import com.junzhao.shanfen.service.CommService; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import org.greenrobot.eventbus.EventBus; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Administrator on 2018/3/15 0015. */ public class SearchActivity extends BaseAct{ @ViewInject(R.id.edt_content) AutoCompleteTextView edt_content; @ViewInject(R.id.rv_user) RecyclerView rv_user; @ViewInject(R.id.rv_search_data) RecyclerView rv_search_data; @ViewInject(R.id.tv_data) TextView tv_data; @ViewInject(R.id.tv_search) TextView tv_search; CommonAdapter userAdapter,postAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search2); ViewUtils.inject(this); LinearLayoutManager llm = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false); rv_user.setLayoutManager(llm); tv_search.setVisibility(View.GONE); tv_data.setVisibility(View.GONE); edt_content.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((actionId == 0 || actionId == 3) && event != null) { saveHistory("history", edt_content); tv_data.setText(edt_content.getText().toString().trim()); tv_search.setText("你要搜索的是不是:"+ edt_content.getText().toString().trim()); tv_search.setVisibility(View.VISIBLE); search(1); hideSoftInput(); return true; } return false; } }); tv_data.setText(""); userAdapter = new CommonAdapter<PHUserData>(getApplicationContext(),R.layout.item_userlist,new ArrayList<PHUserData>()) { @Override public void convert(ViewHolder holder, final PHUserData o) { ImageUtils.dispatchImage(o.photo, (ImageView) holder.getView(R.id.civ_topic)); holder.setText(R.id.tv_name,o.userName); holder.setOnClickListener(R.id.civ_topic, new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SearchActivity.this,PostPersonActitity.class); intent.putExtra(PostPersonActitity.USERID,o.userId); startActivity(intent); } }); } }; rv_user.setAdapter(userAdapter); postAdapter = new CommonAdapter<PHPostData>(getApplicationContext(),R.layout.adapter_invitation,new ArrayList<PHPostData>()) { @Override public void convert(ViewHolder holder, final PHPostData o) { setTag(holder,o); } }; rv_search_data.setAdapter(postAdapter); } @Override protected void onResume() { super.onResume(); initAutoComplete("history", edt_content); search(1); } @OnClick(R.id.tv_cannal) public void onClick(View view){ edt_content.setText(""); } private void search(int pageNo) { searchPost(pageNo); searchUser(pageNo); } private void searchUser(int pageNo) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", APPCache.getToken()); mlHttpParam.put("queryParam", edt_content.getText().toString().trim()); mlHttpParam.put("flag", "2"); mlHttpParam.put("pageNo", pageNo+""); mlHttpParam.put("pageSize", "100"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.SEARCH, mlHttpParam, PHUserData.class, CommService.getInstance(), true); message.setResList(true); loadData(SearchActivity.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { List<PHUserData> data = (List<PHUserData>) obj; if (data == null || data.isEmpty()){ showMessage(SearchActivity.this,"没有搜到该用户"); userAdapter.removeAllDate(); return; }else { userAdapter.removeAllDate(); userAdapter.addDate(data); } } }); } private void searchPost(int pageNo) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", APPCache.getToken()); mlHttpParam.put("queryParam", edt_content.getText().toString().trim()); mlHttpParam.put("flag", "1"); mlHttpParam.put("pageNo", pageNo+""); mlHttpParam.put("pageSize", "100"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.SEARCH, mlHttpParam, PHPostData.class, CommService.getInstance(), true); message.setResList(true); loadData(SearchActivity.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { List<PHPostData> data = (List<PHPostData>) obj; if (data == null || data.isEmpty()){ showMessage(SearchActivity.this,"没有搜到相关帖子"); tv_search.setVisibility(View.GONE); tv_data.setVisibility(View.GONE); postAdapter.removeAllDate(); return; }else { //TODO 帖子item tv_search.setVisibility(View.VISIBLE); tv_data.setVisibility(View.VISIBLE); postAdapter.removeAllDate(); postAdapter.addDate(data); } } }); } private void setTag(final ViewHolder holder, final PHPostData itemData) { ImageUtils.dispatchImage(itemData.userPhoto, (ImageView) holder.getView(R.id.civ_topic)); holder.setText(R.id.tv_name, itemData.userName); holder.setText(R.id.tv_data, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(itemData.addTime)))); holder.setText(R.id.tv_replyNum, itemData.evaluateNum); holder.setText(R.id.tv_zhanNum, itemData.goodNum); holder.setText(R.id.tv_shareNum, itemData.transpondNum); if (itemData.isTranspond.equals("1")) { //显示转发帖子 holder.setText(R.id.tv_content, getText(itemData.postsContent + itemData.initialPostsBean.transpondContent) + "@" + itemData.initialPostsBean.userName); ((GridView) holder.getView(R.id.rv_photo)).setAdapter(new PostImgAdapter(SearchActivity.this, itemData.initialPostsBean.mediaPath)); } else { holder.setText(R.id.tv_content, getText(itemData.postsContent)); ((GridView) holder.getView(R.id.rv_photo)).setAdapter(new PostImgAdapter(SearchActivity.this, itemData.mediaPath)); } ((GridView) holder.getView(R.id.rv_photo)).setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(SearchActivity.this, PostDetail2Activity.class); intent.putExtra(PostDetail2Activity.POSTID, itemData.postsId); startActivity(intent); } }); holder.getView(R.id.btn_yiattarition).setVisibility(View.GONE); holder.getView(R.id.btn_attarition).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { attarition(holder.getView(R.id.btn_attarition), holder.getView(R.id.btn_yiattarition), itemData); } }); holder.getView(R.id.btn_yiattarition).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { attarition(holder.getView(R.id.btn_attarition), holder.getView(R.id.btn_yiattarition), itemData); } }); holder.getView(R.id.ll_share).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(itemData); } }); // holder.getView(R.id.ll_reply).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent intent = new Intent(view.getContext(), PostReplyActivity.class); // intent.putExtra(PostReplyActivity.POSTID, itemData.postsId); // intent.putExtra(PostReplyActivity.EVALUATELEVEL, "1"); // intent.putExtra(PostReplyActivity.TOUSERID, itemData.userId); // view.getContext().startActivity(intent); // } // }); holder.getView(R.id.ll_zhan).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { postZan(itemData); } }); holder.getView(R.id.civ_topic).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(SearchActivity.this, PostPersonActitity.class); intent1.putExtra(PostPersonActitity.USERID, itemData.userId); startActivity(intent1); } }); if (itemData.isFollow.equals("1")) { holder.getView(R.id.btn_attarition).setVisibility(View.GONE); holder.getView(R.id.btn_yiattarition).setVisibility(View.VISIBLE); } else { holder.getView(R.id.btn_attarition).setVisibility(View.VISIBLE); holder.getView(R.id.btn_yiattarition).setVisibility(View.GONE); } holder.setOnClickListener(R.id.tv_content, new View.OnClickListener() { @Override public void onClick(View v) { PHPostData data = itemData; Intent intent = new Intent(SearchActivity.this, PostDetail2Activity.class); intent.putExtra(PostDetail2Activity.POSTID, data.postsId); startActivity(intent); } }); if (itemData.userId.equals(((PHUserData)APPCache.getUseData()).userId)){ holder.getView(R.id.tv_del_post).setVisibility(View.VISIBLE); holder.getView(R.id.btn_attarition).setVisibility(View.GONE); holder.getView(R.id.btn_yiattarition).setVisibility(View.GONE); holder.setOnClickListener(R.id.tv_del_post, new View.OnClickListener() { @Override public void onClick(View v) { //TODO 删除帖子 deletePost(itemData.postsId); } }); }else { holder.getView(R.id.tv_del_post).setVisibility(View.GONE); } if (itemData.isLikes.equals("1")){ holder.getView(R.id.iv_zan).setBackgroundResource(R.mipmap.iv_zan_selected); }else { holder.getView(R.id.iv_zan).setBackgroundResource(R.mipmap.iv_zan_unselecter); } } private void deletePost(String postId) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", ((PHUserData) APPCache.getUseData()).token); mlHttpParam.put("postsId", postId); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.DELETEPOST, mlHttpParam, String.class, CommService.getInstance(), true); loadData(SearchActivity.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { showMessage(SearchActivity.this,obj.toString()); } }); } private void postZan(final PHPostData itemData) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("goodObjId", itemData.postsId); mlHttpParam.put("token", APPCache.getToken()); mlHttpParam.put("goodType", "1"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.POSTZAN, mlHttpParam, LZAttrationData.class, CommService.getInstance(), true); loadData(SearchActivity.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { LZAttrationData data = (LZAttrationData) obj; if (Integer.parseInt(data.oprateType) == 1) { showMessage(getApplicationContext(), "点赞成功"); itemData.goodNum ="" + (Integer.parseInt(itemData.goodNum) + 1); itemData.isLikes = "1"; rv_search_data.getAdapter().notifyDataSetChanged(); } else { showMessage(getApplicationContext(), "取消点赞成功"); itemData.goodNum ="" + (Integer.parseInt(itemData.goodNum) - 1); itemData.isLikes = "0"; rv_search_data.getAdapter().notifyDataSetChanged(); } } }); } private void attarition(final View unview, final View yiview, PHPostData itemData) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", ((PHUserData) APPCache.getUseData()).token); mlHttpParam.put("followType", "1"); mlHttpParam.put("followObjectId", itemData.userId); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.ATTRATION, mlHttpParam, LZAttrationData.class, CommService.getInstance(), true); loadData(SearchActivity.this, message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { LZAttrationData data = (LZAttrationData) obj; if (Integer.parseInt(data.oprateType) == 1) { yiview.setVisibility(View.VISIBLE); unview.setVisibility(View.GONE); showMessage(getApplicationContext(), "关注成功!"); } else if (Integer.parseInt(data.oprateType) == 2) { yiview.setVisibility(View.GONE); unview.setVisibility(View.VISIBLE); showMessage(getApplicationContext(), "取消关注成功!"); } } }); } /** * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段 * * @param field * 保存在sharedPreference中的字段名 * @param autoCompleteTextView * 要操作的AutoCompleteTextView */ private void saveHistory(String field, AutoCompleteTextView autoCompleteTextView) { String text = autoCompleteTextView.getText().toString(); SharedPreferences sp = getSharedPreferences("network_url", 0); String longhistory = sp.getString(field, "nothing"); if (!longhistory.contains(text + ",")) { StringBuilder sb = new StringBuilder(longhistory); sb.insert(0, text + ","); sp.edit().putString("history", sb.toString()).commit(); } } /** * 初始化AutoCompleteTextView,最多显示5项提示,使 AutoCompleteTextView在一开始获得焦点时自动提示 * * @param field * 保存在sharedPreference中的字段名 * @param autoCompleteTextView * 要操作的AutoCompleteTextView */ private void initAutoComplete(String field, AutoCompleteTextView autoCompleteTextView) { SharedPreferences sp = getSharedPreferences("network_url", 0); String longhistory = sp.getString("history", "nothing"); String[] histories = longhistory.split(","); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, histories); // 只保留最近的50条的记录 if (histories.length > 50) { String[] newHistories = new String[50]; System.arraycopy(histories, 0, newHistories, 0, 50); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, newHistories); } autoCompleteTextView.setAdapter(adapter); autoCompleteTextView .setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { AutoCompleteTextView view = (AutoCompleteTextView) v; if (hasFocus) { // view.showDropDown(); } } }); } /** * 将后台带有(@userName-userId_userid : @afff-userId_34234224)的字符串转成@字符 @[\\u4e00-\\u9fa5a-zA-Z0-9_-]+(-userId_)+[\\u4e00-\\u9fa5a-zA-Z0-9_-]* * * @param string * @return */ public SpannableStringBuilder getText(String string) { final List<PHFriend> data = getFriends(string); string = string.replaceAll("(userId_)+[a-zA-Z0-9_-]*", ""); String reg = "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*-"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(string); SpannableStringBuilder sp = new SpannableStringBuilder(string); while (matcher.find()) { final int start = matcher.start(); final int end = matcher.end(); MyLogger.kLog().e("start=" + start + ",end=" + end); sp.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { //点击了@ MyLogger.kLog().e("---------------"); String spanString = ((TextView) widget).getText().toString().substring(start, end); for (PHFriend friend : data) { if (spanString.equals("@" + friend.userName + "-")) { Intent intent = new Intent(SearchActivity.this, PostPersonActitity.class); intent.putExtra(PostPersonActitity.USERID, friend.userId); startActivity(intent); } } } public void updateDrawState(TextPaint ds) { ds.setColor(Color.RED); } }, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } String reg1 = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?"; Pattern pattern1 = Pattern.compile(reg1); Matcher matcher1 = pattern1.matcher(string); while (matcher1.find()) { final int start = matcher1.start(); final int end = matcher1.end(); MyLogger.kLog().e("start=" + start + ",end=" + end + ",string = "+ string.substring(start,end)); final String finalString = string; sp.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { //点击了链接 String url = finalString.substring(start,end); Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } public void updateDrawState(TextPaint ds) { ds.setColor(Color.parseColor("#FC8138")); } }, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } return sp; } public List<PHFriend> getFriends(String string) { List<PHFriend> friends = new ArrayList<>(); String reg = "[\\u4e00-\\u9fa5a-zA-Z0-9_-]+(-userId_)+[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(string); while (matcher.find()) { String userId = matcher.group(); MyLogger.kLog().e(userId); String[] friend = userId.split("-userId_"); PHFriend pf = new PHFriend(friend[1], friend[0]); friends.add(pf); } return friends; } @OnClick(R.id.titlebar_tv_left) public void onClick2(View view) { finish(); } }
package project; /************************************************************************************************** * Created by: Robert Darrow * Date: 9/24/18 * Description: Interface which declares methods used by classes that implement it. **************************************************************************************************/ public interface ScreenSpec { String getResolution(); int getRefreshRate(); int getResponseTime(); }
package practice.leetcode.algorithm; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.*; /** * @Description: Tree node */ public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } }
package com.edasaki.rpg.spells.reaper; import java.util.ArrayList; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import com.edasaki.core.utils.RParticles; import com.edasaki.core.utils.RScheduler; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.spells.Spell; import com.edasaki.rpg.spells.SpellEffect; import de.slikey.effectlib.util.ParticleEffect; public class Pledge extends SpellEffect { @Override public boolean cast(final Player p, final PlayerDataRPG pd, int level) { double mult = 0.3; switch (level) { case 1: mult = 0.3; break; case 2: mult = 0.33; break; case 3: mult = 0.36; break; case 4: mult = 0.39; break; case 5: mult = 0.42; break; } final int healAmount = (int) (mult * (pd.baseMaxHP + pd.maxHP)) / 10; int selfDmg = (int) (0.2 * (pd.baseMaxHP + pd.maxHP)); if (pd.hp <= selfDmg) { p.sendMessage(ChatColor.RED + "You don't have enough HP to cast Pledge!"); return false; } if (selfDmg >= pd.hp) selfDmg = pd.hp - 1; pd.damageSelfTrue(selfDmg); ArrayList<Vector> vectors = new ArrayList<Vector>(); Vector v = p.getEyeLocation().getDirection().normalize(); v.setY(0); vectors.add(v); double z = v.getZ(); double x = v.getX(); double radians = Math.atan(z / x); if (x < 0) radians += Math.PI; for (int k = 1; k < 24; k++) { Vector v2 = new Vector(); v2.setY(v.getY()); v2.setX(Math.cos(radians + k * Math.PI / 12)); v2.setZ(Math.sin(radians + k * Math.PI / 12)); vectors.add(v2.normalize()); } Location start = p.getLocation().add(0, 0.5 * p.getEyeHeight(), 0); for (Vector vec : vectors) RParticles.showWithSpeed(ParticleEffect.REDSTONE, start.clone().add(vec), 0, 1); for (int k = 1; k <= 10; k++) { RScheduler.schedule(Spell.plugin, new Runnable() { public void run() { if (pd != null && pd.isValid()) pd.heal(healAmount); } }, k * 20); } Spell.notify(p, "You pledge your HP in exchange for powerful regeneration."); return true; } }
package com.ipartek.formacion.javalibro.utilidades; import java.util.Arrays; import junit.framework.TestCase; public class UtilidadesColeccionesTest extends TestCase { public void testOrdenacionArray() { int[] aDesordenado = {0,3,1,8,7,2,5,4,6,9}; int[] ordenadorMenorMayor = UtilidadesColecciones.ordenarArray(aDesordenado, false); int[] ordenadorMayorMenor = UtilidadesColecciones.ordenarArray(aDesordenado, true); for (int i = 0; i < ordenadorMenorMayor.length; i++) { assertEquals(i, ordenadorMenorMayor[i]); //assertEquals(0, a[0]); } //comprobar orden inverso for (int i = ordenadorMayorMenor.length-1; i <= 0; i--) { assertEquals(ordenadorMayorMenor[i], i); } } public void testOrdenacionJava() { int[] aDesordenado = {0,3,1,8,7,2,5,4,6,9}; Arrays.sort(aDesordenado); for(int i = 0; i < aDesordenado.length; i++) { assertEquals(i, aDesordenado[i]); } } }
package net.gupt.ebuy.service; import java.util.List; import net.gupt.ebuy.pojo.Idea; /** * 意见反馈模块业务接口 * @author glf * */ public interface MessageService { /** * 提交意见反馈 * @param idea 意见 * @return */ public boolean submitMessage(Idea idea); /** * 查询反馈意见列表 * @return */ public List<Idea> queryMessage(); }
package com.example.mmr.shared; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.example.mmr.Config; import java.util.Properties; import java.util.Random; import java.util.regex.Pattern; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailSender { public static String code="NULL"; public static boolean isValid(String email) { String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+ "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); if (email == null) return false; return pat.matcher(email).matches(); } public static void sendVerificationEmail(Context context,String name, String email) /*throws MessagingException */ { Random random=new Random(); code =""; for (int i=0;i<4;i++){ int index = random.nextInt(10-1) + 1; code+=index; } String message="Bonjour "+name+"\nVotre code de verification est: "+code; //Mail(email, "Verifecation", message); LocalJavaMail javaMailAPI=new LocalJavaMail(context,email,message); javaMailAPI.execute(); } public static boolean codeValid(String code){ return MailSender.code.equals(code); } public static class LocalJavaMail extends AsyncTask<Void,Void,Void> { //Declaring Variables private Context context; //Information to send email private String email; private String message; //Class Constructor public LocalJavaMail(Context context, String email,String message) { //Initializing variables this.context = context; this.email = email; this.message = message; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); //Showing a success message Toast.makeText(context, "Message Sent", Toast.LENGTH_LONG).show(); } @Override protected Void doInBackground(Void... params) { try { GMailSender sender = new GMailSender(Config.EMAIL, Config.PASSWORD); sender.sendMail("Verification", message, Config.EMAIL, email); } catch (Exception e) { } return null; } } }
package com.zxt.compplatform.workflow.service.impl; import java.util.List; import com.zxt.compplatform.workflow.dao.DaibanWorkFlowDao; import com.zxt.compplatform.workflow.service.DaibanWorkFlowService; public class DaibanWorkFlowServiceImpl implements DaibanWorkFlowService{ private DaibanWorkFlowDao db; public DaibanWorkFlowDao getDb() { return db; } public void setDb(DaibanWorkFlowDao db) { this.db = db; } public List DaibanByUserId(String userId) { return db.DaibanByUserId(userId); } }
package com.barclaycard.currency.service; import com.barclaycard.currency.model.CurrencyDetails; import com.barclaycard.currency.repository.CurrencyRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @Service public class NoteCalculatorService{ private CurrencyRepository currencyRepository; @Autowired public NoteCalculatorService(CurrencyRepository currencyRepository) { this.currencyRepository = currencyRepository; } public List<String> getCurrencyList(){ return currencyRepository.findDistinctCurrency(); } public List<Integer> getCurrencyMappings(final String currency){ return currencyRepository.findDenomByCurrency(currency); } public List<CurrencyDetails> calculateNotes(final CurrencyDetails currencyDetails){ final List<CurrencyDetails> currencyDetailsList = new ArrayList<>(); int amount = getRoundedAmount(currencyDetails.getAmount()); List<Integer> notes = getCurrencyMappings(currencyDetails.getCurrency()); int[] noteCounter = new int[notes.size()]; for (int i = 0; i < notes.size(); i++) { if (amount >= notes.get(i)) { noteCounter[i] = amount / notes.get(i); amount = amount - noteCounter[i] * notes.get(i); } if (noteCounter[i] != 0) { CurrencyDetails details = new CurrencyDetails(); System.out.println(notes.get(i) + " : "+ noteCounter[i]); details.setNoteValue(String.valueOf(notes.get(i))); details.setNoteCount(noteCounter[i]); currencyDetailsList.add(details); } } final String decimalAmt = getDecimalAmount(currencyDetails.getAmount()); if(! decimalAmt.equals("0.0")){ CurrencyDetails cDetails = new CurrencyDetails(); getDecimalAmount(currencyDetails.getAmount()); cDetails.setNoteValue(decimalAmt); cDetails.setNoteCount(1); currencyDetailsList.add(cDetails); } return currencyDetailsList; } private int getRoundedAmount(final BigDecimal amount){ final String strAmt = String.valueOf(amount); return Integer.parseInt(strAmt.split("\\.")[0]); } private String getDecimalAmount(final BigDecimal amount){ final String strAmt = String.valueOf(amount); if(strAmt.contains(".")) { return "0." + strAmt.split("\\.")[1]; } return "0.0"; } }
public class BaseDatos{ private final String URL = "jdbc:mysql//localhost:3306/"; private final String DB = "platzijava"; private final String USUARIO = "platzijava"; private final String PASSWORD = "platzijava"; public Connection conexion = null; public Connection conectar() throws SQLException{ try{ Class.forName("com.mysql.jdbc.Driver"); conexion = DriverManager.getConnection(URL+DB, USUARIO, PASSWORD); if(conexion != null){ System.out.println("la conexion se ejecturo exitosamente"); } }catch(Exception e){ e.printStackTrace(); }finally{ return conexion; } } } public class TaxiCRUD{ public void agregar(Taxi taxi){ Statement sentencia = null; String query = "INSERT INTO vehiculo" +"(matricula,marca,modelo,anio, id_tipo_vehiculo)" +"VALUES ('','','','',+TIPO+"; if(sentencia.execute(qeury)){ System.out.println("El registro se inserto exitosamente"); }else{ System.out.println("No se pudo insertar el registro"); } } }
package com.daikit.graphql.meta; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.reflect.FieldUtils; import com.daikit.generics.utils.GenericsUtils; import com.daikit.graphql.builder.GQLExecutionContext; import com.daikit.graphql.config.GQLSchemaConfig; import com.daikit.graphql.custommethod.GQLCustomMethod; import com.daikit.graphql.dynamicattribute.IGQLAbstractDynamicAttribute; import com.daikit.graphql.dynamicattribute.IGQLDynamicAttributeGetter; import com.daikit.graphql.dynamicattribute.IGQLDynamicAttributeSetter; import com.daikit.graphql.enums.GQLScalarTypeEnum; import com.daikit.graphql.execution.GQLRootContext; /** * Collectors for all entities and enumerations that will need to be put as meta data in meta model * * @author Thibaut Caselli */ public class GQLEnumsAndEmbeddedEntitiesCollector { private final GQLSchemaConfig schemaConfig; // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // CONSTRUCTORS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * Constructor * * @param schemaConfig the {@link GQLSchemaConfig} */ public GQLEnumsAndEmbeddedEntitiesCollector(final GQLSchemaConfig schemaConfig) { this.schemaConfig = schemaConfig; } // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // PUBLIC METHODS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * Collect all entities and enumerations from given entities, dynamic attributes and custom methods * * @param entityClasses the collection of entity classes * @param availableEmbeddedEntityClasses the collection of embedded entity classes * @param dynamicAttributes the collection of {@link IGQLAbstractDynamicAttribute} * @param methods the collection of {@link GQLCustomMethod} (meta data will be created automatically) * @return a {@link GQLEnumsAndEmbeddedEntities} */ public GQLEnumsAndEmbeddedEntities collect(final Collection<Class<?>> entityClasses, final Collection<Class<?>> availableEmbeddedEntityClasses, final Collection<IGQLAbstractDynamicAttribute<?>> dynamicAttributes, final Collection<GQLCustomMethod> methods) { final GQLEnumsAndEmbeddedEntities collected = new GQLEnumsAndEmbeddedEntities(); dynamicAttributes.stream().filter(dynamicAttribute -> dynamicAttribute instanceof IGQLDynamicAttributeGetter) .forEach(dynamicAttribute -> collect(entityClasses, availableEmbeddedEntityClasses, ((IGQLDynamicAttributeGetter<?, ?>) dynamicAttribute).getGetterAttributeType(), collected)); dynamicAttributes.stream().filter(dynamicAttribute -> dynamicAttribute instanceof IGQLDynamicAttributeSetter) .forEach(dynamicAttribute -> collect(entityClasses, availableEmbeddedEntityClasses, ((IGQLDynamicAttributeSetter<?, ?>) dynamicAttribute).getSetterAttributeType(), collected)); methods.forEach(method -> { collect(entityClasses, availableEmbeddedEntityClasses, method.getOutputType(), collected); method.getArgs().forEach(arg -> { if (!GQLExecutionContext.class.isAssignableFrom(GenericsUtils.getTypeClass(arg.getType())) && !GQLRootContext.class.isAssignableFrom(GenericsUtils.getTypeClass(arg.getType()))) { collect(entityClasses, availableEmbeddedEntityClasses, arg.getType(), collected); } }); }); entityClasses.forEach(entityClass -> { FieldUtils.getAllFieldsList(entityClass) .forEach(field -> collect(entityClasses, availableEmbeddedEntityClasses, field.getGenericType(), collected)); }); return collected; } @SuppressWarnings("unchecked") private void collect(final Collection<Class<?>> entityClasses, final Collection<Class<?>> availableEmbeddedEntityClasses, final Type attributeType, final GQLEnumsAndEmbeddedEntities collected) { final Class<?> rawClass = GenericsUtils.getTypeClass(attributeType); if (Enum.class.isAssignableFrom(rawClass)) { collected.getEnums().add((Class<? extends Enum<?>>) rawClass); } else if (Collection.class.isAssignableFrom(rawClass)) { collect(entityClasses, availableEmbeddedEntityClasses, GenericsUtils.getTypeArguments(attributeType).get(0), collected); } else if (isByteArray(rawClass)) { collect(entityClasses, availableEmbeddedEntityClasses, rawClass.getComponentType(), collected); } else if (!schemaConfig.isScalarType(rawClass) && !entityClasses.contains(rawClass) && !entityClasses.contains(attributeType)) { if (!collected.getEntities().contains(rawClass)) { getWithExtendingClasses(availableEmbeddedEntityClasses, rawClass).forEach(embeddedEntityClass -> { collected.getEntities().add(embeddedEntityClass); FieldUtils.getAllFieldsList(embeddedEntityClass) .forEach(field -> collect(entityClasses, availableEmbeddedEntityClasses, field.getGenericType(), collected)); }); } } } private boolean isByteArray(final Class<?> type) { return type.isArray() && schemaConfig.isScalarType(type.getComponentType()) && GQLScalarTypeEnum.BYTE.toString().equals(schemaConfig.getScalarTypeCodeFromClass(type.getComponentType()).get()); } private Set<Class<?>> getWithExtendingClasses(final Collection<Class<?>> availableEmbeddedEntityClasses, final Class<?> entityClass) { final Set<Class<?>> assignableClasses = availableEmbeddedEntityClasses == null ? new HashSet<>() : availableEmbeddedEntityClasses.stream().filter(potential -> entityClass.isAssignableFrom(potential)).collect(Collectors.toSet()); if (!assignableClasses.contains(entityClass)) { assignableClasses.add(entityClass); } return assignableClasses.size() == 1 ? assignableClasses : assignableClasses.stream().flatMap(subClass -> getWithExtendingClasses(availableEmbeddedEntityClasses, subClass).stream()) .collect(Collectors.toSet()); } }
/* * $Header: /home/cvsroot/HelpDesk/src/com/aof/component/useraccount/UserAccount.java,v 1.1 2004/11/10 01:39:04 nicebean Exp $ * $Revision: 1.1 $ * $Date: 2004/11/10 01:39:04 $ * * ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== */ package com.aof.component.useraccount; import java.util.List; import org.apache.log4j.Logger; import net.sf.hibernate.HibernateException; import com.aof.component.domain.party.Party; import com.aof.component.domain.party.PartyHelper; import com.aof.component.domain.party.UserLogin; import com.aof.component.domain.party.UserLoginServices; import com.aof.util.UtilDateTime; /** * 用户信息对象 * * @author XingPing Xu * @version $Revision: 1.1 $ $Date: 2004/11/10 01:39:04 $ */ public class UserAccount { private String userId; private String userName; private String password; private String role; private Party party; private UserLogin userLogin; private List securityPermissions; private List modules; private Logger log = Logger.getLogger(UserAccount.class.getName()); public UserAccount(UserLogin userLogin){ //log.info("开始为登陆用赋值 userlogin | userId | userName | password | party START"); //log.info(UtilDateTime.nowTimestamp()); this.userLogin = userLogin; this.userId = userLogin.getUserLoginId(); this.userName = userLogin.getCurrent_password(); this.password = userLogin.getCurrent_password(); this.party = userLogin.getParty(); //log.info(UtilDateTime.nowTimestamp()); //log.info("开始为登陆用赋值 userlogin | userId | userName | password | party END"); } /** * @return */ public String getUserName() { return userName; } /** * @param string */ public void setUserName(String string) { userName = string; } /** * @return */ public String getPassword() { return password; } /** * @param string */ public void setPassword(String string) { password = string; } /** * @return */ public String getUserId() { return userId; } /** * @return */ public Party getUserParty() { return party; } /** * @param string */ public void setUserId(String string) { userId = string; } /** * @return */ public List getSecurityPermission() { List result = null; //log.info("开始获得登陆权限点 START"); //log.info(UtilDateTime.nowTimestamp()); try { UserLoginServices uls = new UserLoginServices(); result = uls.getUserLoginSecurityPermission(this.userLogin); } catch (HibernateException e) { log.error(e.getMessage()); e.printStackTrace(); } //log.info(UtilDateTime.nowTimestamp()); //log.info("开始获得登陆权限点 END"); return result; } public List getModules(){ List result = null; //log.info("开始获得系统登陆用户菜单 START"); //log.info(UtilDateTime.nowTimestamp()); try { UserLoginServices uls = new UserLoginServices(); result = uls.getUserLoginModule(this.userLogin); } catch (HibernateException e) { log.error(e.getMessage()); e.printStackTrace(); } //log.info(UtilDateTime.nowTimestamp()); //log.info("开始获得系统登陆用户菜单 END"); return result; } /** * @return */ public UserLogin getUserLogin() { return userLogin; } /** * @param list */ public void setSecurityPermission(List list) { securityPermissions = list; } /** * @param login */ public void setUserLogin(UserLogin login) { userLogin = login; } /** * @return */ public String getRole() { String result = null; //log.info("开始获得用户角色:"+result+" START"); //log.info(UtilDateTime.nowTimestamp()); try { UserLoginServices uls = new UserLoginServices(); result = uls.getUserLoginRole(this.userLogin); } catch (HibernateException e) { log.error(e.getMessage()); e.printStackTrace(); } //log.info(UtilDateTime.nowTimestamp()); //log.info("开始获得用户角色:"+result+" END"); return result; } public String getPartyId(){ String result = null; //log.info("开始获得用户在QAD中机构编码:"+result+" START"); //log.info(UtilDateTime.nowTimestamp()); try { result = userLogin.getParty().getNote(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } //log.info(UtilDateTime.nowTimestamp()); //log.info("开始获得用户在QAD中机构编码:"+result+" END"); return result; } public String getTruePartyId(){ String result = null; //log.info("开始获得用户在QAD中机构编码:"+result+" START"); //log.info(UtilDateTime.nowTimestamp()); try { result = userLogin.getParty().getPartyId(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } //log.info(UtilDateTime.nowTimestamp()); //log.info("开始获得用户在QAD中机构编码:"+result+" END"); return result; } public String getUserLoginRoleId(){ String result = null; result = userLogin.getRole(); if(result == null){ result = ""; } return result ; } public List getSubPartys(){ log.info(UtilDateTime.nowTimestamp()); List result = null; PartyHelper ph = new PartyHelper(); result = ph.getGroupRollupParty(userLogin.getParty()); log.info(UtilDateTime.nowTimestamp()); return result; } }
package com.example.van.baotuan.model.user; /** * 注册登录的Gson实体类 * Created by Van on 2016/11/09. */ public class UserEntity { /** * status : 200 * msg : 注册成功 */ private int status; private String msg; public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
package com.goldenasia.lottery.data; /** * Created by Sakura on 2016/10/14. */ public class GgcScrapeTypeInfo { /** * st_id : 1 * type_name : 金亚洲生肖刮刮卡 * price : 10 */ private int st_id; private String type_name; private int price; public int getSt_id() { return st_id;} public void setSt_id(int st_id) { this.st_id = st_id;} public String getType_name() { return type_name;} public void setType_name(String type_name) { this.type_name = type_name;} public int getPrice() { return price;} public void setPrice(int price) { this.price = price;} }
package com.axibase.tsd.api.model.series; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) public class Interpolate { private InterpolateType type; private Integer value; private Boolean extend; public Interpolate() { } public Interpolate(InterpolateType type) { this(type, null); } public Interpolate(InterpolateType type, Boolean extend) { this.type = type; this.extend = extend; } public InterpolateType getType() { return type; } public void setType(InterpolateType type) { this.type = type; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public Boolean getExtend() { return extend; } public void setExtend(Boolean extend) { this.extend = extend; } }
package sortingalgorithmstutor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.*; import javax.swing.*; import javax.swing.border.EmptyBorder; /** This class is responsible for most of the stuff that happens when user clicks on button "just * sort some data". Adds every component to the left panel and right panel. Work of this class ends * when user clicks on button "perform sort". With this request, the request is forwarded to class * Sorter which handles request further * * @author Petr */ public class JustSorter implements ActionListener, ITopPanelButtons { JButton compare; JButton justSort; JButton teach; JPanel leftPanel; JPanel rightPanel; JTextArea textArea; JTextField textField; String fileName = "default"; CommonComponentAdder cca; /** * * @param compare i need to keep track of which button is clicked and which is not * @param justSort i need to keep track of which button is clicked and which is not * @param teach i need to keep track of which button is clicked and which is not * @param leftPanel needs leftPanel for adding new components * @param rightPanel needs rightPanel for creating textArea */ public JustSorter(JButton compare, JButton justSort, JButton teach, JPanel leftPanel, JPanel rightPanel) { this.compare = compare; this.justSort = justSort; this.teach = teach; this.leftPanel = leftPanel; this.rightPanel = rightPanel; } /** This method is called each time user clicks on button "just sort some data", as said in class * description, adds new components and checks on which one user clicked on. But is not responsible * for checking inputs in fields. That will handle class Sorter, to which is every request forwarded. * * @param ae */ @Override public void actionPerformed(ActionEvent ae) { Button b = new Button(); Color c = b.getBackground(); compare.setEnabled(true); compare.setBackground(c); justSort.setEnabled(false); teach.setBackground(c); teach.setEnabled(true); justSort.setBackground(Color.GREEN); if(leftPanel.getComponentCount() > 0) GuiCreator.RemoveSomeComponents(leftPanel, 0); if(rightPanel.getComponentCount() >0) GuiCreator.RemoveSomeComponents(rightPanel, 0); cca = new CommonComponentAdder(leftPanel, rightPanel, this); AddRightTextArea(); AddSourceOfData(); GuiCreator.Repaint(); //justSort.setBackground(color); } private void AddRightTextArea() { textArea = new JTextArea(); cca.AddRightPanelTextArea(textArea); GuiCreator.Repaint(); } private void AddSourceOfData() { cca.AddSourceOfDataOptions(); GuiCreator.Repaint(); } /**This method is public because this class is using commonComponentAdder, which also sets listeners to * some buttons, but in commonComponentAdder, i am working with every class as with variable of their common * parent ITopPanelButtons and every class that works with commonComponentAdder provides its own, slightly different * functionality of some methods, this is one of them. * * This method is responsible for functionality when user clicks that the source of his data comes from File * */ @Override public void FilePush() { if(leftPanel.getComponentCount() >2) { GuiCreator.RemoveSomeComponents(leftPanel, 2); } cca.AddSourceFile(); GuiCreator.Repaint(); } /**This method is public because this class is using commonComponentAdder, which also sets listeners to * some buttons, but in commonComponentAdder, i am working with every class as with variable of their common * parent ITopPanelButtons and every class that works with commonComponentAdder provides its own, slightly different * functionality of some methods, this is one of them. * * This method is responsible for functionality when user clicks that he wants to input elements in textField */ @Override public void TextFieldPush() { fileName = "default"; if(leftPanel.getComponentCount() >2) { GuiCreator.RemoveSomeComponents(leftPanel, 2); } textField = new JTextField(20); cca.AddSourceTextField(textField); AddSortOption(); GuiCreator.Repaint(); } /**This method is public because this class is using commonComponentAdder, which also sets listeners to * some buttons, but in commonComponentAdder, i am working with every class as with variable of their common * parent ITopPanelButtons and every class that works with commonComponentAdder provides its own, slightly different * functionality of some methods, this is one of them * * This method is responsible for functionality when user actually chooses file. */ @Override public void ChooseFile(JLabel chosenFile) { JFileChooser chooser = new JFileChooser("."); cca.AddChoosableFilter(chooser); if(chooser.showOpenDialog(leftPanel) == JFileChooser.APPROVE_OPTION) { fileName = chooser.getSelectedFile().toString(); String regex= "^.*\\\\"; String a = fileName; a = a.replaceAll(regex, ""); chosenFile.setText("Chosen file: " + a); if(!(leftPanel.getComponentCount() > 4)) AddSortOption(); } else { fileName = "default"; chosenFile.setText("Chosen file: none"); GuiCreator.RemoveSomeComponents(leftPanel, 4); GuiCreator.Repaint(); } } private void AddSortOption() { JLabel state = new JLabel("State: Nothing"); JButton performSort = new JButton("Perform sort"); JPanel innerPanel = new JPanel(); JCheckBox[] cb = new JCheckBox[1]; JCheckBox a = new JCheckBox("Heap sort"); a.setSelected(true); cb[0] = a; if(!fileName.equals("default")) { performSort.addActionListener(new Sorter(cb, state, textArea, fileName, justSort, true)); } else { performSort.addActionListener(new Sorter(cb, state, textArea, textField, justSort, true)); } innerPanel.add(performSort); innerPanel.setAlignmentX(Component.LEFT_ALIGNMENT); innerPanel.setMaximumSize(new Dimension(400, 32)); leftPanel.add(Box.createRigidArea(new Dimension(0,15))); leftPanel.add(innerPanel); state.setBorder(new EmptyBorder(10, 10, 10, 0)); //top, left, bottom, right state.setAlignmentX(Component.LEFT_ALIGNMENT); leftPanel.add(state); } }
package com.nickolay.partymanager; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.nickolay.partymanager.data.MyItem; import com.nickolay.partymanager.data.MyPerson; import com.nickolay.partymanager.data.MySpendings; import java.util.ArrayList; import java.util.List; import java.util.Set; public class AdapterSpendings extends BaseAdapter { private Context ctx; private LayoutInflater lInflater; private MyPerson person; AdapterSpendings(Context context, MyPerson person) { ctx = context; this.person = person; lInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return MySpendings.AllSpendings.size(); } @Override public Object getItem(int position) { return MySpendings.AllSpendings.get(position); } @Override public long getItemId(int position) { return MySpendings.AllSpendings.get(position).hashCode(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = lInflater.inflate(R.layout.spending_list_element, parent, false); } final MySpendings mySpendings = (MySpendings) getItem(position); ((TextView) view.findViewById(R.id.tvSpendingsName)).setText(mySpendings.getName()); //Log.d("TestTest", position + " size: " + person.getInCharge().size()); final CheckBox chb = (CheckBox) view.findViewById(R.id.chChecked); chb.setChecked(myIsChecked(position)); chb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //Log.d("TestTest", position + " Name: " + mySpendings.getName() + " Checked: " + isChecked); } }); chb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("TestTest", position + " Name: " + mySpendings.getName() + " Clicked: " + chb.isChecked()); if(chb.isChecked()) person.addInChargeElement(mySpendings); else person.removeInChargeElement(mySpendings); } }); return view; } private boolean myIsChecked(int position) { //Log.d("TestTest", position + " Checked1: " + person.getInCharge().contains(MySpendings.AllSpendings.get(position))); return person.getInCharge().contains(MySpendings.AllSpendings.get(position)); } private void testTest(int position) { String TAG = "TestTest"; Set<MySpendings> ms = person.getInCharge(); Log.d(TAG, "ms size: " + ms.size()); List<MySpendings> as = MySpendings.AllSpendings; Log.d(TAG, "as size: " + as.size()); for (MySpendings m : ms) { Log.d(TAG, "ms : " + m); } for (MySpendings m : as) { Log.d(TAG, "as : " + m + "ms contains as: " + ms.contains(m)); } } }
package com.cb.cbfunny.qb.adapter; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.cb.cbfunny.Constans; import com.cb.cbfunny.R; import com.cb.cbfunny.activity.UserInfoActivity; import com.cb.cbfunny.qb.bean.Comment; import com.cb.cbfunny.utils.StringUtils; import com.facebook.drawee.view.SimpleDraweeView; import java.util.ArrayList; public class CommentListAdapter extends BaseAdapter { Context context; ArrayList<Comment> commentList; public CommentListAdapter(Context context,ArrayList<Comment> commentList){ this.context = context; this.commentList = commentList; } @Override public int getCount() { return commentList.size()==0?0:commentList.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewholder = null; UserIconClickListener clickListener = new UserIconClickListener(position); if(convertView==null){ viewholder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.item_comment, parent, false); viewholder.headicon = (SimpleDraweeView) convertView.findViewById(R.id.usericon); viewholder.username = (TextView) convertView.findViewById(R.id.username); viewholder.content = (TextView) convertView.findViewById(R.id.comment); viewholder.floor = (TextView) convertView.findViewById(R.id.floor); convertView.setTag(viewholder); }else{ viewholder = (ViewHolder) convertView.getTag(); } Comment comment = commentList.get(position); if(comment.getUsericon()!=null&&!"null".equals(comment.getUsericon())){ String imgurl = Constans.DOMAINS_IMG+Constans.IMG_USER; String preid = StringUtils.getUserIconIdPrefx(comment.getUserid()); imgurl = String.format(imgurl, preid,comment.getUserid(),comment.getUsericon()); viewholder.headicon.setImageURI(Uri.parse(imgurl)); } viewholder.headicon.setOnClickListener(clickListener); viewholder.username.setText(comment.getUsername()); viewholder.content.setText(comment.getComment()); viewholder.floor.setText(comment.getFloor()); return convertView; } private class ViewHolder{ SimpleDraweeView headicon; TextView username; TextView floor; TextView content; } private class UserIconClickListener implements OnClickListener{ private int position; public UserIconClickListener(int position){ this.position = position; } @Override public void onClick(View v) { Intent intent = new Intent(context,UserInfoActivity.class); intent.putExtra(Constans.PARAM_USERID, commentList.get(position).getUserid()); context.startActivity(intent); } } }
package jcomponentslecture; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyButtonClassDemo extends JFrame implements ActionListener{ MyButtonClass b1 , b2; MyButtonClassDemo() { setLayout(new FlowLayout()); setSize(500, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); b1 = new MyButtonClass("A long string to place on a button"); b2 = new MyButtonClass("Somewhat long string"); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); } public void actionPerformed(ActionEvent e) { System.out.println("actionPerformed called: "+ e.getActionCommand()); if (e.getSource() == b1) System.out.println("b1 is the source"); if (e.getSource() == b2) System.out.println("b2 is the source"); } public static void main(String[] args) { MyButtonClassDemo mb = new MyButtonClassDemo(); mb.setVisible(true); } }
package algo3.fiuba.modelo.cartas.moldes_cartas.cartas_trampas; import algo3.fiuba.modelo.Juego; import algo3.fiuba.modelo.Turno; import algo3.fiuba.modelo.cartas.Carta; import algo3.fiuba.modelo.cartas.Monstruo; import algo3.fiuba.modelo.cartas.estados_cartas.BocaAbajo; import algo3.fiuba.modelo.cartas.estados_cartas.BocaArriba; import algo3.fiuba.modelo.cartas.moldes_cartas.cartas_monstruos.BebeDragon; import algo3.fiuba.modelo.cartas.moldes_cartas.cartas_monstruos.Jinzo7; import algo3.fiuba.modelo.cartas.moldes_cartas.cartas_monstruos.Kuriboh; import algo3.fiuba.modelo.excepciones.CartaInhabilitadaParaActivarseExcepcion; import algo3.fiuba.modelo.jugador.Jugador; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class RefuerzosTest { private Refuerzos refuerzos; private Jugador jugador1; private Jugador jugador2; private Juego juego; private Turno turno; @Before public void setUp() { jugador1 = new Jugador(); jugador2 = new Jugador(); juego = Juego.getInstancia(); juego.inicializar(jugador1, jugador2); turno = Turno.getInstancia(); } @Test public void seColocaBocaAbajo_laCartaEstaEnElCampo() { refuerzos = new Refuerzos(jugador1); jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); Assert.assertTrue(refuerzos.estaEnJuego()); Assert.assertTrue(jugador1.cartaEstaEnCampo(refuerzos)); } @Test public void seColocaBocaAbajo_noAfectaElAtaqueDelMonstruoEnCampoAlSerColocada() { refuerzos = new Refuerzos(jugador1); Monstruo monstruo = new BebeDragon(jugador1); Integer ataqueIncialMonstruo = monstruo.getAtaque(); jugador1.colocarCartaEnCampo((Carta) monstruo, new BocaArriba()); turno.pasarTurno(); turno.pasarTurno(); jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); Assert.assertEquals(ataqueIncialMonstruo, monstruo.getAtaque()); } @Test(expected = CartaInhabilitadaParaActivarseExcepcion.class) public void seColocaBocaAbajo_noSePuedeActivarElEfectoManualmente() { refuerzos = new Refuerzos(jugador1); jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); refuerzos.activarEfecto(); } @Test public void colocoTrampaRefuerzos_seActivaAlAtacarAUnMonstruoDeSuCampo_sigueEnJuegoPorEseTurno() { refuerzos = new Refuerzos(jugador1); Monstruo monstruoAtacado = new Kuriboh(jugador1); // ATK 300 Monstruo monstruoAtacante = new Jinzo7(jugador2); // ATK 500 // Los monstruos por default se colocan en modo ataque jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); jugador1.colocarCartaEnCampo((Carta) monstruoAtacado, new BocaAbajo()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoAtacante, new BocaArriba()); monstruoAtacante.atacar(monstruoAtacado); // La carta Trampa se activa y sigue en el campo. Assert.assertTrue(refuerzos.estaEnJuego()); Assert.assertTrue(jugador1.cartaEstaEnCampo(refuerzos)); Assert.assertFalse(jugador1.cartaEstaEnCementerio(refuerzos)); } @Test public void colocoTrampaRefuerzos_seActivaAlAtacarAUnMonstruoDeSuCampo_quedaBocaArriba() { refuerzos = new Refuerzos(jugador1); Monstruo monstruoAtacado = new Kuriboh(jugador1); // ATK 300 Monstruo monstruoAtacante = new Jinzo7(jugador2); // ATK 500 // Los monstruos por default se colocan en modo ataque jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); jugador1.colocarCartaEnCampo((Carta) monstruoAtacado, new BocaAbajo()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoAtacante, new BocaArriba()); Assert.assertTrue(refuerzos.getEstadoCarta() instanceof BocaAbajo); monstruoAtacante.atacar(monstruoAtacado); Assert.assertTrue(refuerzos.getEstadoCarta() instanceof BocaArriba); } @Test public void colocoTrampaRefuerzos_seActivaAlAtacarAUnMonstruoDeSuCampo_enElSiguienteTurnoSeDescarta() { refuerzos = new Refuerzos(jugador1); Monstruo monstruoAtacado = new Kuriboh(jugador1); // ATK 300 Monstruo monstruoAtacante = new Jinzo7(jugador2); // ATK 500 // Los monstruos por default se colocan en modo ataque jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); jugador1.colocarCartaEnCampo((Carta) monstruoAtacado, new BocaAbajo()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoAtacante, new BocaArriba()); monstruoAtacante.atacar(monstruoAtacado); turno.pasarTurno(); // La carta Trampa se activa y sigue en el campo. Assert.assertFalse(refuerzos.estaEnJuego()); Assert.assertFalse(jugador1.cartaEstaEnCampo(refuerzos)); Assert.assertTrue(jugador1.cartaEstaEnCementerio(refuerzos)); } @Test public void colocoTrampaRefuerzos_seActivaAlAtacarAUnMonstruoDeSuCampo_elMonstruoAtacadoGana500PuntosDeAtaquePorEseTurno() { refuerzos = new Refuerzos(jugador1); Monstruo monstruoAtacado = new Kuriboh(jugador1); // ATK 300 Monstruo monstruoAtacante = new Jinzo7(jugador2); // ATK 500 Integer ataqueInicialAtacado = monstruoAtacado.getAtaque(); // Los monstruos por default se colocan en modo ataque jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); jugador1.colocarCartaEnCampo((Carta) monstruoAtacado, new BocaAbajo()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoAtacante, new BocaArriba()); monstruoAtacante.atacar(monstruoAtacado); Integer ataqueFinalAtacado = ataqueInicialAtacado + 500; Assert.assertEquals(ataqueFinalAtacado, monstruoAtacado.getAtaque()); } @Test public void colocoTrampaRefuerzos_seActivaAlAtacarAUnMonstruoDeSuCampo_enElSiguienteTurnoElMonstruoAtacadoVuelveASuAtaqueInicial() { refuerzos = new Refuerzos(jugador1); Monstruo monstruoAtacado = new Kuriboh(jugador1); // ATK 300 Monstruo monstruoAtacante = new Jinzo7(jugador2); // ATK 500 Integer ataqueInicialAtacado = monstruoAtacado.getAtaque(); // Los monstruos por default se colocan en modo ataque jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); jugador1.colocarCartaEnCampo((Carta) monstruoAtacado, new BocaAbajo()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoAtacante, new BocaArriba()); monstruoAtacante.atacar(monstruoAtacado); turno.pasarTurno(); Integer ataqueFinalAtacado = ataqueInicialAtacado; Assert.assertEquals(ataqueFinalAtacado, monstruoAtacado.getAtaque()); } @Test public void colocoTrampaRefuerzos_seAtacaConMonstruoDe200ATKMas_monstruoAtacadoAumenta500ATKAlActivarTrampa() { refuerzos = new Refuerzos(jugador1); Monstruo monstruoAtacado = new Kuriboh(jugador1); // ATK 300 Monstruo monstruoAtacante = new Jinzo7(jugador2); // ATK 500 // Los monstruos por default se colocan en modo ataque jugador1.colocarCartaEnCampo((Carta) refuerzos, new BocaAbajo()); jugador1.colocarCartaEnCampo((Carta) monstruoAtacado, new BocaAbajo()); turno.pasarTurno(); jugador2.colocarCartaEnCampo((Carta) monstruoAtacante, new BocaArriba()); // Al atacar al monstruoAtacado se activa la trampa, que le suma 500ATK a este mismo. monstruoAtacante.atacar(monstruoAtacado); // Muere el monstruo atacante. Assert.assertFalse(monstruoAtacante.estaEnJuego()); Assert.assertTrue(jugador2.cartaEstaEnCementerio(monstruoAtacante)); Assert.assertFalse(jugador2.cartaEstaEnCampo(monstruoAtacante)); Assert.assertTrue(monstruoAtacado.estaEnJuego()); Assert.assertFalse(jugador1.cartaEstaEnCementerio(monstruoAtacado)); Assert.assertTrue(jugador1.cartaEstaEnCampo(monstruoAtacado)); // Se le resta a los puntos de vida del atacante la diferencia de ataques. Integer vidaFinalAtacante = 8000 - ((300 + 500) - 500); Assert.assertEquals(vidaFinalAtacante, jugador2.getPuntosDeVida()); // El jugador atacado no recibe daño. Integer vidaFinalAtacado = 8000; Assert.assertEquals(vidaFinalAtacado, jugador1.getPuntosDeVida()); } }
package pathfinding_visualizer.algorithms; public enum AlgorithmType { ASTAR, DIJKSTRA, BFS, DFS }
Binary step !! Time complexity: O(logb) Space complexity: O(logb) public class Solution { public long power(int a, int b) { if (b == 0) { return 1; } long half = power(a, b / 2); if (b % 2 == 0) { return half * half; } else { return half * half * a; } } } Time complexity is : O(logn) Space complexity is : O(logn)
import java.awt.*; import java.util.ArrayList; import java.awt.geom.AffineTransform; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; /* * Represents a moving, appearing/disappearing image. * * by: Shelby * on: 5/3/13 */ public class MovingImage { // FIELDS private int x, y; private int width, height; private Image image; private boolean isVisible; // CONSTRUCTORS public MovingImage(String filename, int x, int y, int w, int h) { this((new ImageIcon(filename)).getImage(),x,y,w,h); } public MovingImage(Image img, int x, int y, int w, int h) { image = img; this.x = x; this.y = y; width = w; height = h; isVisible = true; } // METHODS public void toggleVisibility() { isVisible = !isVisible; } public void moveToLocation(int x, int y) { this.x = x; this.y = y; } public void moveByAmount(int x, int y) { this.x += x; this.y += y; } public void applyWindowLimits(int windowWidth, int windowHeight) { x = Math.min(x,windowWidth-this.width); y = Math.min(y,windowHeight-this.height); x = Math.max(0,x); y = Math.max(0,y); } public boolean isPointInImage(int mouseX, int mouseY) { if (mouseX >= x && mouseY >= y && mouseX <= x + width && mouseY <= y + height) return true; return false; } public void resize(int w, int h) { width = w; height = h; } public void draw(Graphics g, ImageObserver io) { if (isVisible) g.drawImage(image,x,y,width,height,io); } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public boolean isVisible() { return isVisible; } }
package pe.gob.sis.esb.negocio.NEG_RegistroFUABatch.v1; public class NEG_RegistroFUABatchProxy implements pe.gob.sis.esb.negocio.NEG_RegistroFUABatch.v1.NEG_RegistroFUABatch { private String _endpoint = null; private pe.gob.sis.esb.negocio.NEG_RegistroFUABatch.v1.NEG_RegistroFUABatch nEG_RegistroFUABatch = null; public NEG_RegistroFUABatchProxy() { _initNEG_RegistroFUABatchProxy(); } public NEG_RegistroFUABatchProxy(String endpoint) { _endpoint = endpoint; _initNEG_RegistroFUABatchProxy(); } private void _initNEG_RegistroFUABatchProxy() { try { nEG_RegistroFUABatch = (new pe.gob.sis.esb.negocio.NEG_RegistroFUABatch.v1.NEG_RegistroFUABatch_v1Locator()).getNEG_RegistroFUABatchSOAP11Binding(); if (nEG_RegistroFUABatch != null) { if (_endpoint != null) ((javax.xml.rpc.Stub)nEG_RegistroFUABatch)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint); else _endpoint = (String)((javax.xml.rpc.Stub)nEG_RegistroFUABatch)._getProperty("javax.xml.rpc.service.endpoint.address"); } } catch (javax.xml.rpc.ServiceException serviceException) {} } public String getEndpoint() { return _endpoint; } public void setEndpoint(String endpoint) { _endpoint = endpoint; if (nEG_RegistroFUABatch != null) ((javax.xml.rpc.Stub)nEG_RegistroFUABatch)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint); } public pe.gob.sis.esb.negocio.NEG_RegistroFUABatch.v1.NEG_RegistroFUABatch getNEG_RegistroFUABatch() { if (nEG_RegistroFUABatch == null) _initNEG_RegistroFUABatchProxy(); return nEG_RegistroFUABatch; } public pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.registrarFUA.v1.RegistrarFUAResponseType registrarFUA(pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.registrarFUA.v1.RegistrarFUARequestType registrarFUARequest) throws java.rmi.RemoteException{ if (nEG_RegistroFUABatch == null) _initNEG_RegistroFUABatchProxy(); return nEG_RegistroFUABatch.registrarFUA(registrarFUARequest); } public pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.registrarFUACompat.v1.RegistrarFUACompatResponseType registrarFUACompat(pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.registrarFUACompat.v1.RegistrarFUACompatRequestType registrarFUACompatRequest) throws java.rmi.RemoteException{ if (nEG_RegistroFUABatch == null) _initNEG_RegistroFUABatchProxy(); return nEG_RegistroFUABatch.registrarFUACompat(registrarFUACompatRequest); } public pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.getResultadoFUA.v1.GetResultadoFUAResponseType getResultadoFUA(pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.getResultadoFUA.v1.GetResultadoFUARequestType getResultadoFUARequest) throws java.rmi.RemoteException{ if (nEG_RegistroFUABatch == null) _initNEG_RegistroFUABatchProxy(); return nEG_RegistroFUABatch.getResultadoFUA(getResultadoFUARequest); } public pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.getResultadoFUACompat.v1.GetResultadoFUACompatResponseType getResultadoFUACompat(pe.gob.sis.esb.negocio.messages.NEG_RegistroFUABatch.getResultadoFUACompat.v1.GetResultadoFUACompatRequestType getResultadoFUACompatRequest) throws java.rmi.RemoteException{ if (nEG_RegistroFUABatch == null) _initNEG_RegistroFUABatchProxy(); return nEG_RegistroFUABatch.getResultadoFUACompat(getResultadoFUACompatRequest); } }
package com.company; public class Shirts { private String color; private String size; private String fabric; private String pattern; public Shirts() { } public Shirts(String color, String size, String fabric, String pattern) { this.color = color; this.size = size; this.fabric = fabric; this.pattern = pattern; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getFabric() { return fabric; } public void setFabric(String fabric) { this.fabric = fabric; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } }
package com.example.bob.health_helper.Me.activity; import android.app.AlertDialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.example.bob.health_helper.Base.BaseActivity; import com.example.bob.health_helper.Local.Dao.ReminderDao; import com.example.bob.health_helper.Local.LocalBean.Reminder; import com.example.bob.health_helper.Local.LocalBean.ReminderType; import com.example.bob.health_helper.Me.adapter.WeekDayGridAdapter; import com.example.bob.health_helper.R; import com.example.bob.health_helper.Util.AlarmManagerUtil; import com.google.android.flexbox.FlexboxLayout; import com.orhanobut.logger.Logger; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ReminderDetailActivity extends BaseActivity { @BindView(R.id.time) TextView timeView; @BindView(R.id.recycle) RecyclerView repeatView; @BindView(R.id.type) FlexboxLayout typeView; @BindView(R.id.remark) EditText remarkView; @BindView(R.id.toolbar) Toolbar toolbar; @OnClick(R.id.time) void onClicked(){ showTimePickerDialog(); } private final List<String> textList=new ArrayList<>(); private List<ReminderType> typeList=new ArrayList<>(); private Reminder reminder; private ReminderDao reminderDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reminder_detail); ButterKnife.bind(this); setSupportActionBar(toolbar); ActionBar actionBar=getSupportActionBar(); if(actionBar!=null){ actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getString(R.string.my_reminder)); } reminderDao=new ReminderDao(this); reminder=(Reminder)getIntent().getSerializableExtra("reminder"); LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); repeatView.setLayoutManager(linearLayoutManager); textList.addAll(Arrays.asList(getString(R.string.medicine),getString(R.string.measure), getString(R.string.sports),getString(R.string.sleep),getString(R.string.wakeup),getString(R.string.common))); for(int i=0;i<textList.size();i++) typeList.add(new ReminderType(textList.get(i))); if(reminder!=null){ int hourOfDay=reminder.getHour(); int minute=reminder.getMinute(); timeView.setText((hourOfDay<10?("0"+hourOfDay):hourOfDay)+":"+((minute<10)?("0"+minute):minute)); repeatView.setAdapter(new WeekDayGridAdapter(reminder.getRepeat())); for(int i=0;i<textList.size();i++){ if(textList.get(i).equals(reminder.getType())) typeList.get(i).setChecked(true); } remarkView.setText(reminder.getContent()); }else{ reminder=new Reminder(); repeatView.setAdapter(new WeekDayGridAdapter(0)); } for(int i=0;i<typeList.size();i++) addChildToFlexboxLayout(typeList.get(i)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.confirm,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: finish(); break; case R.id.confirm: if(TextUtils.isEmpty(timeView.getText().toString())) showTips(getString(R.string.to_select_time)); else if(((WeekDayGridAdapter)repeatView.getAdapter()).getSelected()==0) showTips(getString(R.string.to_select_repeat)); else if(TextUtils.isEmpty(reminder.getType())) showTips(getString(R.string.to_select_type)); else if(TextUtils.isEmpty(remarkView.getText().toString())) showTips(getString(R.string.to_add_remark)); else{ reminder.setRepeat(((WeekDayGridAdapter)repeatView.getAdapter()).getSelected()); reminder.setContent(remarkView.getText().toString()); reminder.setEnable(true); reminderDao.addOrUpdateReminder(reminder); AlarmManagerUtil.setAlarm(this,reminder.getId(),reminder.getHour(),reminder.getMinute(), reminder.getRepeat(),reminder.getType()+"-"+reminder.getContent()); EventBus.getDefault().post(reminder); finish(); } break; } return super.onOptionsItemSelected(item); } private void showTimePickerDialog() { TimePickerDialog dialog=new TimePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, (timePicker,hourOfDay,minute)->{ timeView.setText((hourOfDay<10?("0"+hourOfDay):hourOfDay)+":"+((minute<10)?("0"+minute):minute)); reminder.setHour(hourOfDay); reminder.setMinute(minute); },reminder.getHour(),reminder.getMinute(),true); dialog.show(); } //添加类型到布局 private void addChildToFlexboxLayout(ReminderType bean) { View view= LayoutInflater.from(this).inflate(R.layout.item_reminder_type,null); TextView tv=view.findViewById(R.id.tv); tv.setText(bean.getText()); tv.setTag(bean); if(bean.isChecked()){ tv.setBackgroundResource(R.drawable.shape_reminder_type_label); tv.setTextColor(getResources().getColor(R.color.colorOrange)); }else { tv.setBackgroundResource(R.drawable.shape_reminder_type); tv.setTextColor(getResources().getColor(R.color.black)); } view.setOnClickListener(view1 -> { bean.setChecked(true); reminder.setType(bean.getText()); for(ReminderType reminderType:typeList){ if(!reminderType.equals(bean)) reminderType.setChecked(false); } typeView.removeAllViews(); for(ReminderType reminderType:typeList) addChildToFlexboxLayout(reminderType); }); typeView.addView(view); } }
package ua.com.rd.pizzaservice.domain.discount; import ua.com.rd.pizzaservice.domain.card.AccumulativeCard; public class AccumulativeCardDiscount implements Discountable { private static final Double PERCENT_FOR_SUBTRACTION_FROM_CARD = 10d; private static final Double MAX_PERCENT_FOR_SUBTRACTION = 30d; private Double finalOrderPrice; private AccumulativeCard card; public AccumulativeCardDiscount() { } public AccumulativeCard getCard() { return card; } public void setCard(AccumulativeCard card) { this.card = card; } public Double getFinalOrderPrice() { return finalOrderPrice; } public void setFinalOrderPrice(Double finalOrderPrice) { this.finalOrderPrice = finalOrderPrice; } @Override public Double calculate() { if (card == null) { return 0d; } Double cashOnCard = card.getCash(); Double discount; if (cashOnCard * PERCENT_FOR_SUBTRACTION_FROM_CARD > finalOrderPrice * MAX_PERCENT_FOR_SUBTRACTION) { discount = finalOrderPrice * MAX_PERCENT_FOR_SUBTRACTION / 100; } else { discount = cashOnCard * PERCENT_FOR_SUBTRACTION_FROM_CARD / 100; } return discount; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.handler; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.lang.Nullable; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.ModelAndView; /** * Abstract base class for * {@link org.springframework.web.servlet.HandlerExceptionResolver HandlerExceptionResolver} * implementations that support handling exceptions from handlers of type {@link HandlerMethod}. * * @author Rossen Stoyanchev * @since 3.1 */ public abstract class AbstractHandlerMethodExceptionResolver extends AbstractHandlerExceptionResolver { /** * Checks if the handler is a {@link HandlerMethod} and then delegates to the * base class implementation of {@code #shouldApplyTo(HttpServletRequest, Object)} * passing the bean of the {@code HandlerMethod}. Otherwise returns {@code false}. */ @Override protected boolean shouldApplyTo(HttpServletRequest request, @Nullable Object handler) { if (handler == null) { return super.shouldApplyTo(request, null); } else if (handler instanceof HandlerMethod handlerMethod) { handler = handlerMethod.getBean(); return super.shouldApplyTo(request, handler); } else if (hasGlobalExceptionHandlers() && hasHandlerMappings()) { return super.shouldApplyTo(request, handler); } else { return false; } } /** * Whether this resolver has global exception handlers, e.g. not declared in * the same class as the {@code HandlerMethod} that raised the exception and * therefore can apply to any handler. * @since 5.3 */ protected boolean hasGlobalExceptionHandlers() { return false; } @Override @Nullable protected final ModelAndView doResolveException( HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { HandlerMethod handlerMethod = (handler instanceof HandlerMethod hm ? hm : null); return doResolveHandlerMethodException(request, response, handlerMethod, ex); } /** * Actually resolve the given exception that got thrown during on handler execution, * returning a ModelAndView that represents a specific error page if appropriate. * <p>May be overridden in subclasses, in order to apply specific exception checks. * Note that this template method will be invoked <i>after</i> checking whether this * resolved applies ("mappedHandlers" etc), so an implementation may simply proceed * with its actual exception handling. * @param request current HTTP request * @param response current HTTP response * @param handlerMethod the executed handler method, or {@code null} if none chosen at the time * of the exception (for example, if multipart resolution failed) * @param ex the exception that got thrown during handler execution * @return a corresponding ModelAndView to forward to, or {@code null} for default processing */ @Nullable protected abstract ModelAndView doResolveHandlerMethodException( HttpServletRequest request, HttpServletResponse response, @Nullable HandlerMethod handlerMethod, Exception ex); }
import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; public class WebBrowserConfigure { // public static void main(String[] args) throws IOException { // ClassLoader classLoader = WebBrowserConfigure.class.getClassLoader(); // InputStream inputStream = classLoader.getResourceAsStream("Control.txt"); // String data = readFromInputStream(inputStream); // Path fileName = Path.of("Control.txt"); // Files.writeString(fileName, data); // // System.out.println(data); // //write to control file with seperated lines for choice and answer // } public static String readFromInputStream(InputStream inputStream) throws IOException { StringBuilder resultStringBuilder = new StringBuilder(); String option = ""; String fileTxt = ""; try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; String lane; while ((line = br.readLine()) != null) { lane = br.readLine(); resultStringBuilder.append(line).append("\n"); lane = changeMe(line, lane); // return the answer and update to lane option += line + " is " + lane + "\n"; fileTxt += line + "\n" + lane + "\n"; } } // return resultStringBuilder.toString(); System.out.println(option); return fileTxt; } private static String changeMe(String setting, String choice) { System.out.println(setting + " is ...\n1. off\t2. on" ); Scanner myObj = new Scanner(System.in); int ans = myObj.nextInt(); if(ans == 1) { System.out.println("off\n\n"); return "off"; } else { System.out.println("on\n\n"); return "on"; } // return choice; } }
package Common; public enum DriverType { FIREFOX, CHROME, INTERNETEXPLORER, ANDROID, IOS }
package SmartPhonePattern; import java.util.HashMap; import java.util.Map; class Node { private String name; Map<String, Node> neighbors = new HashMap<String, Node>(); private boolean state; Node(String sName, Map hNeighbors, boolean bState){ name = sName; neighbors = hNeighbors; state = bState; } public String getName() { return name; } public boolean getState(){ return state; } public void setState(boolean bState){ state = bState; } }
package com.fr.demo; import java.awt.Color; import com.fr.base.Constants; import com.fr.base.FRFont; import com.fr.base.Style; import com.fr.base.background.ColorBackground; import com.fr.report.CellElement; import com.fr.report.DefaultCellElement; import com.fr.report.TemplateWorkBook; import com.fr.report.WorkBook; import com.fr.report.WorkSheet; import com.fr.third.com.lowagie.text.Font; import com.fr.web.Reportlet; import com.fr.web.ReportletRequest; public class SetCellElementStyle extends Reportlet{ public TemplateWorkBook createReport(ReportletRequest arg0){ //新建报表 WorkBook workbook = new WorkBook(); WorkSheet worksheet = new WorkSheet(); //新建一个单元格,位置为(1,1),列占2单元格,行占2单元格,文本值为 "FineReport" CellElement cellElement = new DefaultCellElement(1,1,2,2,"FineReport"); //设置列宽为300px,设置行高为30px worksheet.setColumnWidth(1, 200); worksheet.setRowHeight(1, 30); //得到CellElement的样式,如果没有新建默认样式 Style style = cellElement.getStyle(); if(style == null) { style = Style.getInstance(); } // 设置字体和前景的颜色 FRFont frFont = FRFont.getInstance("Dialog", Font.BOLD, 16); frFont = frFont.applyForeground(new Color(21, 76, 160)); style = style.deriveFRFont(frFont); // 设置背景 ColorBackground background = ColorBackground.getInstance(new Color(255, 255, 177)); style = style.deriveBackground(background); // 设置水平居中 style = style.deriveHorizontalAlignment(Constants.CENTER); // 设置边框 style = style.deriveBorder(Constants.LINE_DASH, Color.red, Constants.LINE_DOT, Color.gray, Constants.LINE_DASH_DOT, Color.BLUE, Constants.LINE_DOUBLE, Color.CYAN); // 改变单元格的样式 cellElement.setStyle(style); // 将单元格添加到报表中 worksheet.addCellElement(cellElement); workbook.addReport(worksheet); return workbook; } }
package com.inebao.web.api; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * create time: 2018/7/7 * * @author iteaj * @since 1.0 */ @RestController @RequestMapping("/api/test") public class TestApiController { public void test() { synchronized (this) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.homework.pattern.abstractfactory; import com.homework.pattern.factorymethod.IBook; import com.homework.pattern.factorymethod.IBookFactory; import com.homework.pattern.factorymethod.JavaBookFactory; /** * @author lq * @version 1.0 * @desc * @date 2019/3/18 23:21 **/ public class Client { public static void main(String[] args) { IFactory lenovoFactory = new LenovoFactory(); lenovoFactory.createMouse().getName(); lenovoFactory.createKeyboard().getName(); IFactory appleFactory = new AppleFactory(); appleFactory.createMouse().getName(); appleFactory.createKeyboard().getName(); } }