text
stringlengths
10
2.72M
package com.uit.huydaoduc.hieu.chi.hhapp.Framework.Direction; import android.content.Context; import android.util.Log; import com.uit.huydaoduc.hieu.chi.hhapp.Common.Common; import com.uit.huydaoduc.hieu.chi.hhapp.R; import com.uit.huydaoduc.hieu.chi.hhapp.Remote.IGoogleAPI; import com.google.android.gms.maps.model.LatLng; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Mai Thanh Hiep on 4/3/2016. * Customize by Phan Huu Chi on 4/2018 : use Retrofit 2 instead * alternative parseJSon method * whole new Object Class from JSon * multi finding method by splitting Create URL method */ public class DirectionFinder { private static final String TAG = "DirectionFinder"; private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?"; private static String GOOGLE_API_KEY; private DirectionFinderListener listener; private IGoogleAPI mapService; String urlRequest; public DirectionFinder(DirectionFinderListener listener, Context context) { urlRequest = null; this.listener = listener; this.GOOGLE_API_KEY = context.getResources().getString(R.string.map_api_key); mapService = Common.getGoogleAPI(); } /** * 1 place - 1 place */ public void createUrl(String origin, String destination) throws UnsupportedEncodingException { String urlOrigin = URLEncoder.encode(origin, "utf-8"); String urlDestination = URLEncoder.encode(destination, "utf-8"); urlRequest = DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&mode=driving" + "&mode=driving" + "&key=" + GOOGLE_API_KEY; } /** * 1 point - 1 place */ public void createUrl(LatLng latLng , String destination) throws UnsupportedEncodingException { String urlOrigin = latLng.latitude + "," + latLng.longitude; String urlDestination = URLEncoder.encode(destination, "utf-8"); urlRequest = DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&mode=driving" + "&mode=driving" + "&key=" + GOOGLE_API_KEY; } /** * 1 point - 1 point */ public void createUrl(LatLng start_latLng , LatLng end_latLng) throws UnsupportedEncodingException { String url_start = start_latLng.latitude + "," + start_latLng.longitude; String url_end = end_latLng.latitude + "," + end_latLng.longitude; urlRequest = DIRECTION_URL_API + "origin=" + url_start + "&destination=" + url_end + "&mode=driving" + "&mode=driving" + "&key=" + GOOGLE_API_KEY; } // NOTE: must call "createUrl" method before execute public void execute() throws UnsupportedEncodingException { listener.onDirectionFinderStart(); // setup the request get data ( set up the call ) if(urlRequest == null) { Log.e(TAG, "Error: urlRequest == null"); return; } Call<String> call = mapService.getPath(urlRequest); // enqueue: execute asynchronously . User a Callback to get respond from the server call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { try { String responseString = response.body(); // get response object // the response String is the whole JSON file have info of the direction parseJSon(responseString); // parse JSON } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(Call<String> call, Throwable t) { //todo: check Log.e(TAG, t.getMessage()); } }); } private void parseJSon(String data) throws JSONException { if (data == null) return; List<Route> routeList = new ArrayList<Route>(); final JSONObject jSONObject = new JSONObject(data); JSONArray routeJSONArray = jSONObject.getJSONArray("routes"); Route route; JSONObject routesJSONObject; for (int m = 0; m < routeJSONArray.length(); m++) { route = new Route(); routesJSONObject = routeJSONArray.getJSONObject(m); JSONArray legsJSONArray; route.setSummary(routesJSONObject.getString("summary")); JSONObject boundJSONObject = routesJSONObject.getJSONObject("bounds"); Bound routeBound = new Bound(); JSONObject routBoundNorthEast = boundJSONObject.getJSONObject("northeast"); routeBound.setNorthEast(new LatLng(routBoundNorthEast.getDouble("lat"), routBoundNorthEast.getDouble("lng"))); JSONObject routBoundSouthWest = boundJSONObject.getJSONObject("southwest"); routeBound.setSouthWest(new LatLng(routBoundSouthWest.getDouble("lat"), routBoundSouthWest.getDouble("lng"))); route.setBounds(routeBound); // Get LEGS Info legsJSONArray = routesJSONObject.getJSONArray("legs"); JSONObject legJSONObject; Leg leg; JSONArray stepsJSONArray; for (int b = 0; b < legsJSONArray.length(); b++) { leg = new Leg(); legJSONObject = legsJSONArray.getJSONObject(b); leg.setDistance(new Distance(legJSONObject.optJSONObject("distance").optString("text"), legJSONObject.optJSONObject("distance").optLong("value"))); leg.setDuration(new Duration(legJSONObject.optJSONObject("duration").optString("text"), legJSONObject.optJSONObject("duration").optLong("value"))); JSONObject legStartLocationJSONObject = legJSONObject.getJSONObject("start_location"); leg.setStartLocation(new LatLng(legStartLocationJSONObject.getDouble("lat"), legStartLocationJSONObject.getDouble("lng"))); JSONObject legEndLocationJSONObject = legJSONObject.getJSONObject("end_location"); leg.setEndLocation(new LatLng(legEndLocationJSONObject.getDouble("lat"), legEndLocationJSONObject.getDouble("lng"))); leg.setStartAddress(legJSONObject.getString("start_address")); leg.setEndAddress(legJSONObject.getString("end_address")); // Get STEPS Info stepsJSONArray = legJSONObject.getJSONArray("steps"); JSONObject stepJSONObject, stepDurationJSONObject, legPolyLineJSONObject, stepStartLocationJSONObject, stepEndLocationJSONObject; Step step; String encodedString; LatLng stepStartLocationLatLng, stepEndLocationLatLng; for (int i = 0; i < stepsJSONArray.length(); i++) { stepJSONObject = stepsJSONArray.getJSONObject(i); step = new Step(); JSONObject stepDistanceJSONObject = stepJSONObject.getJSONObject("distance"); step.setDistance(new Distance(stepDistanceJSONObject.getString("text"), stepDistanceJSONObject.getLong("value"))); stepDurationJSONObject = stepJSONObject.getJSONObject("duration"); step.setDuration(new Duration(stepDurationJSONObject.getString("text"), stepDurationJSONObject.getLong("value"))); stepEndLocationJSONObject = stepJSONObject.getJSONObject("end_location"); stepEndLocationLatLng = new LatLng(stepEndLocationJSONObject.getDouble("lat"), stepEndLocationJSONObject.getDouble("lng")); step.setEndLocation(stepEndLocationLatLng); step.setHtmlInstructions(stepJSONObject.getString("html_instructions")); legPolyLineJSONObject = stepJSONObject.getJSONObject("polyline"); encodedString = legPolyLineJSONObject.getString("points"); step.setPoints(decodePolyLine(encodedString)); stepStartLocationJSONObject = stepJSONObject.getJSONObject("start_location"); stepStartLocationLatLng = new LatLng(stepStartLocationJSONObject.getDouble("lat"), stepStartLocationJSONObject.getDouble("lng")); step.setStartLocation(stepStartLocationLatLng); leg.addStep(step); } route.addLeg(leg); } routeList.add(route); } listener.onDirectionFinderSuccess(routeList); } private List<LatLng> decodePolyLine(final String poly) { int len = poly.length(); int index = 0; List<LatLng> decoded = new ArrayList<LatLng>(); int lat = 0; int lng = 0; while (index < len) { int b; int shift = 0; int result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; decoded.add(new LatLng( lat / 100000d, lng / 100000d )); } return decoded; } }
/* * Copyright 2002-2022 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.filter; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.web.testfixture.servlet.MockFilterChain; import org.springframework.web.testfixture.servlet.MockHttpServletRequest; import org.springframework.web.testfixture.servlet.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * Test fixture for {@link FormContentFilter}. * * @author Rossen Stoyanchev */ public class FormContentFilterTests { private final FormContentFilter filter = new FormContentFilter(); private MockHttpServletRequest request; private MockHttpServletResponse response; private MockFilterChain filterChain; @BeforeEach public void setup() { this.request = new MockHttpServletRequest("PUT", "/"); this.request.setContentType("application/x-www-form-urlencoded; charset=ISO-8859-1"); this.response = new MockHttpServletResponse(); this.filterChain = new MockFilterChain(); } @Test public void wrapPutPatchAndDeleteOnly() throws Exception { for (HttpMethod method : HttpMethod.values()) { MockHttpServletRequest request = new MockHttpServletRequest(method.name(), "/"); request.setContent("foo=bar".getBytes("ISO-8859-1")); request.setContentType("application/x-www-form-urlencoded; charset=ISO-8859-1"); this.filterChain = new MockFilterChain(); this.filter.doFilter(request, this.response, this.filterChain); if (method == HttpMethod.PUT || method == HttpMethod.PATCH || method == HttpMethod.DELETE) { assertThat(this.filterChain.getRequest()).isNotSameAs(request); } else { assertThat(this.filterChain.getRequest()).isSameAs(request); } } } @Test public void wrapFormEncodedOnly() throws Exception { String[] contentTypes = new String[] {"text/plain", "multipart/form-data"}; for (String contentType : contentTypes) { MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/"); request.setContent("".getBytes("ISO-8859-1")); request.setContentType(contentType); this.filterChain = new MockFilterChain(); this.filter.doFilter(request, this.response, this.filterChain); assertThat(this.filterChain.getRequest()).isSameAs(request); } } @Test public void invalidMediaType() throws Exception { this.request.setContent("".getBytes("ISO-8859-1")); this.request.setContentType("foo"); this.filterChain = new MockFilterChain(); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.filterChain.getRequest()).isSameAs(this.request); } @Test public void getParameter() throws Exception { this.request.setContent("name=value".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.filterChain.getRequest().getParameter("name")).isEqualTo("value"); } @Test public void getParameterFromQueryString() throws Exception { this.request.addParameter("name", "value1"); this.request.setContent("name=value2".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(this.filterChain.getRequest().getParameter("name")).as("Query string parameters should be listed ahead of form parameters").isEqualTo("value1"); } @Test public void getParameterNullValue() throws Exception { this.request.setContent("name=value".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(this.filterChain.getRequest().getParameter("noSuchParam")).isNull(); } @Test public void getParameterNames() throws Exception { this.request.addParameter("name1", "value1"); this.request.addParameter("name2", "value2"); this.request.setContent("name1=value1&name3=value3&name4=value4".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); List<String> names = Collections.list(this.filterChain.getRequest().getParameterNames()); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(names).isEqualTo(Arrays.asList("name1", "name2", "name3", "name4")); } @Test public void getParameterValues() throws Exception { this.request.setQueryString("name=value1&name=value2"); this.request.addParameter("name", "value1"); this.request.addParameter("name", "value2"); this.request.setContent("name=value3&name=value4".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("name"); assertThat(filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(values).isEqualTo(new String[] {"value1", "value2", "value3", "value4"}); } @Test public void getParameterValuesFromQueryString() throws Exception { this.request.setQueryString("name=value1&name=value2"); this.request.addParameter("name", "value1"); this.request.addParameter("name", "value2"); this.request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("name"); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(values).isEqualTo(new String[] {"value1", "value2"}); } @Test public void getParameterValuesFromFormContent() throws Exception { this.request.addParameter("name", "value1"); this.request.addParameter("name", "value2"); this.request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("anotherName"); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(values).isEqualTo(new String[] {"anotherValue"}); } @Test public void getParameterValuesInvalidName() throws Exception { this.request.addParameter("name", "value1"); this.request.addParameter("name", "value2"); this.request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); String[] values = this.filterChain.getRequest().getParameterValues("noSuchParameter"); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(values).isNull(); } @Test public void getParameterMap() throws Exception { this.request.setQueryString("name=value1&name=value2"); this.request.addParameter("name", "value1"); this.request.addParameter("name", "value2"); this.request.setContent("name=value3&name4=value4".getBytes("ISO-8859-1")); this.filter.doFilter(this.request, this.response, this.filterChain); Map<String, String[]> parameters = this.filterChain.getRequest().getParameterMap(); assertThat(this.filterChain.getRequest()).as("Request not wrapped").isNotSameAs(this.request); assertThat(parameters).hasSize(2); assertThat(parameters.get("name")).isEqualTo(new String[] {"value1", "value2", "value3"}); assertThat(parameters.get("name4")).isEqualTo(new String[] {"value4"}); } @Test // SPR-15835 public void hiddenHttpMethodFilterFollowedByHttpPutFormContentFilter() throws Exception { this.request.addParameter("_method", "PUT"); this.request.addParameter("hiddenField", "testHidden"); this.filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.filterChain.getRequest().getParameterValues("hiddenField")).isEqualTo(new String[] {"testHidden"}); } }
/* * ModifyTBTHDF5Plugin */ package net.maizegenetics.analysis.gbs; import cern.colt.list.IntArrayList; import net.maizegenetics.dna.map.TagsOnPhysicalMap; import net.maizegenetics.dna.tag.TagCounts; import net.maizegenetics.dna.tag.Tags; import net.maizegenetics.dna.tag.TagsByTaxa.FilePacking; import net.maizegenetics.dna.tag.TagsByTaxaByteHDF5TaxaGroups; import net.maizegenetics.dna.tag.TagsByTaxa; import net.maizegenetics.dna.tag.TagsByTaxaByte; import net.maizegenetics.dna.tag.TagsByTaxaByteHDF5TagGroups; import net.maizegenetics.util.ArgsEngine; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import java.awt.Frame; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.TreeMap; import javax.swing.ImageIcon; import org.apache.log4j.Logger; /** * This pipeline modifies TagsByTaxa HDF5 file with data organized by taxa. * It can: * 1. Create an empty TBT. * 2. Merge two TBT * 3. Combined similarly named taxa * 4. Pivot a taxa TBT to a tag TBT * * @author ed */ public class ModifyTBTHDF5Plugin extends AbstractPlugin { private static final Logger myLogger = Logger.getLogger(ModifyTBTHDF5Plugin.class); private ArgsEngine myArgsEngine = null; private String myAdditionalTBTHDF5 = null; private String myTargetTBTHDF5 = null; private String myOutputTransposeTagTBTHDF5 = null; // private String myOutputLogFile = null; private boolean combineTaxa = false; private Tags myMasterTags = null; private static int maxGoodReads = 500000000; // maximum number of good barcoded reads expected in a fastq file IntArrayList[] taxaReads; int[] readsPerSample, mappedReadsPerSample; int goodBarcodedReads = 0, allReads = 0, goodMatched = 0; HashMap<String, Integer> taxaNameToIndices; TagsByTaxaByteHDF5TaxaGroups targetTBT = null; public ModifyTBTHDF5Plugin() { super(null, false); } public ModifyTBTHDF5Plugin(Frame parentFrame) { super(parentFrame, false); } @Override public DataSet performFunction(DataSet input) { if (myMasterTags != null) { targetTBT = new TagsByTaxaByteHDF5TaxaGroups(myMasterTags, myTargetTBTHDF5); } else { targetTBT = new TagsByTaxaByteHDF5TaxaGroups(myTargetTBTHDF5); } if (myAdditionalTBTHDF5 != null) { addAllTaxaToNewHDF5(myAdditionalTBTHDF5); } if (combineTaxa) { combineTaxaHDF5(); } if (myOutputTransposeTagTBTHDF5 != null) { TagsByTaxaByteHDF5TagGroups tranTBT = new TagsByTaxaByteHDF5TagGroups(targetTBT, myOutputTransposeTagTBTHDF5); } targetTBT.getFileReadyForClosing(); targetTBT = null; System.gc(); return null; } private void printUsage() { myLogger.info( "\n\n\nThe ModifyTBTHDF5Plugin accepts the following arguments:\n" + "-o Target TBT HDF5 (*tbt.h5) file to be modified\n" + "Depending on the modification that you wish to make, one of either:\n" + " -i TBT HDF5 (*tbt.h5) file containing additional taxa to be added to the target TBT HDF5 file\n" + " -c Merge taxa in the target TBT HDF5 file with same LibraryPrepID\n" + " -p Pivot (transpose) the target TBT HDF5 file into a tag-optimized orientation\n" // + "For creating an emptry TBT HDF4, one of either:\n" // + " -t Tag count file, OR A\n" // + " -m Physical map file containing alignments\n" // + "-L Output log file \n" +"\n\n\n"); } @Override public void setParameters(String[] args) { if (args.length == 0) { printUsage(); throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n"); } if (myArgsEngine == null) { myArgsEngine = new ArgsEngine(); myArgsEngine.add("-i", "--addition-file", true); myArgsEngine.add("-o", "--target-HDF5", true); // myArgsEngine.add("-L", "--outputlogfile", true); myArgsEngine.add("-c", "--combine-taxa", false); myArgsEngine.add("-p", "--taghdf-file", true); // myArgsEngine.add("-t", "--tagcount-file", true); // myArgsEngine.add("-m", "--physical-map", true); } myArgsEngine.parse(args); if (myArgsEngine.getBoolean("-o")) { myTargetTBTHDF5 = myArgsEngine.getString("-o"); } else { printUsage(); throw new IllegalArgumentException("Please specify an target file (option -o)."); } if (myArgsEngine.getBoolean("-i")) { myAdditionalTBTHDF5 = myArgsEngine.getString("-i"); } if (myArgsEngine.getBoolean("-p")) { myOutputTransposeTagTBTHDF5 = myArgsEngine.getString("-p"); } if (myArgsEngine.getBoolean("-c")) { combineTaxa = true; } // if (myArgsEngine.getBoolean("-L")) { // myOutputLogFile = myArgsEngine.getString("-L"); // } else { // printUsage(); // throw new IllegalArgumentException("Please specify a log file (option -L)."); // } // // Create Tags object from tag count file with option -t, or from TOPM file with option -m // if (myArgsEngine.getBoolean("-t")) { // if (myArgsEngine.getBoolean("-m")) { // printUsage(); // throw new IllegalArgumentException("Options -t and -m are mutually exclusive."); // } // myMasterTags = new TagCounts(myArgsEngine.getString("-t"), FilePacking.Bit); // } else if (myArgsEngine.getBoolean("-m")) { // if (myArgsEngine.getBoolean("-t")) { // printUsage(); // throw new IllegalArgumentException("Options -t and -m are mutually exclusive."); // } // myMasterTags = new TagsOnPhysicalMap(myArgsEngine.getString("-m"), true); // } } private boolean addAllTaxaToNewHDF5(String addTBTName) { TagsByTaxaByteHDF5TaxaGroups addTBT = new TagsByTaxaByteHDF5TaxaGroups(addTBTName); for (int i = 0; i < addTBT.getTagCount(); i++) { if (!Arrays.equals(targetTBT.getTag(i), addTBT.getTag(i))) { System.err.println("Tags are not the same for the two TBT file. They cannot be combined."); System.exit(0); } } for (int i = 0; i < addTBT.getTaxaCount(); i++) { String name = addTBT.getTaxaName(i); byte[] states = addTBT.getReadCountDistributionForTaxon(i); targetTBT.addTaxon(name, states); } addTBT.getFileReadyForClosing(); return true; } private boolean combineTaxaHDF5() { TreeMap<String, ArrayList<String>> combineTaxa = new TreeMap<String, ArrayList<String>>(); for (String tn : targetTBT.getTaxaNames()) { String ptn = parseTaxaName(tn, "#"); ArrayList<String> taxaList = combineTaxa.get(ptn); if (taxaList == null) { combineTaxa.put(ptn, taxaList = new ArrayList<String>()); } taxaList.add(tn); } for (ArrayList<String> taxaList : combineTaxa.values()) { if (taxaList.size() < 2) { continue; } byte[] di = new byte[targetTBT.getTagCount()]; String ptn = parseTaxaName(taxaList.get(0), "" + taxaList.size()); for (int i = 0; i < taxaList.size(); i++) { int j = targetTBT.getIndexOfTaxaName(taxaList.get(i)); byte[] dj = targetTBT.getReadCountDistributionForTaxon(j); for (int k = 0; k < dj.length; k++) { int ts = di[k] + dj[k]; if (ts > Byte.MAX_VALUE) { di[k] = Byte.MAX_VALUE; // System.out.println(di[k]+"+"+dj[k]); } else { di[k] = (byte) ts; } } } targetTBT.addTaxon(ptn, di); for (String tn : taxaList) { targetTBT.deleteTaxon(tn); } } return true; } private String parseTaxaName(String tn, String cnt) { String[] s = tn.split(":"); return s[0] + ":MRG:" + cnt + ":" + s[3]; } @Override public ImageIcon getIcon() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getButtonName() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getToolTipText() { throw new UnsupportedOperationException("Not supported yet."); } public static void main(String[] args) { String inTBTFile = "/Users/edbuckler/SolexaAnal/GBS/build20120110/tbt/434GFAAXX_s_3.tbt.byte"; TagsByTaxa inTBT = new TagsByTaxaByte(inTBTFile, FilePacking.Byte); // TagsByTaxaByteHDF5TaxaGroups tHDF5 = new TagsByTaxaByteHDF5TaxaGroups(inTBT, "/Users/edbuckler/SolexaAnal/GBS/test/433s3.h5"); // Tags theTags=new TagCountMutable(inTBT, inTBT.getTagCount()); // TagsByTaxaByteHDF5TaxaGroups rHDF5 = new TagsByTaxaByteHDF5TaxaGroups(theTags, "/Users/edbuckler/SolexaAnal/GBS/test/r433s3.h5"); // for (int i=0; i<tHDF5.getTaxaCount(); i++) { // byte[] d=tHDF5.getReadCountDistributionForTaxon(i); // String newName=tHDF5.getTaxaName(i).replace(":3:", ":4:"); // rHDF5.addTaxon(newName, d); // } // tHDF5.getFileReadyForClosing(); // rHDF5.getFileReadyForClosing(); // // args = new String[] { // "-i", "/Users/edbuckler/SolexaAnal/GBS/test/r433s3.h5", // "-o", "/Users/edbuckler/SolexaAnal/GBS/test/433s3.h5", // "-L", "/Users/edbuckler/SolexaAnal/GBS/test/testFQSeqTBT.log", // //"-c", // "-p","/Users/edbuckler/SolexaAnal/GBS/test/t433s3.h5", // }; // // ModifyTBTHDF5Plugin testClass = new ModifyTBTHDF5Plugin(); // testClass.setParameters(args); // testClass.performFunction(null); // // rHDF5 = new TagsByTaxaByteHDF5TaxaGroups("/Users/edbuckler/SolexaAnal/GBS/test/433s3.h5"); // tHDF5 = new TagsByTaxaByteHDF5TaxaGroups("/Users/edbuckler/SolexaAnal/GBS/test/r433s3.h5"); // // for (int i=0; i<rHDF5.getTaxaCount(); i++) { // byte[] di=rHDF5.getReadCountDistributionForTaxon(i); // int sumi=0; // for (byte b : di) {sumi+=b;} // System.out.println(rHDF5.getTaxaName(i)+":"+sumi); // for (int j = 0; j < tHDF5.getTaxaCount(); j++) { // byte[] dj=tHDF5.getReadCountDistributionForTaxon(j); // if(Arrays.equals(di, dj)) { // int sumj=0; // for (byte b : dj) {sumj+=b;} // System.out.println(rHDF5.getTaxaName(i)+":"+sumi+"="+tHDF5.getTaxaName(j)+":"+sumj); // } // } // } TagsByTaxaByteHDF5TagGroups transHDF5 = new TagsByTaxaByteHDF5TagGroups("/Users/edbuckler/SolexaAnal/GBS/test/t433s3.h5"); int same = 0, diff = 0, count = 0; long time = System.currentTimeMillis(); int tags = 9; for (int i = 0; i < 1000000; i += 11) { int taxon = i % inTBT.getTaxaCount(); // taxon=15; if (i % 550 == 0) { tags = i % inTBT.getTagCount(); } int newTaxonIndex = transHDF5.getIndexOfTaxaName(inTBT.getTaxaName(taxon)); if (inTBT.getReadCountForTagTaxon(tags, taxon) == transHDF5.getReadCountForTagTaxon(tags, newTaxonIndex)) { same++; } else { diff++; } count++; } System.out.printf("Same %d Diff %d %n", same, diff); long duration = System.currentTimeMillis() - time; double rate = (double) duration / (double) count; System.out.printf("Rate %g %n", rate); } }
package com.durgesh.schoolassist.Adapters; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.AdapterView; import android.widget.Spinner; import android.widget.TextView; import com.durgesh.schoolassist.PracticalsActivity; import com.durgesh.schoolassist.QuizActivity; import com.durgesh.schoolassist.R; import com.durgesh.schoolassist.RubricsActivity; public class RecyclerViewHolder extends RecyclerView.ViewHolder implements AdapterView.OnItemSelectedListener { TextView sname; Spinner spinner; String username; public RecyclerViewHolder(@NonNull View itemView, String username, Context context) { super(itemView); sname = itemView.findViewById(R.id.text_recycler); spinner = itemView.findViewById(R.id.spinner_recycler); this.username=username; spinner.setOnItemSelectedListener(this); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { //Do Nothing } else if(position==1) { Intent i = new Intent(view.getContext(), RubricsActivity.class).putExtra("username",username).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); view.getContext().startActivity(i); } else if(position==2) { Intent i = new Intent(view.getContext(), QuizActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("username",username); view.getContext().startActivity(i); } else if(position==3) { Intent i = new Intent(view.getContext(), PracticalsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("username",username); view.getContext().startActivity(i); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }
package pl.edu.agh.to2.interpreter.expressions; import pl.edu.agh.to2.commands.Command; import java.util.Deque; public class TerminalExpressionCOMMAND implements Expression { @Override public Command interpret(Deque<Expression> s) { return null; } @Override public String getRaw() { return null; } }
package egovframework.rte.ptl.mvc.bind; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Calendar; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.mortbay.log.Log; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.context.request.NativeWebRequest; public class CommandMapArgumentResolver implements WebArgumentResolver { public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { Class clazz = methodParameter.getParameterType(); String paramName = methodParameter.getParameterName(); // 기본조회 파라미터 // String S_Seq_Crum = ""; // String S_ShowDetail = ""; // // String selectSeqCurm = ""; if ((clazz.equals(Map.class)) && (paramName.equals("commandMap"))) { Map commandMap = new HashMap(); HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest(); Enumeration enumeration = request.getParameterNames(); // 맵으로날라오는 세션 값을 사칭한 아이디 삭제 // commandMap.put("suserId", null); HttpSession session = request.getSession(true); Enumeration senumeration = session.getAttributeNames(); //관리자 페이지 메뉴 클릭시 옵션설정 Y : session검색 정보 삭제, N : continue String admMenuInitOption = "N"; while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); String[] values = request.getParameterValues(key); // // if (key.equals("S_Seq_Crum")) { // S_Seq_Crum = (String) ((values.length > 1) ? values : values[0]); // continue; // } // // if (key.equals("selectSeqCurm")) { // selectSeqCurm = (String) ((values.length > 1) ? values : values[0]); // continue; // } // // if (key.equals("S_ShowDetail")) { // S_ShowDetail = (String) ((values.length > 1) ? values : values[0]); // continue; // } if (values != null) { // 배열로 초기화하는 폼값들은 모두 배열로 받는다. _Array시작하면 instance는 배열로 저장된다. if (key.startsWith("_Array")) { commandMap.put(key, (String[]) values); //Log.info("request commandMap \"_Array\" values length : " + values.length); } else { if(key.startsWith("ses_search_")) { session.removeAttribute(key); session.setAttribute(key, (values.length > 1) ? values : values[0]); } commandMap.remove(key); commandMap.put(key, (values.length > 1) ? values : values[0]); //Log.info("## request : " + key + " / " + ((values.length > 1) ? values : values[0])); } } } //관리자 페이지 메뉴 클릭시 옵션설정 Y : session검색 정보 삭제, N : continue if(commandMap.get("admMenuInitOption") != null && !"".equals(commandMap.get("admMenuInitOption"))) admMenuInitOption = commandMap.get("admMenuInitOption") + ""; while (senumeration.hasMoreElements()) { String skey = (String) senumeration.nextElement(); //검색박스는 세션에 등록하지 않는다. 검색 controller에서 세션에 저장한다. // if(skey.indexOf("ses_search_", 0) > -1) // continue; // else if(admMenuInitOption.equals("Y") && skey.startsWith("ses_search_")) { session.removeAttribute(skey); } else { commandMap.remove(skey); commandMap.put(skey, session.getAttribute(skey)); } } /* String S_DateType = (String) commandMap.get("S_DateType"); String S_SDate = (String) commandMap.get("S_SDate"); String S_EDate = (String) commandMap.get("S_EDate"); if (S_DateType == null || S_DateType.equals("")) { S_DateType = "3"; Calendar c_day = Calendar.getInstance(); int Y, M, D = 0; Y = c_day.get(Calendar.YEAR); M = c_day.get(Calendar.MONTH) + 3; D = c_day.get(Calendar.DATE); if (S_EDate == null || S_EDate.equals("")) { S_EDate = Y + "-" + ((M < 10) ? "0" + M : M) + "-" + ((D < 10) ? "0" + D : D); } c_day.add(c_day.MONTH, -3); Y = c_day.get(Calendar.YEAR); M = c_day.get(Calendar.MONTH) + 1; D = c_day.get(Calendar.DATE); if (S_SDate == null || S_SDate.equals("")) { S_SDate = Y + "-" + ((M < 10) ? "0" + M : M) + "-" + ((D < 10) ? "0" + D : D); } } String selectSDate = (String) commandMap.get("selectSDate"); String selectEDate = (String) commandMap.get("selectEDate"); Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); c.setTime(new Date(System.currentTimeMillis())); // String toDay = sdf.format(c.getTime()); if(selectSDate == null || selectSDate.equals("") ){ c.add(Calendar.MONTH, -1); Date minusOneMonth = c.getTime(); selectSDate = sdf.format(minusOneMonth); } if(selectEDate == null || selectEDate.equals("")){ c.add(Calendar.MONTH, 2); Date plusOneMonth = c.getTime(); selectEDate = sdf.format(plusOneMonth); } System.out.println("S_DateType="+S_DateType); System.out.println("S_SDate="+S_SDate); System.out.println("S_EDate="+S_EDate); commandMap.remove("S_DateType"); commandMap.remove("S_SDate"); commandMap.remove("S_EDate"); commandMap.put("S_DateType", S_DateType); commandMap.put("S_SDate", S_SDate); commandMap.put("S_EDate", S_EDate); commandMap.remove("selectSDate"); commandMap.remove("selectEDate"); commandMap.put("selectSDate", selectSDate); commandMap.put("selectEDate", selectEDate); session.removeAttribute("S_Seq_Crum"); session.setAttribute("S_Seq_Crum", S_Seq_Crum); session.removeAttribute("selectSeqCurm"); session.setAttribute("selectSeqCurm", selectSeqCurm); session.removeAttribute("S_ShowDetail"); session.setAttribute("S_ShowDetail", S_ShowDetail); commandMap.put("selectSeqCurm", selectSeqCurm); commandMap.put("S_Seq_Crum", S_Seq_Crum); commandMap.put("S_ShowDetail", S_ShowDetail); */ return commandMap; } return UNRESOLVED; } }
/* * 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 servlet.common.error; /** * * @author dangminhtien */ public class AddToCartError implements PresentableError { private String overQuantity; private String incorectQuantity; private String productId; public AddToCartError (String productId) { this.productId = productId; } public AddToCartError(String productId,String overQuantity, String incorectQuantity) { this.overQuantity = overQuantity; this.productId = productId; this.incorectQuantity = incorectQuantity; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getOverQuantity() { return overQuantity; } public void setOverQuantity() { this.overQuantity = "Insufficient inventory to supply"; } public String getIncorectQuantity() { return incorectQuantity; } public void setIncorectQuantity() { this.incorectQuantity = "Invalid format"; } }
package org.sunshinelibrary.turtle.utils; import org.sunshinelibrary.turtle.models.WebApp; import java.util.ArrayList; import java.util.List; /** * User: fxp * Date: 10/15/13 * Time: 3:49 PM */ public class DiffManifest { public List<WebApp> newApps = new ArrayList<WebApp>(); public List<WebApp> deletedApps = new ArrayList<WebApp>(); @Override public String toString() { return "new:" + newApps + "," + "delete:" + deletedApps; } }
/* Name : Poonam I. Patil Roll_no : 08 Div : B */ import java.util.*; abstract class shape { double dim1,dim2; shape(double a, double b) { dim1=a; dim2=b; } abstract void area(); } class rectangle extends shape { rectangle(double a, double b) { super(a,b); } void area() { System.out.println("Area of rectangle is : "+(dim1*dim2)); } } class triangle extends shape { triangle(double a, double b) { super(a,b); } void area() { System.out.println("Area of triangle is : "+((dim1*dim2)/2)); } } class abst { public static void main( String args[]) { shape ref; double a,b; Scanner in = new Scanner(System.in); System.out.println("\n enter 1st input no. : "); a=in.nextInt(); System.out.println("\n enter 2nd input no. : "); b=in.nextInt(); ref=new rectangle(a,b); ref.area(); ref=new triangle(a,b); ref.area(); } } /* ***** OUTPUT ***** student@student-Pegatron:~$ javac abst.java student@student-Pegatron:~$ java abst enter 1st input no. : 5 enter 2nd input no. : 5 Area of rectangle is : 25.0 Area of triangle is : 12.5 */
package com.cit360projectmark4.dao; import com.cit360projectmark4.pojo.CapturedEntity; import com.cit360projectmark4.pojo.ScabsEntity; import com.cit360projectmark4.pojo.UsersEntity; import com.cit360projectmark4.util.HibernateUtil; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import java.util.ArrayList; import java.util.List; public class BaseDaoImpl implements BaseDao { @Override public ScabsEntity getScab(int id) { Session session = HibernateUtil.getSession(); ScabsEntity scab = (ScabsEntity) session.get(ScabsEntity.class, id); return scab; } @Override public boolean login(String username, String password) { System.out.println("BaseDaoImpl: login: starting"); Session session = HibernateUtil.getSession(); if (session != null) { try { System.out.println("BaseDaoImpl: login: checking login credentials"); UsersEntity user = (UsersEntity) session.get(UsersEntity.class, username); System.out.println("BaseDaoImpl: login: credentials retrieved"); if (password.equals(user.getPassword())) { System.out.println("BaseDaoImpl: login: user " + user.toString() + " exists"); return true; } } catch (Exception exception) { System.out.println("BaseDaoImpl: login: Exception occurred while reading user data: " + exception.getMessage()); return false; } } else { System.out.println("BaseDaoImpl: login: DB server down....."); } return false; } @Override public String register(UsersEntity user) { System.out.println("BaseDaoImpl: register: starting"); String msg = "Registration unsuccessful, try again..."; Session session = HibernateUtil.getSession(); if (session != null) { try { if (user != null) { System.out.println("BaseDaoImpl: register: attempting to save user"); String username = (String) session.save(user); System.out.println("BaseDaoImpl: register: username string retrieved"); session.beginTransaction().commit(); System.out.println("BaseDaoImpl: register: user " + username + " created"); msg = "User " + username + " created successfully, please login..."; } } catch (Exception exception) { System.out.println("BaseDaoImpl: register: Exception occurred while reading user data: " + exception.getMessage()); } } else { System.out.println("BaseDaoImpl: register: DB server down....."); msg = "Registration couldn't complete because database is down. Contact Scab Admin"; } System.out.println("BaseDaoImpl: register: msg = " + msg); return msg; } @Override public String recordCalories(String username, String string_calories) { System.out.println("BaseDaoImpl: recordCalories: starting"); String msg = "Calories couldn't be recorded, try again..."; Session session = HibernateUtil.getSession(); if (session != null) { try { System.out.println("BaseDaoImpl: recordCalories: attempting input parse"); int calories = Integer.parseInt(string_calories); System.out.println("BaseDaoImpl: recordCalories: retrieving user by username " + username); UsersEntity user = (UsersEntity) session.get(UsersEntity.class, username); int old_calories = user.getcalories(); System.out.println("BaseDaoImpl: recordCalories: updating user object"); user.setcalories(calories + old_calories); System.out.println("BaseDaoImpl: recordCalories: pushing to database"); session.save(user); session.beginTransaction().commit(); msg = calories + " have been added! Your total is now " + (calories + old_calories); } catch (Exception exception) { System.out.println("BaseDaoImpl: recordCalories: Exception occurred while recording calories " + exception.getMessage()); } } else { System.out.println("BaseDaoImpl: recordCalories: DB server down....."); msg = "Calories couldn't be recorded because database is down. Contact Scab Admin"; } System.out.println("BaseDaoImpl: recordCalories: msg = " + msg); return msg; } @Override public String useCalories(String username, int calories) { System.out.println("BaseDaoImpl: useCalories: starting"); String msg = "Calories couldn't be used, try again..."; Session session = HibernateUtil.getSession(); if (session != null) { try { System.out.println("BaseDaoImpl: useCalories: retrieving user by username " + username); UsersEntity user = (UsersEntity) session.get(UsersEntity.class, username); int cur_calories = user.getcalories(); System.out.println("BaseDaoImpl: useCalories: subtracting calories"); int new_calories = cur_calories - calories; if (new_calories >= 0) { msg = "Calories accepted!"; System.out.println("BaseDaoImpl: useCalories: step amount accepted"); user.setcalories(new_calories); System.out.println("BaseDaoImpl: useCalories: pushing to database"); session.save(user); session.beginTransaction().commit(); } else { System.out.println("BaseDaoImpl: useCalories: step amount NOT accepted"); msg = "Calories can't be more then what you have, try again....."; } } catch (Exception exception) { System.out.println("BaseDaoImpl: useCalories: Exception occurred while recording calories " + exception.getMessage()); } } else { System.out.println("BaseDaoImpl: useCalories: DB server down..."); msg = "Calories couldn't be used because database is down. Contact Scab Admin"; } System.out.println("BaseDaoImpl: useCalories: msg = " + msg); return msg; } @Override public String storeCapturedScab(CapturedEntity new_scab) { System.out.println("BaseDaoImpl: storeCapturedScab: starting"); String msg = "There was an error saving your Scab! Contact Scab Admin"; Session session = HibernateUtil.getSession(); if (session != null) { try { System.out.println("BaseDaoImpl: storeCapturedScab: attempting to save Scab"); session.save(new_scab); System.out.println("BaseDaoImpl: storeCapturedScab: Scab is saved"); session.beginTransaction().commit(); System.out.println("BaseDaoImpl: storeCapturedScab: Scab is committed"); msg = "Congrats! You chose " + new_scab.getScab() + "!"; } catch (Exception exception) { System.out.println("BaseDaoImpl: storeCapturedScab: Exception occurred saving captured " + exception.getMessage()); } } else { System.out.println("BaseDaoImpl: storeCapturedScab: DB server down....."); } System.out.println("BaseDaoImpl: storeCapturedScab: msg = " + msg); return msg; } @Override public List<CapturedEntity> getCapturedScabs(String username) { System.out.println("BaseDaoImpl: getCapturedScabs: starting"); Session session = HibernateUtil.getSession(); List<CapturedEntity> results = null; if (session != null) { try { System.out.println("BaseDaoImpl: storeCapturedScab: attempting to retrieve Scabs"); Criteria criteria = session.createCriteria(CapturedEntity.class); System.out.println("BaseDaoImpl: storeCapturedScab: adding username criteria"); criteria.add(Restrictions.eq("owner", username)); System.out.println("BaseDaoImpl: storeCapturedScab: setting criteria to list"); results = criteria.list(); } catch (Exception exception) { System.out.println("BaseDaoImpl: getCapturedScabs: Exception occurred retrieving captured Scabs" + exception.getMessage()); results = new ArrayList<>(); } } else { System.out.println("BaseDaoImpl: getCapturedScabs: DB server down....."); results = new ArrayList<>(); } return results; } }
package OnlinemusicstoreClasses; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import javax.sound.sampled.*; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.ResourceBundle; public class PlaylistController implements Initializable { DatabaseManager db = DatabaseManager.getInstance(); @FXML private Button showHistory; @FXML private TableView<Song> StartTable; @FXML private TableView<Song> tableAdded; @FXML TableColumn<Song, String> Song; @FXML TableColumn<Song, String> Artist; @FXML TableColumn<Song, String> Album; @FXML TableColumn<Song, String> SongInPlaylist; @FXML TableColumn<Song, String> ArtistInPlaylist; @FXML TableColumn<Song, String> AlbumInPlaylist; ObservableList<Song>playlistSongs=FXCollections.observableArrayList(); CurrentUser cu = CurrentUser.getInstance(); private ObservableList<Song> boughtSongs = FXCollections.observableArrayList(db.getBoughtSongs(cu.getUserId()));; public void changetoMainmenu(javafx.event.ActionEvent event) { try { Node node = (Node) event.getSource(); Stage stage = (Stage) node.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("../OnlinemusicstoreFxml/mainMenu.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); } catch (NullPointerException ne) { ne.getSuppressed(); } catch (IOException e) { e.printStackTrace(); } } public void showHistory(ActionEvent event) { try { Node node = (Node) event.getSource(); Stage stage = (Stage) node.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("../OnlinemusicstoreFxml/orderhistory.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); } catch (Exception e){ e.printStackTrace(); } } @Override public void initialize(URL location, ResourceBundle resources) { Song.setText("Song"); Artist.setText("Artist"); Album.setText("Album"); SongInPlaylist.setText("Song"); ArtistInPlaylist.setText("Artist"); AlbumInPlaylist.setText("Album"); StartTable.setItems(boughtSongs); Song.setCellValueFactory(new PropertyValueFactory<Song, String>("songName")); Artist.setCellValueFactory(new PropertyValueFactory<Song, String>("artistName")); Album.setCellValueFactory(new PropertyValueFactory<Song, String>("albumName")); addToPlaylist(); tableAdded.setItems(playlistSongs); SongInPlaylist.setCellValueFactory(new PropertyValueFactory<Song, String>("songName")); ArtistInPlaylist.setCellValueFactory(new PropertyValueFactory<Song, String>("albumName")); AlbumInPlaylist.setCellValueFactory(new PropertyValueFactory<Song, String>("artistName")); } //checks if the selected song is in the playlist table. If it is dont add to playlistSongs. If it itsnt add to playlistSongs. @FXML public void addToPlaylist(){ StartTable.setRowFactory( tableView -> { TableRow<Song> row = new TableRow<>(); row.setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (! row.isEmpty()) ) { Song rowData = row.getItem(); System.out.println(rowData); boolean songIsInList = false; for (int i = 0; i < playlistSongs.size(); i++){ if (playlistSongs.get(i).equals(rowData)){ songIsInList = true; break; } } if (!songIsInList){ playlistSongs.add(rowData); } } }); return row; }); } public void playSong(ActionEvent event){ Song songToPlay = tableAdded.getSelectionModel().getSelectedItem(); if (songToPlay != null) { try { db.getMusicFile(songToPlay.getSongId()); AudioInputStream audioIn = AudioSystem.getAudioInputStream(new File("song.wav")); Clip clip = AudioSystem.getClip(); clip.open(audioIn); clip.start(); } catch (UnsupportedAudioFileException ex) { System.out.println("File not found"); } catch (IOException ex) { ex.printStackTrace(); } catch (LineUnavailableException lex) { lex.printStackTrace(); } } } public void deletePlaylist(ActionEvent event){ Song selectedItem = tableAdded.getSelectionModel().getSelectedItem(); tableAdded.requestFocus(); tableAdded.getItems().remove(selectedItem); } public void clearPlaylist(ActionEvent event){ tableAdded.requestFocus(); tableAdded.getItems().clear(); } @FXML void helpMenuPressed(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Information about searching"); alert.setHeaderText("Searching"); alert.setContentText("Here you can search for songs which you can add to your cart. Simply double-click" + "on whichever song you want to add to your cart."); alert.showAndWait(); } //created by jimmie @FXML void createPlaylist(ActionEvent event) { ObservableList<Song> songsObs = FXCollections.observableArrayList(); songsObs = tableAdded.getItems(); PlaylistSingleton pS = PlaylistSingleton.getInstance(); //This array was neccessary because otherwise the songs would get lost when clearing the playlistTableView. ArrayList<Song> sonsss = new ArrayList<>(tableAdded.getItems()); //a conversion from the sonss arraylist was also necessary as an observable arraylist is sent as an argument //to the setItems() method in the playlistSingleton. ObservableList<Song> ss = FXCollections.observableArrayList(sonsss); if (sonsss.size()==0) { System.out.println("Observable: " + ss); Alert alertBox = new Alert(Alert.AlertType.INFORMATION); alertBox.setHeaderText("Error"); alertBox.setContentText("You must choose some songs before creating a playlist"); alertBox.showAndWait(); } //if arraylist is not empty (there are items in the playlistTableView) send the observable arraylist to playlist singleton if (sonsss.size()>0) { pS.setPlaylist(ss); System.out.println("Song added to playlist"+sonsss); System.out.println("ss Observable list before deletion: "+songsObs); sonsss.clear(); tableAdded.getItems().clear(); System.out.println("ss Observable list after deletion deletion: "+songsObs); } } @FXML void viewPlaylists(ActionEvent event) { PlaylistSingleton playlistSingleton = PlaylistSingleton.getInstance(); try { Node node = (Node) event.getSource(); Stage stage = (Stage) node.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("../OnlinemusicstoreFxml/userPlaylists.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); } catch (Exception e){ e.printStackTrace(); } //System.out.println(playlistSingleton.getPlaylist()); } }
package com.dq.police.controller.actions; import com.dq.police.controller.Action; import com.dq.police.helpers.ConstraintsUtil; import com.dq.police.view.View; import lombok.AllArgsConstructor; @AllArgsConstructor public class ExitAction extends Action { private View view; @Override public String execute() { view.setAppRunning(false); return ConstraintsUtil.OPERATION_SUCCESS_MESSAGE; } @Override public String getName() { return "Exit"; } }
package termP; import java.io.BufferedReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class termP { public static void main(String[] args){ MainPanel mp = new MainPanel(); } }
package instruments; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class SaxophoneTest { Saxophone saxophone; @Before public void before(){ saxophone = new Saxophone("Very High", SaxophoneType.TENOR , "brass", "woodwind", "Gold", 100, 200, "phwee"); } @Test public void hasSaxophoneType(){ assertEquals(SaxophoneType.TENOR, saxophone.getSaxophoneType()); } @Test public void hasMarkupPrice(){ assertEquals(100, saxophone.calculateMarkup(), 0.01); } @Test public void canMakeSound(){ assertEquals("phwee", saxophone.play("phwee")); } }
package pet_shop.negocio.beans; import java.time.LocalDateTime; public class Animal { private static long proximoID = 1; private long id; private Pessoa dono; private String nome; private double peso; private String especie; private String raca; private LocalDateTime dataNascimento; public Animal(Pessoa dono, String nome, double peso, String especie, String raca, LocalDateTime dataNascimento) { this.id = proximoID; proximoID++; this.dono = dono; this.nome = nome; this.peso = peso; this.especie = especie; this.raca = raca; this.dataNascimento = dataNascimento; } public long getId() { return id; } public Pessoa getDono() { return dono; } public void setDono(Pessoa dono) { this.dono = dono; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public double getPeso() { return peso; } public void setPeso(double peso) { this.peso = peso; } public String getEspecie() { return especie; } public void setEspecie(String especie) { this.especie = especie; } public String getRaca() { return raca; } public void setRaca(String raca) { this.raca = raca; } public LocalDateTime getDataNascimento() { return dataNascimento; } public void setDataNascimento(LocalDateTime dataNascimento) { this.dataNascimento = dataNascimento; } public String toString() { return "ID: " + this.id + "\nNome: " + this.nome + "\nDono: " +this.dono.getNome() + "\nPeso: " + this.peso + "kg \nEspécie: " + this.especie + "\nRaça: " + this.raca + "\nData de Nascimento: " + this.dataNascimento; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Animal other = (Animal) obj; if (dataNascimento == null) { if (other.dataNascimento != null) return false; } else if (!dataNascimento.equals(other.dataNascimento)) return false; if (dono == null) { if (other.dono != null) return false; } else if (!dono.equals(other.dono)) return false; if (especie == null) { if (other.especie != null) return false; } else if (!especie.equals(other.especie)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (peso != other.peso) return false; if (raca == null) { if (other.raca != null) return false; } else if (!raca.equals(other.raca)) return false; return true; } }
package 연습장; import java.util.Scanner; public class 사용자입력받기 { public static void main(String[] args) { for (int i = 0; i < 10; i++) { Scanner s = new Scanner(System.in); System.out.println("아무 숫자나 입력하세요"); int userinput = s.nextInt(); System.out.println("한번 더 아무 숫자나 입력하세요"); int userinput1 = s.nextInt(); System.out.println("당신이 입력한 숫자는 " + userinput + " / " + userinput1 + " 입니다"); System.out.println("\n어떤 계산을 수행하시겠습니까?\n" + "1.더하기 2.곱하기 3.나누기 4.그만하기"); int userinput2 = s.nextInt(); 메소드페이지 Method = new 메소드페이지(); if (userinput2 == 1) { Method.Sum(userinput, userinput1); } else if (userinput2 == 2) { Method.Multi(userinput, userinput1); } else if (userinput2 == 3) { Method.Division(userinput, userinput1); } else if (userinput2 == 4) { System.out.println("프로그램을 종료합니다"); break; } else { System.out.println("잘못 입력 하셨습니다\n"); } } } }
package com._520it.wms.web.action; import com._520it.wms.query.ClientQueryObject; import com._520it.wms.query.OrderBillChartQueryObject; import com._520it.wms.query.SaleChartQueryObject; import com._520it.wms.service.IBrandService; import com._520it.wms.service.IChartService; import com._520it.wms.service.IClientService; import com._520it.wms.service.ISupplierService; import com.alibaba.fastjson.JSON; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by 123 on 2017/8/8. */ // 处理所有的报表的请求 public class ChartAction extends BaseAction { @Setter private IChartService chartService; @Setter private ISupplierService supplierService; @Setter private IBrandService brandService; @Setter private IClientService clientService; @Getter private OrderBillChartQueryObject qo = new OrderBillChartQueryObject(); @Getter private SaleChartQueryObject sqo = new SaleChartQueryObject(); public String orderChart() { put("listData",chartService.orderBillChart(qo)); put("groupTypes",OrderBillChartQueryObject.GROUP_BY_TYPES); put("suppliers",supplierService.list()); put("brands",brandService.list()); return "orderChart"; } public String saleChart(){ put("groupTypes",SaleChartQueryObject.GROUP_BY_TYPES); put("clients",clientService.list()); put("brands",brandService.list()); put("listData",chartService.saleChart(sqo)); return "saleChart"; } // 销售报表柱状图 public String saleChartByBar(){ put("groupTypes",SaleChartQueryObject.GROUP_BY_TYPES); put("clients",clientService.list()); put("brands",brandService.list()); List<Map<String, Object>> list = chartService.saleChart(sqo); put("listData",list); // 分组的类型 List<Object> groupByTypeList = new ArrayList<>(); // 对应的销售额 List<Object> totalAmountList = new ArrayList<>(); for (Map<String, Object> map : list) { groupByTypeList.add(map.get("groupByType")); totalAmountList.add(map.get("totalAmount")); } // 当前分组类型中的数据 put("groupByTypeList", JSON.toJSONString(groupByTypeList)); // 当前分组类型对应的数据 put("totalAmountList", JSON.toJSONString(totalAmountList)); // 当前分组类型 put("groupType",SaleChartQueryObject.GROUP_BY_TYPES.get(sqo.getGroupByType())); return "saleChartByBar"; } // 销售报表柱饼图 public String saleChartByPie(){ put("groupTypes",SaleChartQueryObject.GROUP_BY_TYPES); put("clients",clientService.list()); put("brands",brandService.list()); List<Map<String, Object>> list = chartService.saleChart(sqo); put("listData",list); // 分组的类型 List<Object> groupByTypeList = new ArrayList<>(); // 分组的类型和数据 List<Map<String,Object>> dataList = new ArrayList<>(); BigDecimal maxAmount = BigDecimal.ZERO; for (Map<String, Object> map : list) { groupByTypeList.add(map.get("groupByType")); Map<String,Object> dataMap = new HashMap(); dataList.add(dataMap); dataMap.put("value",map.get("totalAmount")); dataMap.put("name",map.get("groupByType")); BigDecimal totalAmount = (BigDecimal) map.get("totalAmount"); if (maxAmount.compareTo(totalAmount) <= 0) { maxAmount = totalAmount; } } put("maxAmount",maxAmount); // 当前分组类型中的数据 put("groupByTypeList", JSON.toJSONString(groupByTypeList)); // 分组类型和数据 put("dataList", JSON.toJSONString(dataList)); // 当前分组类型 put("groupType",SaleChartQueryObject.GROUP_BY_TYPES.get(sqo.getGroupByType())); return "saleChartByPie"; } }
package com.moviee.moviee.activities; import android.animation.ValueAnimator; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.RelativeLayout; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.moviee.moviee.ApiStrings.DatabaseStrings; import com.moviee.moviee.ApiStrings.MovieStrings; import com.moviee.moviee.Interfaces.ServiceCallback; import com.moviee.moviee.R; import com.moviee.moviee.activities.base.AdActivity; import com.moviee.moviee.adapters.FilmViewPagerAdapter; import com.moviee.moviee.fragments.FilmFragment; import com.moviee.moviee.interpolators.Ease; import com.moviee.moviee.models.Movie; import com.moviee.moviee.services.FilmSharedIO; import com.moviee.moviee.services.TheMovieDB; import com.moviee.moviee.views.NonSwipeableViewPager; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class FilmActivity extends AdActivity { @BindView(R.id.frameLoading) View mLoadingFrame; @BindView(R.id.FilmList) ImageButton mList; @BindView(R.id.view_pager) NonSwipeableViewPager mMainViewPager; private List<Movie> mMovies = new ArrayList<>(); private LinkedHashMap<String, String> hash = new LinkedHashMap<>(); private String[] keys = {DatabaseStrings.FIELD_ACTOR_ID, DatabaseStrings.FIELD_FINAL_DATE, DatabaseStrings.FIELD_GENRE_ID, DatabaseStrings.FIELD_INITIAL_DATE, DatabaseStrings.FIELD_RATE, DatabaseStrings.FIELD_SIMILAR_TO, DatabaseStrings.FIELD_ORDER}; private FilmViewPagerAdapter mAdapter; private float scrollPosition = 0f; private int position = 0; private int currentPage = 1; private int lastAdPage = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_film); ButterKnife.bind(this); mLoadingFrame.setVisibility(View.VISIBLE); //Get passed informations and parse it Intent intent = getIntent(); for(int i = 0; i < keys.length; i++){ if(intent.hasExtra(keys[i])) hash.put(keys[i], intent.getStringExtra(keys[i])); } //Load all films and set adapter to viewpager new TheMovieDB(new ServiceCallback<Movie>() { @Override public void onResponse(List<Movie> list) { mMovies = list; removeDuplicates(mMovies); runOnUiThread(new Runnable() { @Override public void run() { if(mMovies == null || (mMovies.size() == 0 && currentPage < 5)) { finish(); } Intent intent = getIntent(); intent.setClass(getApplicationContext(), ListOfMoviesActivity.class); buildIntent(intent); startActivityForResult(intent, 88); //And finally, animations final ValueAnimator animator = ValueAnimator.ofInt(mLoadingFrame.getMeasuredHeight(), 0); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mLoadingFrame.getLayoutParams(); params.height = (int) animation.getAnimatedValue(); mLoadingFrame.setLayoutParams(params); } }); animator.setDuration(800).setInterpolator(new Ease()); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // Do something after 5s = 500 FilmFragment fragment1 = new FilmFragment(); buildFragment(fragment1, 0); FilmFragment fragment2 = new FilmFragment(); buildFragment(fragment2, 1); mAdapter = new FilmViewPagerAdapter(getSupportFragmentManager(), fragment1, fragment2); mMainViewPager.setAdapter(mAdapter); animator.start(); } }, 1000); } }); } }, getApplicationContext()).getMovieByFilter(hash, currentPage + ""); } @OnClick(R.id.FilmNext) public void nextFilm(){ try { loadTwoNextFilms(mMainViewPager.getCurrentItem()); mMainViewPager.setCurrentItem(mMainViewPager.getCurrentItem() + 1, true); } catch (Exception exd) { } } @OnClick(R.id.FilmPrevious) public void previousFilm(){ if(mMainViewPager.getCurrentItem() != 0) { mMainViewPager.setCurrentItem(mMainViewPager.getCurrentItem() - 1, true); } } @OnClick(R.id.FilmList) public void viewFilmList(){ Intent intent = getIntent(); intent.setClass(this, ListOfMoviesActivity.class); buildIntent(intent); startActivityForResult(intent, 88); } private void buildFragment(Fragment fragment, int position) { try { Bundle args = new Bundle(); Movie actual = mMovies.get(position); String genre = new FilmSharedIO(getApplicationContext()).getGenreById(actual.genre, getApplicationContext()); args.putString(MovieStrings.FIELD_DATE, actual.releaseDate); args.putString(MovieStrings.FIELD_DESCRIPTION, actual.generalInfo); args.putString(MovieStrings.FIELD_GENRE, genre); args.putString(MovieStrings.FIELD_ID, actual.id); args.putString(MovieStrings.FIELD_IMAGE, actual.urlImage); args.putString(MovieStrings.FIELD_RATE, actual.rating); args.putString(MovieStrings.FIELD_TITLE, actual.name); fragment.setArguments(args); } catch (Exception e){ e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 88){ Type type = new TypeToken<ArrayList<Movie>>(){}.getType(); if(resultCode == RESULT_CANCELED){ mMovies = new Gson().fromJson(data.getStringExtra("movies"), type); scrollPosition = data.getFloatExtra("yposition", 0f); }else{ mMovies = new Gson().fromJson(data.getStringExtra("movies"), type); scrollPosition = data.getFloatExtra("yposition", 0f); position = data.getIntExtra("index", 0); int actual = mMainViewPager.getCurrentItem(); while(position > actual) { loadTwoNextFilms(actual); actual += 2; } mMainViewPager.setCurrentItem(position, true); } } } private void buildIntent(Intent intent){ intent.putExtra("movies", new Gson().toJson(mMovies)); intent.putExtra("index", position); intent.putExtra("yposition", scrollPosition); } private void loadTwoNextFilms(int fromCurrentIndex){ if(fromCurrentIndex < mMovies.size()) { if ((mMovies.size() - 1) - fromCurrentIndex == 10) { //Load new page downloadFilms(); } if (fromCurrentIndex + 1 == mAdapter.getCount() - 1) { loadFilms(2, fromCurrentIndex + 1); } if (fromCurrentIndex == mAdapter.getCount() - 1) { loadFilms(2, fromCurrentIndex); } } } private void downloadFilms(){ //Load all films and add to the list new TheMovieDB(new ServiceCallback<Movie>() { @Override public void onResponse(List<Movie> list) { mMovies.addAll(list); removeDuplicates(mMovies); } }, getApplicationContext()).getMovieByFilter(hash, (currentPage++) + ""); } private void loadFilms(int howMany, int fromCurrentIndex){ for (int i = 0; i < howMany; i++) { FilmFragment fragment = new FilmFragment(); buildFragment(fragment, fromCurrentIndex + (i + 1)); mAdapter.addNewFilm(fragment); } } @Override public void onBackPressed() { SharedPreferences preferences = getSharedPreferences("pref", MODE_PRIVATE); if(preferences.getBoolean("fromList", false)){ Intent intent = getIntent(); intent.setClass(this, ListOfMoviesActivity.class); buildIntent(intent); startActivityForResult(intent, 88); }else { startActivity(new Intent(this, MainActivity.class)); finish(); } } private void removeDuplicates(List<Movie> movies){ for(int i = 0; i < movies.size(); i++){ String savedFilmName = movies.get(i).name; for(int x = 0; x < movies.size(); x++){ if(movies.get(x).name.equals(savedFilmName) && x != i){ movies.remove(x); } } } } }
package com.novakivska.app.homework.homework15; /** * Created by Tas_ka on 5/9/2017. */ public class Furniture { private int furnitureItems; public Furniture (int furnitureItems){ this.furnitureItems = furnitureItems; } public int getFurnitureItems() { return furnitureItems; } }
package br.senac.rn.agenda.model; import lombok.Data; import javax.persistence.*; @Entity @Table(name = "tb_contatos") @Data public class Contato { @Id @Column(name = "con_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "con_nome", nullable = false) private String nome; @Column(name = "con_fone", nullable = false) private String fone; }
package be.openclinic.pharmacy; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.text.SimpleDateFormat; import java.util.Vector; import net.admin.Service; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.system.Debug; import be.mxs.common.util.system.ScreenHelper; import be.openclinic.common.OC_Object; import be.openclinic.common.ObjectReference; public class OperationDocument extends OC_Object { private String type=""; private String sourceuid=""; private String destinationuid=""; private java.util.Date date; private String comment=""; private String reference=""; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSourceuid() { return sourceuid; } public void setSourceuid(String sourceuid) { this.sourceuid = sourceuid; } public Object getSource(){ if(MedwanQuery.getInstance().getConfigString("stockOperationDocumentServiceSources","").indexOf('*'+getType()+'*')>-1){ return Service.getService(sourceuid); } else { return ServiceStock.get(sourceuid); } } public String getSourceName(String language){ String s = ""; if(sourceuid!=null){ if(MedwanQuery.getInstance().getConfigString("stockOperationDocumentServiceSources","").indexOf('*'+getType()+'*')>-1){ Service service = Service.getService(sourceuid); if(service!=null){ s=ScreenHelper.checkString(service.getLabel(language)); } } else { ServiceStock serviceStock= ServiceStock.get(sourceuid); if(serviceStock!=null){ s= ScreenHelper.checkString(serviceStock.getName()); } } } return s; } public String getDestinationuid() { return destinationuid; } public void setDestinationuid(String destinationuid) { this.destinationuid = destinationuid; } public ServiceStock getDestination(){ return ServiceStock.get(destinationuid); } public java.util.Date getDate() { return date; } public void setDate(java.util.Date date) { this.date = date; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public static OperationDocument get(String documentUid){ OperationDocument document = null; PreparedStatement ps = null; ResultSet rs = null; if(documentUid!=null && documentUid.split("\\.").length>1){ Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ String sSelect = "SELECT * FROM OC_PRODUCTSTOCKOPERATIONDOCUMENTS"+ " WHERE OC_DOCUMENT_SERVERID = ? AND OC_DOCUMENT_OBJECTID = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(documentUid.substring(0,documentUid.indexOf(".")))); ps.setInt(2,Integer.parseInt(documentUid.substring(documentUid.indexOf(".")+1))); rs = ps.executeQuery(); // get data from DB if(rs.next()){ document=new OperationDocument(); document.setUid(documentUid); document.setType(rs.getString("OC_DOCUMENT_TYPE")); document.setSourceuid(rs.getString("OC_DOCUMENT_SOURCEUID")); document.setDestinationuid(rs.getString("OC_DOCUMENT_DESTINATIONUID")); document.setDate(rs.getTimestamp("OC_DOCUMENT_DATE")); document.setComment(rs.getString("OC_DOCUMENT_COMMENT")); document.setReference(rs.getString("OC_DOCUMENT_REFERENCE")); } } catch(Exception e){ if(e.getMessage().endsWith("NOT FOUND")){ Debug.println(e.getMessage()); } else{ e.printStackTrace(); } } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } return document; } public Vector getProductStockOperations(){ PreparedStatement ps = null; ResultSet rs = null; String sSelect; Vector operations = new Vector(); Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); try { sSelect="select * from OC_PRODUCTSTOCKOPERATIONS where OC_OPERATION_DOCUMENTUID=? order by OC_OPERATION_DATE,OC_OPERATION_OBJECTID"; ps = conn.prepareStatement(sSelect); ps.setString(1, this.getUid()); rs=ps.executeQuery(); ProductStockOperation operation = null; while(rs.next()){ operation = new ProductStockOperation(); operation.setUid(rs.getString("OC_OPERATION_SERVERID")+"."+rs.getString("OC_OPERATION_OBJECTID")); operation.setDescription(rs.getString("OC_OPERATION_DESCRIPTION")); operation.setDate(rs.getDate("OC_OPERATION_DATE")); operation.setUnitsChanged(rs.getInt("OC_OPERATION_UNITSCHANGED")); operation.setProductStockUid(rs.getString("OC_OPERATION_PRODUCTSTOCKUID")); operation.setPrescriptionUid(rs.getString("OC_OPERATION_PRESCRIPTIONUID")); // sourceDestination (Patient|Med|Service) ObjectReference sourceDestination = new ObjectReference(); sourceDestination.setObjectType(rs.getString("OC_OPERATION_SRCDESTTYPE")); sourceDestination.setObjectUid(rs.getString("OC_OPERATION_SRCDESTUID")); operation.setSourceDestination(sourceDestination); // OBJECT variables operation.setCreateDateTime(rs.getTimestamp("OC_OPERATION_CREATETIME")); operation.setUpdateDateTime(rs.getTimestamp("OC_OPERATION_UPDATETIME")); operation.setUpdateUser(ScreenHelper.checkString(rs.getString("OC_OPERATION_UPDATEUID"))); operation.setVersion(rs.getInt("OC_OPERATION_VERSION")); operation.setBatchUid(rs.getString("OC_OPERATION_BATCHUID")); operation.setOrderUID(rs.getString("OC_OPERATION_ORDERUID")); operation.setOperationUID(rs.getString("OC_OPERATION_UID")); operation.setReceiveComment(rs.getString("OC_OPERATION_RECEIVECOMMENT")); operation.setUnitsReceived(rs.getInt("OC_OPERATION_UNITSRECEIVED")); operation.setReceiveProductStockUid(rs.getString("OC_OPERATION_RECEIVEPRODUCTSTOCKUID")); operation.setDocumentUID(rs.getString("OC_OPERATION_DOCUMENTUID")); operations.add(operation); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); conn.close(); } catch(SQLException se){ se.printStackTrace(); } } return operations; } public static Vector find(String type,String source, String destination, String mindate, String maxdate, String reference, String order){ PreparedStatement ps = null; ResultSet rs = null; String sSelect; Vector documents = new Vector(); String sWhere=""; if(type!=null && type.length()>0){ sWhere+=" AND OC_DOCUMENT_TYPE=?"; } if(source!=null && source.length()>0){ sWhere+=" AND OC_DOCUMENT_SOURCEUID=?"; } if(destination!=null && destination.length()>0){ sWhere+=" AND OC_DOCUMENT_DESTINATIONUID=?"; } if(mindate!=null && mindate.length()>0){ sWhere+=" AND OC_DOCUMENT_DATE>=?"; } if(maxdate!=null && maxdate.length()>0){ sWhere+=" AND OC_DOCUMENT_DATE<=?"; } if(reference!=null && reference.length()>0){ sWhere+=" AND OC_DOCUMENT_REFERENCE=?"; } if(sWhere.length()>0){ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); try { if(order==null || order.length()==0){ order= "OC_DOCUMENT_DATE"; } sSelect="SELECT * from OC_PRODUCTSTOCKOPERATIONDOCUMENTS where 1=1"+sWhere+" ORDER by "+order; ps=conn.prepareStatement(sSelect); int i=1; if(type!=null && type.length()>0){ ps.setString(i++, type); } if(source!=null && source.length()>0){ ps.setString(i++, source); } if(destination!=null && destination.length()>0){ ps.setString(i++, destination); } if(mindate!=null && mindate.length()>0){ ps.setDate(i++, new java.sql.Date(ScreenHelper.parseDate(mindate).getTime())); } if(maxdate!=null && maxdate.length()>0){ ps.setDate(i++, new java.sql.Date(ScreenHelper.parseDate(maxdate).getTime())); } if(reference!=null && reference.length()>0){ ps.setString(i++, reference); } rs=ps.executeQuery(); while(rs.next()){ OperationDocument document = new OperationDocument(); document.setUid(rs.getString("OC_DOCUMENT_SERVERID")+"."+rs.getString("OC_DOCUMENT_OBJECTID")); document.setType(rs.getString("OC_DOCUMENT_TYPE")); document.setSourceuid(rs.getString("OC_DOCUMENT_SOURCEUID")); document.setDestinationuid(rs.getString("OC_DOCUMENT_DESTINATIONUID")); document.setDate(rs.getTimestamp("OC_DOCUMENT_DATE")); document.setComment(rs.getString("OC_DOCUMENT_COMMENT")); document.setReference(rs.getString("OC_DOCUMENT_REFERENCE")); documents.add(document); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } return documents; } public void store(){ PreparedStatement ps = null; ResultSet rs = null; String sSelect; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ if(this.getUid()==null || this.getUid().indexOf(".")<0 || this.getUid().equals("-1")){ //***** INSERT ***** sSelect = "INSERT INTO OC_PRODUCTSTOCKOPERATIONDOCUMENTS (OC_DOCUMENT_SERVERID, OC_DOCUMENT_OBJECTID,"+ " OC_DOCUMENT_TYPE, OC_DOCUMENT_SOURCEUID, OC_DOCUMENT_DESTINATIONUID,"+ " OC_DOCUMENT_DATE, OC_DOCUMENT_COMMENT, OC_DOCUMENT_REFERENCE)"+ " VALUES(?,?,?,?,?,?,?,?)"; ps = oc_conn.prepareStatement(sSelect); // set new uid int serverId = MedwanQuery.getInstance().getConfigInt("serverId"); int operationCounter = MedwanQuery.getInstance().getOpenclinicCounter("OC_PRODUCTSTOCKOPERATIONDOCUMENTS"); ps.setInt(1,serverId); ps.setInt(2,operationCounter); this.setUid(serverId+"."+operationCounter); ps.setString(3,this.getType()); ps.setString(4,this.getSourceuid()); ps.setString(5,this.getDestinationuid()); // date if(this.date!=null) ps.setTimestamp(6,new java.sql.Timestamp(this.date.getTime())); else ps.setNull(6,Types.TIMESTAMP); ps.setString(7,this.getComment()); ps.setString(8,this.getReference()); ps.executeUpdate(); } else{ //***** UPDATE ***** sSelect = "UPDATE OC_PRODUCTSTOCKOPERATIONDOCUMENTS SET OC_DOCUMENT_TYPE=?, OC_DOCUMENT_SOURCEUID=?,"+ " OC_DOCUMENT_DESTINATIONUID=?, OC_DOCUMENT_DATE=?, OC_DOCUMENT_COMMENT=?, OC_DOCUMENT_REFERENCE=?"+ " WHERE OC_DOCUMENT_SERVERID=? AND OC_DOCUMENT_OBJECTID=?"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,this.getType()); ps.setString(2,this.getSourceuid()); ps.setString(3,this.getDestinationuid()); // date begin if(this.date!=null) ps.setTimestamp(4,new java.sql.Timestamp(this.date.getTime())); else ps.setNull(4,Types.TIMESTAMP); ps.setString(5,this.getComment()); ps.setString(6,this.getReference()); ps.setInt(7,Integer.parseInt(this.getUid().substring(0,this.getUid().indexOf(".")))); ps.setInt(8,Integer.parseInt(this.getUid().substring(this.getUid().indexOf(".")+1))); ps.executeUpdate(); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } }
/** * Created by Гамзат on 04.06.2017. * * Урок 47 - Идентификатор final */ public class Bender { public static void main(String[] args) { Fry finalObject = new Fry(1); for (int i = 0; i < 50; i++) { finalObject.add(); System.out.printf("%s", finalObject); } } }
package com.beike.util.luncene.rank; import org.apache.lucene.index.FieldInvertState; import org.apache.lucene.search.Similarity; public class QPSimilarty extends Similarity{ /** * */ private static final long serialVersionUID = 7558565500061194774L; /* (non-Javadoc) * @see org.apache.lucene.search.Similarity#coord(int, int) */ @Override public float coord(int overlap, int maxOverlap) { float overlap2 = (float)Math.pow(2, overlap); float maxOverlap2 = (float)Math.pow(2, maxOverlap); return (overlap2 / maxOverlap2); } /** Implemented as * <code>state.getBoost()*lengthNorm(numTerms)</code>, where * <code>numTerms</code> is {@link FieldInvertState#getLength()} if {@link * #setDiscountOverlaps} is false, else it's {@link * FieldInvertState#getLength()} - {@link * FieldInvertState#getNumOverlap()}. * * @lucene.experimental */ @Override public float computeNorm(String field, FieldInvertState state) { /*final int numTerms; if (discountOverlaps) numTerms = state.getLength() - state.getNumOverlap(); else numTerms = state.getLength(); return state.getBoost() * ((float) (1.0 / Math.sqrt(numTerms)));*/ return 1.0f; } /** Implemented as <code>1/sqrt(sumOfSquaredWeights)</code>. */ @Override public float queryNorm(float sumOfSquaredWeights) { // return (float)(1.0 / Math.sqrt(sumOfSquaredWeights)); return 1.0f; } /** Implemented as <code>sqrt(freq)</code>. */ @Override public float tf(float freq) { // return (float)Math.sqrt(freq); return 1.0f; } /** Implemented as <code>1 / (distance + 1)</code>. */ @Override public float sloppyFreq(int distance) { //return 1.0f / (distance + 1); return 1.0f; } /** Implemented as <code>log(numDocs/(docFreq+1)) + 1</code>. */ @Override public float idf(int docFreq, int numDocs) { // return (float)(Math.log(numDocs/(double)(docFreq+1)) + 1.0); return 1.0f; } // Default true protected boolean discountOverlaps = true; /** Determines whether overlap tokens (Tokens with * 0 position increment) are ignored when computing * norm. By default this is true, meaning overlap * tokens do not count when computing norms. * * @lucene.experimental * * @see #computeNorm */ public void setDiscountOverlaps(boolean v) { discountOverlaps = v; } /** @see #setDiscountOverlaps */ public boolean getDiscountOverlaps() { return discountOverlaps; } }
package com.encdata.corn.niblet.dto.keycloak.roles; import java.util.List; /** * Copyright (c) 2015-2017 Enc Group * * @Description keycloak私有角色元素 * @Author Siwei Jin * @Date 2018/10/25 15:48 */ public class KeycloakClientRoleElementDto { private String id; private String client; private List<PublicRolesDto> mappings; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } public List<PublicRolesDto> getMappings() { return mappings; } public void setMappings(List<PublicRolesDto> mappings) { this.mappings = mappings; } }
package mb.tianxundai.com.toptoken.fgt; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; import butterknife.Unbinder; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.base.BaseFgt; import mb.tianxundai.com.toptoken.interfaces.Layout; @Layout(R.layout.fgt_community) public class CommunityFgt extends BaseFgt { Unbinder unbinder; public CommunityFgt() { } @Override public void initViews() { unbinder = ButterKnife.bind(this, rootView); } /** * 每次fragment可见时 * <p> * 请求接口 */ @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { } else { // 不可见时不执行操作 } } @Override public void initDatas() { } @Override public void setEvents() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view View rootView = super.onCreateView(inflater, container, savedInstanceState); unbinder = ButterKnife.bind(this, rootView); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } }
package cmc.vn.ejbca.RA.service; import cmc.vn.ejbca.RA.dto.respond.*; import cmc.vn.ejbca.RA.response.ResponseObject; import cmc.vn.ejbca.RA.response.ResponseStatus; import cmc.vn.ejbca.RA.util.Units; import org.bouncycastle.util.encoders.Base64; import org.cesecore.keys.util.KeyTools; import org.cesecore.util.CertTools; import org.cesecore.util.CryptoProviderTools; import org.ejbca.core.protocol.ws.client.gen.*; import org.ejbca.core.protocol.ws.common.KeyStoreHelper; import org.springframework.web.multipart.MultipartFile; import javax.xml.namespace.QName; import java.beans.XMLDecoder; import java.io.*; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.KeyPair; import java.security.Security; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class WebService { public String pathFileP12 = "src\\p12\\superadmin.p12"; public String pathFileTrustStore = "src\\p12\\truststore.jks"; public String passwordP12 = ""; //if upload a wrong P12 password at the first time, we cannot connect with another visit, we have to restart server public String passwordTrustStore = ""; /** * Connect to Web Server * Follow: https://download.primekey.com/docs/EJBCA-Enterprise/6_15_2/Web_Service_Interface.html **/ public EjbcaWS connectService(String urlstr, String truststore, String passTruststore, String superadmin, String passSuperadmin) throws Exception { try { // System.out.println("truststore: "+ truststore); // System.out.println("passTruststore: " + passTruststore); // System.out.println("superadmin: " + superadmin); // System.out.println("passSuperadmin: " + passSuperadmin); CryptoProviderTools.installBCProvider(); System.setProperty("javax.net.ssl.trustStore", truststore); System.setProperty("javax.net.ssl.trustStorePassword", passTruststore); System.setProperty("javax.net.ssl.keyStore", superadmin); System.setProperty("javax.net.ssl.keyStorePassword", passSuperadmin); QName qname = new QName("http://ws.protocol.core.ejbca.org/", "EjbcaWSService"); EjbcaWSService service = new EjbcaWSService(new URL(urlstr), qname); return service.getEjbcaWSPort(); } catch (Exception exc) { System.err .println("*** Could not connect to non-authenticated web service"); System.out.println(exc); return null; } } //write file to path file (address file) private static void writeToFile(byte[] data, String file) throws FileNotFoundException, IOException { try (FileOutputStream out = new FileOutputStream(file)) { out.write(data); } } //Delete file with path file private static boolean deleteToFile(String file) { File path = new File(file); return path.delete(); } /** * Create connect RA Server to CA Server **/ public ResponseObject<?> connectRAtoCAServer(MultipartFile fileP12, String passwordP12, MultipartFile fileTrustStore, String passwordTrustStore) { ResponseObject<?> res = new ResponseObject<>(true, ResponseStatus.DO_SERVICE_SUCCESSFUL); try { //save files and passwords to CA server writeToFile(fileTrustStore.getBytes(), pathFileTrustStore); writeToFile(fileP12.getBytes(), pathFileP12); this.passwordP12 = passwordP12; this.passwordTrustStore = passwordTrustStore; } catch (Exception exception) { System.out.println("Cannot save file and password"); return new ResponseObject<>(false, ResponseStatus.UNHANDLED_ERROR, exception.getMessage()); } return res; } /** * Create connect RA Server to CA Server **/ public ResponseObject<?> disConnectRAtoCAServer() { ResponseObject<Boolean> res = new ResponseObject<>(true, ResponseStatus.DO_SERVICE_SUCCESSFUL); this.passwordP12 = ""; this.passwordTrustStore = ""; if (deleteToFile(pathFileTrustStore) && deleteToFile(pathFileP12)) { res.setData(true); return res; } res.setData(false); return res; } /** * Get Available CAs **/ public ResponseObject<List<AvailableCADto>> getAvailableCA(EjbcaWS ejbcaraws) throws Exception { ResponseObject<List<AvailableCADto>> res = new ResponseObject<>(true, ResponseStatus.DO_SERVICE_SUCCESSFUL); List<AvailableCADto> availableCAList = new ArrayList<AvailableCADto>(); System.out.println("\n\n"); // if no AvailableCA be getted if (ejbcaraws.getAvailableCAs().isEmpty()) { System.out.println("No Available CAs"); res.setData(null); } else { try { for (NameAndId i : ejbcaraws.getAvailableCAs() ) { // add AvailableCA to list availableCAList.add(new AvailableCADto(i.getName(), i.getId())); } res.setData(availableCAList); } catch (Exception e) { return new ResponseObject<>(false, ResponseStatus.UNHANDLED_ERROR, e.getMessage()); } } // return list AvailableCA (even null) return res; } public Object objectFromXML(byte[] data) { XMLDecoder d = new XMLDecoder(new BufferedInputStream(new ByteArrayInputStream(data))); Object result = d.readObject(); d.close(); return result; } /** * Get Profile By Id **/ public ResponseObject<Object> getProfileById(EjbcaWS ejbcaraws, String idString, String type) throws Exception { ResponseObject<Object> res = new ResponseObject<>(true, ResponseStatus.DO_SERVICE_SUCCESSFUL); try { // System.out.println(objectFromXML(ejbcaraws.getProfile(1052712113, "cp"))); // System.out.println(objectFromXML(ejbcaraws.getProfile(1078345796, "cp"))); // System.out.println(objectFromXML(ejbcaraws.getProfile(787145346, "eep"))); int idInt = Integer.parseInt(idString); //cp for get certificate profile //eep for get end entity profile res.setData(objectFromXML(ejbcaraws.getProfile(idInt, type))); } catch (Exception e) { return new ResponseObject<>(false, ResponseStatus.UNHANDLED_ERROR, e.getMessage()); } //return list End Entity (even null) return res; } /** * Get End Entity Profile **/ public ResponseObject<List<EndEntityListDto>> getEndEntity(EjbcaWS ejbcaraws) throws Exception { ResponseObject<List<EndEntityListDto>> res = new ResponseObject<>(true, ResponseStatus.DO_SERVICE_SUCCESSFUL); System.out.println("\n\n"); List<EndEntityListDto> endEntityList = new ArrayList<EndEntityListDto>(); // if get no Authorized End Entity Profiles if (ejbcaraws.getAuthorizedEndEntityProfiles().isEmpty()) { System.out.println("No End Entity Profile"); res.setData(null); } else { try { for (NameAndId i : ejbcaraws.getAuthorizedEndEntityProfiles() ) { // add list endEntityList.add(new EndEntityListDto( i.getName(), //name i.getId(), //id availableCA(ejbcaraws.getAvailableCAsInProfile(i.getId())), //list Certificate Profiles availableCP(ejbcaraws.getAvailableCertificateProfiles(i.getId())) //list CAs Profiles )); } res.setData(endEntityList); } catch (Exception e) { return new ResponseObject<>(false, ResponseStatus.UNHANDLED_ERROR, e.getMessage()); } } //return list End Entity (even null) return res; } public List<CPsDto> availableCP(List<NameAndId> available) { List<CPsDto> cPsList = new ArrayList<CPsDto>(); if (available.isEmpty()) { System.out.println("No Available Certificate Profiles"); } else { for (NameAndId i : available ) { //Add list cPsList.add(new CPsDto(i.getName(), i.getId())); } } //return list Certificate Profiles (even null) return cPsList; } public List<CAsDto> availableCA(List<NameAndId> available) { List<CAsDto> cAsList = new ArrayList<CAsDto>(); if (available.isEmpty()) { System.out.println("No Available CAs Profiles"); } else { for (NameAndId i : available ) { //Add list cAsList.add(new CAsDto(i.getName(), i.getId())); } } //return list CAs (even null) return cAsList; } /** * Soft token request **/ public org.ejbca.core.protocol.ws.client.gen.KeyStore softTokenRequest(EjbcaWS ejbcaraws, UserDataVOWS userData, String hardTokenSN, String keyspec, String keyalg) throws Exception { try { KeyStore keyStore = ejbcaraws.softTokenRequest(userData, hardTokenSN, keyspec, keyalg); // System.out.println("\n\n"); // System.out.println("Soft Token Request: \n" + new String(keyStore.getKeystoreData(), StandardCharsets.UTF_8)); return keyStore; } catch (EjbcaException_Exception e) { e.printStackTrace(); throw e; } } /** * Certificate Response **/ CertificateResponse certificateRequest(EjbcaWS ejbcaraws, org.bouncycastle.pkcs.PKCS10CertificationRequest requestData, UserDataVOWS userData, int requestType, String hardTokenSN, String responseType) throws Exception { try { CertificateResponse certenv = ejbcaraws.certificateRequest(userData, new String(Base64.encode(requestData.getEncoded())), requestType, hardTokenSN, responseType); return certenv; } catch (Exception e) { e.printStackTrace(); throw e; } } public CertificateResponse certificateRequestFromP10(EjbcaWS ejbcaraws, org.bouncycastle.jce.PKCS10CertificationRequest requestData, String userName, String password, String hardTokenSN, String responseType) throws Exception { try { CertificateResponse certenv = ejbcaraws.pkcs10Request(userName, password, new String(Base64.encode(requestData.getEncoded())), hardTokenSN, responseType); return certenv; } catch (Exception e) { e.printStackTrace(); throw e; } } public CertificateResponse certificateRequestFromFile(EjbcaWS ejbcaraws, MultipartFile fileRequest, UserDataVOWS userData, int requestType, String hardTokenSN, String responseType) throws Exception { //Declare Function Units Units units = new Units(); //Read file request byte[] request = fileRequest.getBytes(); //Convest file to String String requestText = new String(request, StandardCharsets.UTF_8); //Convest to PKCS10 Certification Request org.bouncycastle.pkcs.PKCS10CertificationRequest requestData = units.convertPemToPKCS10CertificationRequest(requestText); try { CertificateResponse certenv = certificateRequest(ejbcaraws, requestData, userData, requestType, hardTokenSN, responseType); return certenv; } catch (Exception e) { e.printStackTrace(); throw e; } } // void showCertificateRespond(CertificateResponse certificateResponse) throws Exception { // String caString = new String(certificateResponse.getData(), StandardCharsets.UTF_8); // System.out.println("\n\n"); // System.out.println("Certificate response: \n" + caString); // System.out.println(certificateResponse.getCertificate().getIssuerX500Principal().getName()); // System.out.println(certificateResponse.getCertificate().getSubjectX500Principal().getName()); // } /** * pkcs12Req **/ public org.ejbca.core.protocol.ws.client.gen.KeyStore pkcs12Req(EjbcaWS ejbcaraws, String username, String password, String hardTokenSN, String keyspec, String keyalg) throws Exception { try { KeyStore keyStore = ejbcaraws.pkcs12Req(username, password, hardTokenSN, keyspec, keyalg); // System.out.println("\n\n"); // System.out.println("keyStore Data (P12): \n" + new String(keyStore.getKeystoreData(), StandardCharsets.UTF_8)); return keyStore; } catch (Exception e) { e.printStackTrace(); throw e; } } /** * Generate Server Certificate from P12 **/ public java.security.cert.Certificate certificateFromP12(KeyStore p12Req, String type, String password) throws Exception { try { java.security.KeyStore ks = KeyStoreHelper.getKeyStore(p12Req.getKeystoreData(), type, password); Enumeration<String> en = ks.aliases(); String alias = en.nextElement(); java.security.cert.Certificate certificateP12 = (java.security.cert.Certificate) ks.getCertificate(alias); // System.out.println("\n\n"); // System.out.println("Server Certificate from P12:"); // System.out.println("Encoded : " + String.format("%8s", Integer.toBinaryString(ByteBuffer.wrap(certificateP12.getEncoded()).getInt()))); // System.out.println("Type : " + certificateP12.getType()); // System.out.println("Public Key: " + certificateP12.getPublicKey()); return certificateP12; } catch (Exception e) { e.printStackTrace(); throw e; } } /** * Find Certificate **/ public List<Certificate> findCerts(EjbcaWS ejbcaraws, String username, boolean onlyValid) throws Exception { try { return ejbcaraws.findCerts(username, onlyValid); } catch (Exception e) { e.printStackTrace(); throw e; } } public void showCertificate(List<Certificate> result) { System.out.println("\n\n"); if (result.size() != 0) { for (Certificate i : result) { System.out.println("Certificate : " + i.getCertificate()); System.out.println("CertificateData : \n" + new String(i.getCertificateData(), StandardCharsets.UTF_8)); System.out.println("RawCertificateData : " + String.format("%8s", Integer.toBinaryString(ByteBuffer.wrap(i.getRawCertificateData()).getInt())) .replaceAll(" ", "0")); System.out.println("KeyStore : " + i.getKeyStore()); System.out.println("Type : " + i.getType()); System.out.println("========================================="); } } else { System.out.println("No Certificate for search!"); } } /** * Check Revokation Status **/ RevokeStatus checkRevokationStatus(EjbcaWS ejbcaraws, String issuerDN, String certificateSN) throws Exception { try { return ejbcaraws.checkRevokationStatus(issuerDN, certificateSN); } catch (Exception e) { e.printStackTrace(); throw e; } } public RevokeStatus checkRevokation(EjbcaWS ejbcaraws, Certificate cert) { try { //Generate x509 Certificate X509Certificate x509Cert = (X509Certificate) CertTools .getCertfromByteArray(cert.getRawCertificateData()); RevokeStatus check = checkRevokationStatus(ejbcaraws, x509Cert.getIssuerDN().toString(), CertTools .getSerialNumberAsString(x509Cert)); return check; } catch (Exception e) { e.printStackTrace(); return null; } } String checkReason(int i) { if (i == RevokeStatus.NOT_REVOKED) { return "NOT_REVOKED"; } else if (i == RevokeStatus.REVOKATION_REASON_UNSPECIFIED) { return "REVOKATION_REASON_UNSPECIFIED"; } else if (i == RevokeStatus.REVOKATION_REASON_KEYCOMPROMISE) { return "REVOKATION_REASON_KEYCOMPROMISE"; } else if (i == RevokeStatus.REVOKATION_REASON_CACOMPROMISE) { return "REVOKATION_REASON_CACOMPROMISE"; } else if (i == RevokeStatus.REVOKATION_REASON_AFFILIATIONCHANGED) { return "REVOKATION_REASON_AFFILIATIONCHANGED"; } else if (i == RevokeStatus.REVOKATION_REASON_SUPERSEDED) { return "REVOKATION_REASON_SUPERSEDED"; } else if (i == RevokeStatus.REVOKATION_REASON_CESSATIONOFOPERATION) { return "REVOKATION_REASON_CESSATIONOFOPERATION"; } else if (i == RevokeStatus.REVOKATION_REASON_CERTIFICATEHOLD) { return "REVOKATION_REASON_CERTIFICATEHOLD"; } else if (i == RevokeStatus.REVOKATION_REASON_REMOVEFROMCRL) { return "REVOKATION_REASON_REMOVEFROMCRL"; } else if (i == RevokeStatus.REVOKATION_REASON_PRIVILEGESWITHDRAWN) { return "REVOKATION_REASON_PRIVILEGESWITHDRAWN"; } else { return "REVOKATION_REASON_AACOMPROMISE"; } } /** * Revoke Certificate **/ boolean revokeCert(EjbcaWS ejbcaraws, String issuerDN, String certificateSN, int reason) { try { ejbcaraws.revokeCert(issuerDN, certificateSN, reason); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public boolean revokeCertificate(EjbcaWS ejbcaraws, Certificate cert, int reason) { try { //Generate x509 Certificate X509Certificate x509Cert = (X509Certificate) CertTools .getCertfromByteArray(cert.getRawCertificateData()); return revokeCert(ejbcaraws, x509Cert.getIssuerDN().toString(), CertTools .getSerialNumberAsString(x509Cert), reason); } catch (Exception e) { e.printStackTrace(); return false; } } /** * Generate Keys **/ public KeyPair generateKeys(String keySpec, String keyalgorithmRsa) throws Exception { try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPair keys = KeyTools.genKeys(keySpec, keyalgorithmRsa); // System.out.println("\n\n"); // System.out.println("Private Key: " + keys.getPrivate()); // System.out.println("Public key : " + keys.getPublic()); return keys; } catch (Exception e) { e.printStackTrace(); } return null; } }
package com.huy8895.dictionaryapi.helper.imp; import com.huy8895.dictionaryapi.helper.DictAbstract; import com.huy8895.dictionaryapi.model.enums.HtmlTag; import com.huy8895.dictionaryapi.model.rung.RungWord; import com.huy8895.dictionaryapi.model.word.Category; import com.huy8895.dictionaryapi.model.word.Part; import lombok.extern.slf4j.Slf4j; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Component @Slf4j public class RungDict extends DictAbstract { Connection conn; Document doc; @Autowired public RungDict(@Value("${dictionary.api.rung}") String url) { this.url = url; } @Override public RungWord search(String word) { return connect(word); } private RungWord connect(String word) { RungWord result = new RungWord(); conn = Jsoup.connect(this.url + word); try { doc = conn.get(); Elements content = doc.select("div.mw-content-ltr"); result = getResult(content.select("span:has(font), h2:has(span), h3, h5:not(h5:has(font))")); result.setLinkAudio(doc.select("a.ms-s-icon.btnPlay.startPlay") .attr("data-link")); result.setWord(word); } catch (IOException | CloneNotSupportedException e) { e.printStackTrace(); } return result; } @SuppressWarnings("unchecked") private RungWord getResult(Elements select_pronoun) throws CloneNotSupportedException { RungWord rungWord = new RungWord(); ArrayList<Category> categories = new ArrayList<>(); Category category = new Category(); Part part = new Part(); ArrayList<Part> parts = new ArrayList<>(); ArrayList<String> means = new ArrayList<>(); for (Element element : select_pronoun) { boolean isPronounce = element.tagName() .equals(HtmlTag.SPAN.getTag()); boolean isCategory = element.tagName() .equals(HtmlTag.H2.getTag()); boolean isPart = element.tagName() .equals(HtmlTag.H3.getTag()); boolean isMean = element.tagName() .equals(HtmlTag.H5.getTag()); if (isPronounce) { rungWord.setPronounce(element.text()); } if (isCategory) { if (!parts.isEmpty()) { if (!means.isEmpty()) { part.setMeans((List<String>) means.clone()); means.clear(); parts.add(part.clone()); } category.setParts((List<Part>) parts.clone()); parts.clear(); categories.add(category.clone()); } category.setName(element.text()); } if (isPart) { if (!means.isEmpty()) { part.setMeans((List<String>) means.clone()); means.clear(); parts.add(part.clone()); } part.setType(element.text()); } if (isMean) { means.add(element.text()); } } rungWord.setCategories(categories); return rungWord; } }
package com.leviathan143.craftingutils.common.container; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; public class ContainerIngredientList extends Container { public ContainerIngredientList() { } @Override public boolean canInteractWith(EntityPlayer playerIn) { return true; } }
package object.simulation; import java.util.ArrayList; import java.util.List; public class ResultsData { private List<List<ResultsDataEntry>> data; private List<ResultsDataEntry> current_data; ResultsData() { this.data = new ArrayList<List<ResultsDataEntry>>(); this.current_data = new ArrayList<ResultsDataEntry>(); } public void new_iteration() { data.add(current_data); this.current_data = new ArrayList<ResultsDataEntry>(); } public void insert_data_entry(ResultsDataEntry result) { this.current_data.add(result); } public List<List<ResultsDataEntry>> get_results() { return this.data; } }
public class alfavit { public static void main(String[] args) { char [] rus=new char [32]; //задание русского алфавита char [] eng=new char [26]; //задание английского алфавита char [] rusalf=new char [32]; //замена русского алфавита char [] engalf=new char [26]; //замена английского алфавита for (int i=0; i<rus.length;++i) {rus[i]=(char) (1072+i);} //заполнение алфавита for (int i=0; i<eng.length;++i) {eng[i]=(char) (97+i);} //заполнение алфавита // for (int i=0; i<rusalf.length;++i) {if ((i % 2)==0) {rusalf[i]=(char) (9672+i);} else {rusalf[i]=(char) (5792+i);} } //заполнение моего алфавита for (int i=0; i<engalf.length;++i) {if ((i % 2)==0) {engalf[i]=(char) (5792+i);} else {engalf[i]=(char) (9672+i);} } //заполнение моего алфавита // for (int i=0; i<rusalf.length;++i) {System.out.print(rusalf[i]);} System.out.println(); for (int i=0; i<engalf.length;++i) {System.out.print(engalf[i]);} System.out.println(); for (int i=0; i<rus.length;++i) {System.out.print(rus[i]);} System.out.println(); for (int i=0; i<eng.length;++i) {System.out.print(eng[i]);} } }
/** * Copyright (C) 2008 Atlassian * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.atlassian.theplugin.idea.config.serverconfig; import com.atlassian.connector.intellij.bamboo.BambooServerFacade; import com.atlassian.theplugin.commons.bamboo.BambooPlan; import com.atlassian.theplugin.commons.bamboo.BambooServerData; import com.atlassian.theplugin.commons.cfg.BambooServerCfg; import com.atlassian.theplugin.commons.cfg.ServerId; import com.atlassian.theplugin.commons.cfg.SubscribedPlan; import com.atlassian.theplugin.commons.cfg.UserCfg; import com.atlassian.theplugin.commons.exception.ServerPasswordNotProvidedException; import com.atlassian.theplugin.commons.remoteapi.RemoteApiException; import com.atlassian.theplugin.commons.util.MiscUtil; import com.atlassian.theplugin.idea.ProgressAnimationProvider; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import static java.lang.System.arraycopy; public class BambooPlansForm extends JPanel { private static final int MIN_TIMEZONE_DIFF = -24; private static final int MAX_TIMEZONE_DIFF = 24; private JPanel toolbarPanel; private JCheckBox cbUseFavouriteBuilds; private JButton btUpdate; private JList list; private JPanel rootComponent; private JScrollPane scrollList; private JPanel listPanel; private JPanel plansPanel; private JSpinner spinnerTimeZoneDifference; private final SpinnerModel timezoneOffsetSpinnerModel = new SpinnerNumberModel(0, MIN_TIMEZONE_DIFF, MAX_TIMEZONE_DIFF, 1); private JPanel timezonePanel; private JLabel bambooVersionNumberInfo; private JCheckBox cbShowBranches; private JCheckBox cbMyBranches; private final ProgressAnimationProvider progressAnimation = new ProgressAnimationProvider(); private DefaultListModel model; private boolean isListModified; private Boolean isUseFavourite; private Boolean showBranches; private Boolean myBranchesOnly; private transient BambooServerCfg bambooServerCfg; private static final int NUM_SERVERS = 10; private final Map<ServerId, List<BambooPlanItem>> serverPlans = MiscUtil.buildConcurrentHashMap(NUM_SERVERS); private final transient BambooServerFacade bambooServerFacade; private final BambooServerConfigForm serverPanel; private final UserCfg defaultCredentials; public BambooPlansForm(BambooServerFacade bambooServerFacade, BambooServerCfg bambooServerCfg, final BambooServerConfigForm bambooServerConfigForm, @NotNull UserCfg defaultCredentials) { this.bambooServerFacade = bambooServerFacade; this.bambooServerCfg = bambooServerCfg; this.serverPanel = bambooServerConfigForm; this.defaultCredentials = defaultCredentials; $$$setupUI$$$(); final GridConstraints constraint = new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false); progressAnimation.configure(listPanel, scrollList, constraint); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { int index = list.locationToIndex(e.getPoint()); boolean select = (list.getWidth()/2 - e.getPoint().getX() >= 0); setCheckboxState(index, select, !select); } }); list.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { int index = list.getSelectedIndex(); // boolean select = list.getComponentAt(e.getPoint()).getName().equals(PlanListCellRenderer.GROUP_NAME); // setCheckboxState(index, select, !select); } } }); cbUseFavouriteBuilds.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setEnabled(!cbUseFavouriteBuilds.isSelected()); } }); btUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refreshServerPlans(); } }); spinnerTimeZoneDifference.setModel(timezoneOffsetSpinnerModel); bambooVersionNumberInfo.setEnabled(false); bambooVersionNumberInfo.setEnabled(true); } private void refreshServerPlans() { serverPlans.remove(bambooServerCfg.getServerId()); serverPanel.saveData(); BambooServerData.Builder builder = new BambooServerData.Builder(bambooServerCfg); builder.defaultUser(defaultCredentials); bambooServerCfg.setIsBamboo2(bambooServerFacade.isBamboo2(builder.build())); retrievePlans(bambooServerCfg); } private void setCheckboxState(int index, boolean select, boolean group) { if (index != -1 && isEnabled()) { BambooPlanItem pi = (BambooPlanItem) list.getModel().getElementAt(index); if (group) { pi.setGrouped(!pi.isGrouped()); setViewState(index, pi.isGrouped()); if (pi.isGrouped()) { pi.setSelected(true); setViewState(index, pi.isSelected()); } } if (select) { pi.setSelected(!pi.isSelected()); setViewState(index, pi.isSelected()); if (!pi.isSelected()) { pi.setGrouped(false); setViewState(index, pi.isSelected()); } } repaint(); setModifiedState(); } } private void setViewState(int index, boolean newState) { int[] oldIdx = list.getSelectedIndices(); int[] newIdx; if (newState) { newIdx = new int[oldIdx.length + 1]; arraycopy(newIdx, 0, oldIdx, 0, oldIdx.length); newIdx[newIdx.length - 1] = index; } else { newIdx = new int[Math.max(0, oldIdx.length - 1)]; int i = 0; for (int id : oldIdx) { if (id == index) { continue; } newIdx[i++] = id; } } list.setSelectedIndices(newIdx); } private void setModifiedState() { isListModified = false; List<BambooPlanItem> local = serverPlans.get(bambooServerCfg.getServerId()); if (local != null) { for (int i = 0; i < model.getSize(); i++) { if (local.get(i) != null) { if (((BambooPlanItem) model.getElementAt(i)).isSelected() != local.get(i).isSelected()) { isListModified = true; break; } } } } else { isListModified = !model.isEmpty(); } } /** * helper field used to avoid race conditions between thread polling for isModified, * which calls {@link #saveData()} */ private BambooServerCfg currentlyPopulatedServer; private synchronized BambooServerCfg getCurrentlyPopulatedServer() { return currentlyPopulatedServer; } private synchronized void setCurrentlyPopulatedServer(BambooServerCfg bambooServerCfg) { this.currentlyPopulatedServer = bambooServerCfg; } public void setData(final BambooServerCfg serverCfg) { bambooServerCfg = serverCfg; if (bambooServerCfg != null) { int offs = bambooServerCfg.getTimezoneOffset(); offs = Math.min(MAX_TIMEZONE_DIFF, Math.max(MIN_TIMEZONE_DIFF, offs)); timezoneOffsetSpinnerModel.setValue(offs); showBranches = serverCfg.isShowBranches(); myBranchesOnly = serverCfg.isMyBranchesOnly(); cbShowBranches.setSelected(showBranches); cbMyBranches.setSelected(myBranchesOnly); if (bambooServerCfg.getUrl().length() > 0) { retrievePlans(bambooServerCfg); } else { model.removeAllElements(); cbShowBranches.setEnabled(true); cbShowBranches.setSelected(true); cbMyBranches.setEnabled(true); } } } private void retrievePlans(final BambooServerCfg queryServer) { list.setEnabled(false); cbMyBranches.setEnabled(false); cbShowBranches.setEnabled(false); if (isUseFavourite != null) { cbUseFavouriteBuilds.setSelected(isUseFavourite); isUseFavourite = null; } else { cbUseFavouriteBuilds.setSelected(queryServer.isUseFavourites()); } new Thread(new Runnable() { public void run() { progressAnimation.startProgressAnimation(); BambooServerData.Builder builder = new BambooServerData.Builder(bambooServerCfg); builder.defaultUser(defaultCredentials); BambooServerData bambooServerData = builder.build(); bambooServerCfg.setIsBamboo2(bambooServerFacade.isBamboo2(bambooServerData)); final boolean bamboo4 = bambooServerFacade.isBamboo4(bambooServerData); final boolean bamboo5 = bambooServerFacade.isBamboo5(bambooServerData); final StringBuilder msg = new StringBuilder(); try { ServerId key = queryServer.getServerId(); if (!serverPlans.containsKey(key)) { Collection<BambooPlan> plans; try { BambooServerData.Builder b = new BambooServerData.Builder(queryServer); b.defaultUser(defaultCredentials); plans = bambooServerFacade.getPlanList(b.build()); } catch (ServerPasswordNotProvidedException e) { msg.append("Unable to connect: password for server not provided\n"); return; } catch (RemoteApiException e) { msg.append("Unable to connect: "); msg.append(e.getMessage()); msg.append("\n"); return; } List<BambooPlanItem> plansForServer = new ArrayList<BambooPlanItem>(); if (plans != null) { for (BambooPlan plan : plans) { plansForServer.add(new BambooPlanItem(plan, false, false)); } msg.append("Build plans updated from server\n"); } for (SubscribedPlan sPlan : queryServer.getSubscribedPlans()) { boolean exists = false; for (BambooPlanItem bambooPlanItem : plansForServer) { if (bambooPlanItem.getPlan().getKey().equals(sPlan.getKey())) { exists = true; break; } } if (!exists) { BambooPlan p = new BambooPlan(sPlan.getKey(), sPlan.getKey(), null, false, false); plansForServer.add(new BambooPlanItem(p, true, sPlan.isGrouped())); } } msg.append("Build plans updated based on stored configuration"); serverPlans.put(key, plansForServer); } else { msg.append("Build plans updated based on cached values"); } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { if (bamboo4) { cbShowBranches.setEnabled(true); cbMyBranches.setEnabled(bamboo5); } else { cbShowBranches.setSelected(false); cbMyBranches.setSelected(false); } setBambooVersionNumberInfo(queryServer); progressAnimation.stopProgressAnimation(); final String message = msg.toString(); EventQueue.invokeLater(new Runnable() { public void run() { updatePlanNames(queryServer, message); } }); } }); } } }, "atlassian-idea-plugin bamboo panel retrieve plans").start(); } private void setBambooVersionNumberInfo(BambooServerCfg serverCfg) { if (serverCfg.isBamboo2()) { bambooVersionNumberInfo.setEnabled(false); bambooVersionNumberInfo.setVisible(false); bambooVersionNumberInfo.setText(""); } else { bambooVersionNumberInfo.setEnabled(true); bambooVersionNumberInfo.setVisible(true); bambooVersionNumberInfo .setText("Server version number is < 2.0. Some plugin features are disabled (i.e. re-run failed tests)"); } } /** * Synchronizes Bamboo plan view with given data. * Must be run in EDT. * This method is not thread-safe, but I leave it without synchronization, * as it's effective run only in single-threaded way (EDT) * * @param server Bamboo sever for which to update planes * @param message additional message which was built during fetching of data */ private void updatePlanNames(BambooServerCfg server, String message) { if (server.equals(bambooServerCfg)) { setCurrentlyPopulatedServer(null); model.removeAllElements(); List<BambooPlanItem> plans = serverPlans.get(server.getServerId()); if (plans != null) { for (BambooPlanItem plan : plans) { plan.setSelected(false); for (SubscribedPlan sPlan : server.getSubscribedPlans()) { if (sPlan.getKey().equals(plan.getPlan().getKey())) { plan.setSelected(true); plan.setGrouped(sPlan.isGrouped()); break; } } model.addElement(new BambooPlanItem(plan.getPlan(), plan.isSelected(), plan.isGrouped())); } } else { // for those servers for which we cannot fetch metadata, we just show current plans List<BambooPlanItem> modelPlans = MiscUtil.buildArrayList(); for (SubscribedPlan plan : server.getSubscribedPlans()) { final BambooPlanItem bambooPlanItem = new BambooPlanItem(new BambooPlan("Unknown", plan.getKey(), null), true, plan.isGrouped()); model.addElement(bambooPlanItem); modelPlans.add(bambooPlanItem); } serverPlans.put(server.getServerId(), modelPlans); } setVisible(true); // cbUseFavouriteBuilds.setEnabled(true); list.setEnabled(!cbUseFavouriteBuilds.isSelected()); isListModified = false; setCurrentlyPopulatedServer(server); } } /** * This method could theoretically have race conditions with updatePlanNames names above, * as they move play with model. However both methods are run only in single thread (EWT), so race conditions * are not possible. */ public void saveData() { // additional check for getCurrentlyPopulatedServer() is used // to avoid fetching data from list model when it's really not yet representing // our current server if (bambooServerCfg == null || !bambooServerCfg.equals(getCurrentlyPopulatedServer())) { return; } // move data only when we have fetched the data - otherwise we could overwrite user data due to e.g. network problems if (serverPlans.containsKey(bambooServerCfg.getServerId())) { bambooServerCfg.clearSubscribedPlans(); for (int i = 0; i < model.getSize(); ++i) { if (model.getElementAt(i) instanceof BambooPlanItem) { BambooPlanItem p = (BambooPlanItem) model.getElementAt(i); if (p.isSelected()) { SubscribedPlan spb = new SubscribedPlan(p.getPlan().getKey(), p.isGrouped()); bambooServerCfg.getSubscribedPlans().add(spb); } } } } bambooServerCfg.setUseFavourites(cbUseFavouriteBuilds.isSelected()); bambooServerCfg.setShowBranches(cbShowBranches.isSelected()); bambooServerCfg.setMyBranchesOnly(cbMyBranches.isSelected()); bambooServerCfg.setTimezoneOffset(((SpinnerNumberModel) spinnerTimeZoneDifference.getModel()).getNumber().intValue()); } public boolean isModified() { boolean isFavModified = false; if (bambooServerCfg != null) { if (cbUseFavouriteBuilds.isSelected() != bambooServerCfg.isUseFavourites()) { isFavModified = true; } } else { return false; } return isListModified || isFavModified; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); list.setEnabled(enabled); } private void createUIComponents() { model = new DefaultListModel(); list = new JList(model); list.setCellRenderer(new PlanListCellRenderer()); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { createUIComponents(); rootComponent = new JPanel(); rootComponent.setLayout(new GridBagLayout()); plansPanel = new JPanel(); plansPanel.setLayout(new GridBagLayout()); GridBagConstraints gbc; gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; rootComponent.add(plansPanel, gbc); plansPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Build Plans")); listPanel = new JPanel(); listPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); listPanel.setBackground(new Color(-1)); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(0, 12, 0, 12); plansPanel.add(listPanel, gbc); scrollList = new JScrollPane(); scrollList.setBackground(new Color(-1)); listPanel.add(scrollList, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); scrollList.setViewportView(list); toolbarPanel = new JPanel(); toolbarPanel.setLayout(new GridBagLayout()); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 10, 12, 8); plansPanel.add(toolbarPanel, gbc); cbUseFavouriteBuilds = new JCheckBox(); cbUseFavouriteBuilds.setText("Use Favourite Builds For Server"); cbUseFavouriteBuilds.setMnemonic('F'); cbUseFavouriteBuilds.setDisplayedMnemonicIndex(4); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; toolbarPanel.add(cbUseFavouriteBuilds, gbc); btUpdate = new JButton(); btUpdate.setText("Refresh"); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; toolbarPanel.add(btUpdate, gbc); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 12, 12, 12); timezonePanel = new JPanel(); timezonePanel.setLayout(new GridBagLayout()); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1.0; gbc.fill = GridBagConstraints.BOTH; rootComponent.add(timezonePanel, gbc); spinnerTimeZoneDifference = new JSpinner(); spinnerTimeZoneDifference.setMinimumSize(new Dimension(60, 28)); spinnerTimeZoneDifference.setPreferredSize(new Dimension(60, 28)); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; gbc.gridheight = 3; gbc.anchor = GridBagConstraints.WEST; timezonePanel.add(spinnerTimeZoneDifference, gbc); final JLabel label1 = new JLabel(); label1.setText("Time Zone Difference:"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.gridheight = 2; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(0, 12, 0, 12); timezonePanel.add(label1, gbc); final JLabel label2 = new JLabel(); label2.setFont(new Font(label2.getFont().getName(), label2.getFont().getStyle(), 10)); label2.setHorizontalAlignment(0); label2.setHorizontalTextPosition(0); label2.setText("This computer has a time difference of x hours"); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 0; gbc.gridheight = 2; gbc.weightx = 1.0; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(0, 12, 0, 0); timezonePanel.add(label2, gbc); final JLabel label3 = new JLabel(); label3.setFont(new Font(label3.getFont().getName(), label3.getFont().getStyle(), 10)); label3.setHorizontalAlignment(0); label3.setHorizontalTextPosition(0); label3.setText("from the Bamboo server. Positive number denotes"); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 2; gbc.weightx = 1.0; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(0, 12, 0, 0); timezonePanel.add(label3, gbc); final JLabel label4 = new JLabel(); label4.setFont(new Font(label4.getFont().getName(), label4.getFont().getStyle(), 10)); label4.setText("hours ahead, negative number denotes hours behind."); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 3; gbc.weightx = 1.0; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(0, 12, 0, 0); timezonePanel.add(label4, gbc); bambooVersionNumberInfo = new JLabel(); bambooVersionNumberInfo.setEnabled(false); bambooVersionNumberInfo.setFocusTraversalPolicyProvider(true); bambooVersionNumberInfo.setFocusable(false); bambooVersionNumberInfo.setFont(new Font(bambooVersionNumberInfo.getFont().getName(), bambooVersionNumberInfo.getFont().getStyle(), 10)); bambooVersionNumberInfo.setForeground(new Color(-3407872)); bambooVersionNumberInfo.setText(""); bambooVersionNumberInfo.setVisible(true); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 4; gbc.gridwidth = 3; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(4, 12, 4, 0); timezonePanel.add(bambooVersionNumberInfo, gbc); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return rootComponent; } }
package morpion; public class Partie { BigMorpion m = new BigMorpion(); private int last; public Partie() { this.last = -1; } public void tour(Joueur j) { int choix; do { System.out.println("Tour du joueur " + j.getNom()); if (last == -1 || m.getTotal()[last].isFini()) last = j.choixPlateau(); choix = j.choixCase(last); } while (!m.getTotal()[last].addChar(choix, j)); last = choix; } public void tourIA(IA ia) { int choix; do { System.out.println("Tour de l'IA"); if (last == -1 || m.getTotal()[last].isFini()) last = ia.choixPlateauRandom(); choix = ia.choixCaseMorpionSimple(m.getTotal()[last]); } while (!m.getTotal()[last].addChar(choix, ia)); last = choix; } public void start(Joueur j1, Joueur j2) { System.out.println("Début de la partie : " + j1.getNom() + " VS " + j2.getNom()); while (!m.isFini()) { System.out.println(m.toString()); tour(j1); if (!m.isFini()) { System.out.println(m.toString()); tour(j2); } } System.out.println("Fin de la partie"); } public void startIA(Joueur j1, IA ia) { System.out.println("Début de la partie : " + j1.getNom() + " VS IA"); while (!m.isFini()) { System.out.println(m.toString()); tour(j1); if (!m.isFini()) { System.out.println(m.toString()); tourIA(ia); } } System.out.println(m.toString()); System.out.println("Fin de la partie"); } public void checkWinner(Joueur j1, Joueur j2) { char winner = m.getWinner(); if (winner == 'N') System.out.println("égalité"); else if (winner == j1.getMarque()) System.out.println("Le joueur " + j1.getNom() + " a gagné"); else if (winner == j2.getMarque()) System.out.println("Le joueur " + j2.getNom() + " a gagné"); } }
package ru.shikhovtsev.core.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.shikhovtsev.cachehw.HwCache; import ru.shikhovtsev.core.dao.UserDao; import ru.shikhovtsev.core.model.User; import ru.shikhovtsev.core.sessionmanager.SessionManager; import java.util.Optional; public class DbServiceUserImpl implements DBServiceUser { private static Logger logger = LoggerFactory.getLogger(DbServiceUserImpl.class); private final UserDao userDao; private final HwCache<Long, User> cache; public DbServiceUserImpl(UserDao userDao, HwCache<Long, User> cache) { this.userDao = userDao; this.cache = cache; } @Override public Long saveUser(User user) { try (SessionManager sessionManager = userDao.getSessionManager()) { sessionManager.beginSession(); try { long userId = userDao.save(user); sessionManager.commitSession(); logger.info("created user: {}", userId); return userId; } catch (Exception e) { logger.error(e.getMessage(), e); sessionManager.rollbackSession(); throw new DbServiceException(e); } } } @Override public Long updateUser(User user) { try (SessionManager sessionManager = userDao.getSessionManager()) { sessionManager.beginSession(); try { Long id = userDao.update(user); sessionManager.commitSession(); logger.info("updated user: {}", id); cache.remove(user.getId()); return id; } catch (Exception e) { logger.error(e.getMessage(), e); sessionManager.rollbackSession(); throw new DbServiceException(e); } } } @Override public Long createOrUpdate(User user) { try (SessionManager sessionManager = userDao.getSessionManager()) { sessionManager.beginSession(); try { Long id = userDao.createOrUpdate(user); sessionManager.commitSession(); cache.remove(id); return id; } catch (Exception e) { logger.error(e.getMessage(), e); sessionManager.rollbackSession(); throw new DbServiceException(e); } } } @Override public Optional<User> getUser(Long id) { User cached = cache.get(id); if (cached != null) { return Optional.of(cached); } try (SessionManager sessionManager = userDao.getSessionManager()) { sessionManager.beginSession(); try { Optional<User> userOptional = userDao.findById(id); logger.info("user: {}", userOptional.orElse(null)); userOptional.ifPresent(user -> cache.put(id, user)); return userOptional; } catch (Exception e) { logger.error(e.getMessage(), e); sessionManager.rollbackSession(); } return Optional.empty(); } } }
package network.topdown.application.http.protocol; public class GzipUtil { }
package com.acompanhamento.api.service; import com.acompanhamento.api.domain.Terapeuta; import org.springframework.data.domain.Page; public interface TerapeutaService { Terapeuta cadastrarTerapeuta(Terapeuta terapeuta); Terapeuta buscarTerapeutaPorNome(String nome) throws Exception; Terapeuta buscarTerapeutaPorEmail(String email) throws Exception; Terapeuta buscarTerapeutaPeloCrfa(Long crfa) throws Exception; Terapeuta atualizarInformacoes(Terapeuta terapeuta, String email) throws Exception; Page<Terapeuta> listarTerapeutas(Integer page, Integer count); }
package com.asky.backend.service.Iservice; import com.asky.backend.entity.Content; import java.util.List; public interface IContentService { public List<Content> getAllContent(); public Content getContentById(int contentId); public Content insertContent(Content content); public Content updateContent(Content content); }
package com.legaoyi.platform.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonFormat; @Entity(name = "carDevice") @Table(name = "v_car_device") @XmlRootElement public class CarDevice implements Serializable { private static final long serialVersionUID = -8115720901642476217L; public static final String ENTITY_NAME = "carDevice"; @Id @Column(name = "id", length = 32) private String carId; @Column(name = "enterprise_id") private String enterpriseId; /** 部门id **/ @Column(name = "dept_id") private String deptId; /** 分组id **/ @Column(name = "group_id") private String groupId; /** 车载设备id **/ @Column(name = "device_id") private String deviceId; /** 车辆图片id **/ @Column(name = "icon_id") private String iconId; /** 车辆舒适度指数,0~100 **/ @Column(name = "comfort_index") private Integer comfortIndex; /** 状态:0:停用;1:空闲;2:使用中;3:维修中 **/ @Column(name = "state") private Short state = 1; /** 车辆颜色 **/ @Column(name = "color") private Short color; /** 车牌号 **/ @Column(name = "plate_number") private String plateNumber; /** 车牌号类型 **/ @Column(name = "plate_type") private String plateType; /** 车牌颜色 **/ @Column(name = "plate_color") private Short plateColor = 1; /** 生产日期 **/ @Column(name = "production_date") private String productionDate; /** 车架号 **/ @Column(name = "vin") private String vin; /** 发动机号 **/ @Column(name = "engine_no") private String engineNo; /*** 车辆品牌 */ @Column(name = "brand_type") private Short brandType; /*** 品牌型号 */ @Column(name = "brand_model") private Short brandModel; /** 车辆类型 **/ @Column(name = "type") private Short type; /** 核载人数 **/ @Column(name = "seats") private Integer seats = 5; /** 初始里程 **/ @Column(name = "initial_mileage") private Integer initialMileage; /** 油箱容积 **/ @Column(name = "tank_capacity") private Integer tankCapacity; /** 整车质量 **/ @Column(name = "weight") private Integer weight; /** 业务类型 **/ @Column(name = "biz_type") private Integer bizType; /** 年审日期 **/ @Column(name = "verification_date") private String verificationDate; /** 保险到期日期 **/ @Column(name = "insurance_date") private String insuranceDate; /** 购置日期 **/ @Column(name = "acquisition_date") private String acquisitionDate; /** 报废日期 **/ @Column(name = "retirement_date") private String retirementDate; /** 档案编号 **/ @Column(name = "file_no") private String fileNo; /** 行驶证 **/ @Column(name = "driving_license") private String drivingLicense; /** 行驶证到期日期 **/ @Column(name = "driving_lic_date") private String licenseDate; /** 行驶证照片 **/ @Column(name = "driving_lic_img_id") private String licenseImgId; /** 保险公司 **/ @Column(name = "insurance_company") private String insuranceCompany; /** 备注 **/ @Column(name = "remark") private String remark; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_time") protected Date createTime = new Date(); @Column(name = "create_user") private String createUser; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @Temporal(TemporalType.TIMESTAMP) @Column(name = "modify_time") private Date modifyTime; @Column(name = "modify_user") private String modifyUser; /** sim卡号 **/ @Column(name = "sim_code") private String simCode; /** 终端协议版本 **/ @Column(name = "protocol_version") private String protocolVersion; /** 视频协议版本 **/ @Column(name = "vedio_protocol") private String vedioProtocol; /** 视频通道 **/ @Column(name = "vedio_channel") private Integer vedioChannel; /** 设备状态:0:未注册;1:已注册;2:离线;3:在线;4:已注销;5:已停用 **/ @Column(name = "device_state") private Short deviceState; /** 业务状态:0:离线;1:行驶;2:停车;3:熄火;4:无信号 **/ @Column(name = "biz_state") private Short bizState; /** 终端最后上线时间 **/ @Column(name = "last_online_time") private Long lastOnlineTime; /** 终端最后下线时间 **/ @Column(name = "last_offline_time") private Long lastOfflineTime; public String getCarId() { return carId; } public void setCarId(String carId) { this.carId = carId; } public String getEnterpriseId() { return enterpriseId; } public void setEnterpriseId(String enterpriseId) { this.enterpriseId = enterpriseId; } public String getDeptId() { return deptId; } public void setDeptId(String deptId) { this.deptId = deptId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getIconId() { return iconId; } public void setIconId(String iconId) { this.iconId = iconId; } public Integer getComfortIndex() { return comfortIndex; } public void setComfortIndex(Integer comfortIndex) { this.comfortIndex = comfortIndex; } public Short getState() { return state; } public void setState(Short state) { this.state = state; } public Short getColor() { return color; } public void setColor(Short color) { this.color = color; } public String getPlateNumber() { return plateNumber; } public void setPlateNumber(String plateNumber) { this.plateNumber = plateNumber; } public String getPlateType() { return plateType; } public void setPlateType(String plateType) { this.plateType = plateType; } public Short getPlateColor() { return plateColor; } public void setPlateColor(Short plateColor) { this.plateColor = plateColor; } public String getProductionDate() { return productionDate; } public void setProductionDate(String productionDate) { this.productionDate = productionDate; } public String getVin() { return vin; } public void setVin(String vin) { this.vin = vin; } public String getEngineNo() { return engineNo; } public void setEngineNo(String engineNo) { this.engineNo = engineNo; } public Short getBrandType() { return brandType; } public void setBrandType(Short brandType) { this.brandType = brandType; } public Short getBrandModel() { return brandModel; } public void setBrandModel(Short brandModel) { this.brandModel = brandModel; } public Short getType() { return type; } public void setType(Short type) { this.type = type; } public Integer getSeats() { return seats; } public void setSeats(Integer seats) { this.seats = seats; } public Integer getInitialMileage() { return initialMileage; } public void setInitialMileage(Integer initialMileage) { this.initialMileage = initialMileage; } public Integer getTankCapacity() { return tankCapacity; } public void setTankCapacity(Integer tankCapacity) { this.tankCapacity = tankCapacity; } public Integer getWeight() { return weight; } public void setWeight(Integer weight) { this.weight = weight; } public Integer getBizType() { return bizType; } public void setBizType(Integer bizType) { this.bizType = bizType; } public String getVerificationDate() { return verificationDate; } public void setVerificationDate(String verificationDate) { this.verificationDate = verificationDate; } public String getInsuranceDate() { return insuranceDate; } public void setInsuranceDate(String insuranceDate) { this.insuranceDate = insuranceDate; } public String getAcquisitionDate() { return acquisitionDate; } public void setAcquisitionDate(String acquisitionDate) { this.acquisitionDate = acquisitionDate; } public String getRetirementDate() { return retirementDate; } public void setRetirementDate(String retirementDate) { this.retirementDate = retirementDate; } public String getFileNo() { return fileNo; } public void setFileNo(String fileNo) { this.fileNo = fileNo; } public String getDrivingLicense() { return drivingLicense; } public void setDrivingLicense(String drivingLicense) { this.drivingLicense = drivingLicense; } public String getLicenseDate() { return licenseDate; } public void setLicenseDate(String licenseDate) { this.licenseDate = licenseDate; } public String getLicenseImgId() { return licenseImgId; } public void setLicenseImgId(String licenseImgId) { this.licenseImgId = licenseImgId; } public String getInsuranceCompany() { return insuranceCompany; } public void setInsuranceCompany(String insuranceCompany) { this.insuranceCompany = insuranceCompany; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public Date getModifyTime() { return modifyTime; } public void setModifyTime(Date modifyTime) { this.modifyTime = modifyTime; } public String getModifyUser() { return modifyUser; } public void setModifyUser(String modifyUser) { this.modifyUser = modifyUser; } public String getSimCode() { return simCode; } public void setSimCode(String simCode) { this.simCode = simCode; } public String getProtocolVersion() { return protocolVersion; } public void setProtocolVersion(String protocolVersion) { this.protocolVersion = protocolVersion; } public String getVedioProtocol() { return vedioProtocol; } public void setVedioProtocol(String vedioProtocol) { this.vedioProtocol = vedioProtocol; } public Integer getVedioChannel() { return vedioChannel; } public void setVedioChannel(Integer vedioChannel) { this.vedioChannel = vedioChannel; } public Short getDeviceState() { return deviceState; } public void setDeviceState(Short deviceState) { this.deviceState = deviceState; } public Short getBizState() { return bizState; } public void setBizState(Short bizState) { this.bizState = bizState; } public Long getLastOnlineTime() { return lastOnlineTime; } public void setLastOnlineTime(Long lastOnlineTime) { this.lastOnlineTime = lastOnlineTime; } public Long getLastOfflineTime() { return lastOfflineTime; } public void setLastOfflineTime(Long lastOfflineTime) { this.lastOfflineTime = lastOfflineTime; } }
package com.daz.common.publicDict.server; import java.util.List; import java.util.Map; import com.daz.common.publicDict.pojo.publicDictPojo; public interface IPublicDictServer { public List<publicDictPojo> searchPublicDict(Map<String, Object> map)throws Exception; public publicDictPojo searchOnePublicDict(Map<String, Object> map) throws Exception; }
package enem; public class TesteManipulador { public static void main(String[] args) { String path = "F:\\WorkSpace\\Brent\\aluno.db"; IFileOrganizer arq1; //Passo1 - Construção do arquivo base arq1 = new ManipuladorSequencial(path); for (int i=10 ; i>=0; i--){ Aluno a = new Aluno(0, "Aluno"+i, "Rua "+i, (short)00, "M", "aluno"+i+"@ufs.br"); arq1.addReg(a); } //Passo2 - Demonstração do método de Brent [Exemplo do Slide Show - Página 67] arq1 = new OrganizadorBrent(path); Aluno e; e = new Aluno(27,"#27#","*******",(short)00,"M","aluno27@ufs.com.br"); arq1.addReg(e); ///* e = new Aluno(18,"#18#","*******",(short)00,"M","aluno18@ufs.com.br"); arq1.addReg(e); e = new Aluno(29,"#29#","*******",(short)00,"M","aluno29@ufs.com.br"); arq1.addReg(e); e = new Aluno(28,"#28#","*******",(short)00,"M","aluno28@ufs.com.br"); arq1.addReg(e); e = new Aluno(39,"#39#","*******",(short)00,"M","aluno39@ufs.com.br"); arq1.addReg(e); e = new Aluno(13,"#13#","*******",(short)00,"M","aluno13@ufs.com.br"); arq1.addReg(e); e = new Aluno(16,"#16#","*******",(short)00,"M","aluno16@ufs.com.br"); arq1.addReg(e); arq1.delReg(27); //*/ //IFileOrganizer arq1 = new OrganizadorBrent(path); //System.out.println(arq1.getReg(29)); } }
package creational.prototype.bookcode.shape; public class Main { public static void main(String[] args) { Circle c = new Circle(); c.x = 10; c.y = 20; c.color = "red"; c.radius = 2; Circle copy = (Circle) c.clone(); System.out.println(c.equals(copy)); } }
package com.swyrik.kalah.entity; public enum Status { PROCESSING, COMPLETED; }
package org.artifact.security.intercept; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import org.artifact.security.domain.User; /** * 用于登陆成功后返回自定义数据,该接口的实现类须在spring-security.xml中进行配置才能生效 * <p> * 日期:2015年10月30日 * * @version 0.1 * @author Netbug */ public interface LoginSuccessHandler { /** * * <p> * 日期:2015年10月30日 * * @param request * @param user * 当前登录用户信息 * @param result * result的Key建议将实现类路径作为前缀,避免冲突 * @author Netbug */ public void buildLoginSuccessResult(HttpServletRequest request, User user, HashMap<String, Object> result); }
package Problem_15487; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[] arr = new int[N]; int[] ldp = new int[N]; int idx = 0; ldp[0] = (int) -1e9; int rdp = ldp[0]; int ans = ldp[0]; int var_t = Integer.MAX_VALUE; String Buffer = br.readLine(); for(String s : Buffer.split(" ")) { arr[idx] = Integer.parseInt(s); if(idx > 0) { ldp[idx] = Math.max(ldp[idx-1], arr[idx]-var_t); } if(var_t > arr[idx]) var_t = arr[idx]; idx++; } var_t = arr[N-1]; for(int i = N-2; i>1; i--) { rdp = Math.max(rdp, var_t-arr[i]); ans = Math.max(ans, rdp + ldp[i-1]); var_t = Math.max(var_t, arr[i]); } System.out.println(ans); } }
package org.usfirst.frc.team4632.robot; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Timer; /** *I LIEK ROBITS BRUHHHH! */ /*Me Like Robits as wall!! *They yum yum!! Me Likey!*/ public class Robot extends SampleRobot { RobotDrive myRobot; Joystick stick; public Robot() { } public void autonomous() { } public void operatorControl() { } public void test() { } }
package com.group.weatherforecast; import java.util.List; import java.util.Map; public class WeatherForecastItem { int dt; Map<String, Float> main; List<Weather> weather; Map<String, Float> clouds; Map<String, Float> wind; String dt_txt; @Override public String toString() { return "WeatherForecastItem{" + "dt=" + dt + ", main=" + main + ", weather=" + weather + ", clouds=" + clouds + ", wind=" + wind + ", dt_txt='" + dt_txt + '\'' + '}'; } public int getDt() { return dt; } public Map<String, Float> getMain() { return main; } public double getCelsiusTemp() { return main.get("temp") - 273.15; } public List<Weather> getWeather() { return weather; } public Map<String, Float> getClouds() { return clouds; } public Map<String, Float> getWind() { return wind; } public String getDt_txt() { return dt_txt; } }
package com.apktest; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.graphics.PixelFormat; import android.media.AudioManager; import android.media.CamcorderProfile; import android.media.MediaPlayer; import android.media.MediaPlayer.OnBufferingUpdateListener; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; /** * class name:TestBasicVideo<BR> * class description:一个简单的录制视频例子<BR> * PS:实现基本的录制保存文件 <BR> * * @version 1.00 2011/09/21 * @author CODYY)peijiangping */ public class TestBasicVideo extends Activity implements SurfaceHolder.Callback { private Button start;// 开始录制按钮 private Button stop;// 停止录制按钮 private MediaRecorder mediarecorder;// 录制视频的类 private MediaPlayer player; //播放视频类 private SurfaceView surfaceview;// 显示视频的控件 private String videopath; //视频存放路径 private int videoWidth; private int videoHeight; // 用来显示视频的一个接口,我靠不用还不行,也就是说用mediarecorder录制视频还得给个界面看 // 想偷偷录视频的同学可以考虑别的办法。。嗯需要实现这个接口的Callback接口 private SurfaceHolder holder; private SurfaceHolder surfaceHolder; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setBackgroundDrawable(null); //将window的背景设置为空,安卓默认的不是空 requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏 // 设置横屏显示 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 选择支持半透明模式,在有surfaceview的activity中使用。 getWindow().setFormat(PixelFormat.TRANSLUCENT); setContentView(R.layout.videotest); init(); } private void init() { start = (Button) this.findViewById(R.id.start); stop = (Button) this.findViewById(R.id.stop); start.setOnClickListener(new TestVideoListener()); stop.setOnClickListener(new TestVideoListener()); surfaceview = (SurfaceView) this.findViewById(R.id.surfaceview); surfaceview.setOnClickListener(new TestVideoListener()); holder = surfaceview.getHolder();// 取得holder holder.addCallback(this); // holder加入回调接口 // setType必须设置,要不出错. holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } class TestVideoListener implements OnClickListener, OnBufferingUpdateListener, OnPreparedListener, OnCompletionListener { @Override public void onClick(View v) { if (v == start) { start.setBackgroundColor(Color.parseColor("#1b3661")); start.setTextSize(15); start.setEnabled(false); //设置开始按钮不可用 try { //-------------录制视频的相关设置------------- mediarecorder = new MediaRecorder(); //设置视频源 mediarecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); //设置音频源 mediarecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); //相机参数配置类:设置输出720p的视频文件 CamcorderProfile cProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_720P); mediarecorder.setProfile(cProfile); //设置录制的视频帧率,注意文档的说明: mediarecorder.setVideoFrameRate(30); //设置输出路径 videopath = creatPicFlie().getPath(); mediarecorder.setOutputFile(videopath); //设置预览画面 mediarecorder.setPreviewDisplay(holder.getSurface()); // 准备录制 mediarecorder.prepare(); // 开始录制 mediarecorder.start(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if (v == stop) { if(!start.isEnabled()){ start.setBackgroundColor(Color.parseColor("#2b59b1")); start.setTextSize(20); start.setEnabled(true); //设置开始按钮可用 } if (mediarecorder != null) { // 停止录制 mediarecorder.stop(); // 释放资源 mediarecorder.release(); mediarecorder = null; } } if(v == surfaceview){ if(videopath!=null){ if(player!=null){ if(player.isPlaying()){ player.pause(); }else{ player.start(); } return; } //--------------播放视频的相关设置------------------- try { //网络视频地址:http://v.youku.com/v_show/id_XODczNzcwMDUy.html player = new MediaPlayer(); player.setDataSource(videopath); player.setDisplay(holder); player.prepare(); player.setOnBufferingUpdateListener(this); player.setOnPreparedListener(this); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setOnCompletionListener(this); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else{ // OverAllData.Display(getApplicationContext(), "没有可供播放的视频!"); } } } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { } @Override public void onPrepared(MediaPlayer mp) { videoWidth = player.getVideoWidth(); videoHeight = player.getVideoHeight(); if (videoHeight != 0 && videoWidth != 0) { holder.setFixedSize(videoWidth, videoHeight); player.start(); } } //当播放完成时调用的方法 @Override public void onCompletion(MediaPlayer mp) { player.release(); player = null; } } //为视频创建文件夹,和视频名称 public File creatPicFlie(){ String saveDir = Environment.getExternalStorageDirectory() + "/techbloom_XDJ/VIDEO"; File dir = new File(saveDir); if (!dir.exists()) { dir.mkdir(); } Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String time = sdf.format(date); String picName = time+".mp4"; File file = new File(saveDir, picName); return file; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder surfaceHolder = holder; } @Override public void surfaceCreated(SurfaceHolder holder) { // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder surfaceHolder = holder; } @Override public void surfaceDestroyed(SurfaceHolder holder) { // surfaceDestroyed的时候同时对象设置为null surfaceview = null; surfaceHolder = null; mediarecorder = null; } @Override protected void onDestroy() { super.onDestroy(); holder = null; surfaceview = null; mediarecorder = null; if(player!=null){ player.stop(); player.release(); } player = null; } }
// Plugin: Gold2iConomy // Author: EdTheLoon // Date (last modified): 13/07/11 07:43 by EdTheLoon // License : GNU GPL v3 package com.edtheloon.gold2economy; import java.util.HashMap; import org.bukkit.ChatColor; import java.util.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.iConomy.*; import com.iConomy.system.Holdings; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; import cosine.boseconomy.BOSEconomy; public class gold2economy extends JavaPlugin { // Permission nodes public final String PERMISSION_USE = "Gold2Economy.use"; public final String PERMISSION_ADMIN = "Gold2Economy.admin"; // Config Handler, External APIs and class variables public configHandler config = new configHandler(this); public iConomy iConomyPlugin = null; public BOSEconomy BOSEconomyPlugin = null; public static PermissionHandler permissionHandler; public static boolean enabled = false; public static PluginManager pm = null; public static boolean permissionsEnabled = false; // Minecraft Log public static Logger log = Logger.getLogger("Minecraft"); public void onEnable() { // Check to see if configuration exists. If it exists then load it; if not then create it if (config.checkConfig()) { config.loadConfig(); } else { config.createConfig(); } // Register plugin enable and disable events pm = getServer().getPluginManager(); pm.registerEvent(Type.PLUGIN_ENABLE, new server(this), Priority.Monitor, this); pm.registerEvent(Type.PLUGIN_DISABLE, new server(this), Priority.Monitor, this); log.info("[Gold2Economy] Enabled. Version " + this.getDescription().getVersion().toString()); // Hook into iConomy if (config.iConomy && iConomyPlugin == null) { if (pm.getPlugin("iConomy").isEnabled()) { iConomyPlugin = (iConomy) pm.getPlugin("iConomy"); enabled = true; log.info("[Gold2Economy] Hooked into " + iConomyPlugin.getDescription().getName() + " Version " + iConomyPlugin.getDescription().getVersion()); } else { log.info("[Gold2Economy] iConomy not detected. Disabling."); enabled = false; } } // Hook into BOSEconomy if (config.BOSEconomy && BOSEconomyPlugin == null) { if (pm.getPlugin("BOSEconomy").isEnabled()) { BOSEconomyPlugin = (BOSEconomy) pm.getPlugin("BOSEconomy"); enabled = true; log.info("[Gold2Economy] Hooked into " + BOSEconomyPlugin.getDescription().getName() + " Version " + BOSEconomyPlugin.getDescription().getVersion()); } else { log.info("[Gold2Economy] BOSEconomy not detected. Disabling."); enabled = false; } } // Hook into Permissions if (config.usePermissions && permissionHandler == null) { Plugin PermissionsPlugin = getServer().getPluginManager().getPlugin("Permissions"); if (PermissionsPlugin.isEnabled()) { permissionsEnabled = true; permissionHandler = ((Permissions) PermissionsPlugin).getHandler(); log.info("[Gold2Economy] Hooked into " + PermissionsPlugin.getDescription().getName() + " Version " + PermissionsPlugin.getDescription().getVersion()); } else { permissionsEnabled = false; config.usePermissions = false; log.info("[Gold2Economy] Permissions not detected. Falling back to OP for reload command"); } } } public void onDisable() { log.info("[Gold2Economy] Plugin disabled. Version " + this.getDescription().getVersion().toString()); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { // Command = /gi if (enabled) { if (cmd.getName().equalsIgnoreCase("gi")) { if (args.length == 0) { if (config.iConomy && iConomyPlugin != null) { sender.sendMessage(ChatColor.GREEN + "Conversion rate: 1 gold ingot = " + iConomy.format(config.cRate)); return true; } if (config.BOSEconomy && BOSEconomyPlugin != null) { sender.sendMessage(ChatColor.GREEN + "Conversion rate: 1 gold ingot = " + config.cRate.toString()); return true; } } // Reload configuration if (args[0].equalsIgnoreCase("reload")) { if (permissionsEnabled && permissionHandler.has((Player)sender, PERMISSION_ADMIN) || sender instanceof ConsoleCommandSender) { giReload(sender); return true; } else if (!config.usePermissions && sender.isOp()) { giReload(sender); return true; } } // Convert all gold if (args[0].equalsIgnoreCase("all")) { if (config.usePermissions && permissionsEnabled && permissionHandler.has((Player)sender, PERMISSION_USE) || !config.usePermissions) { // Declare and initialise local variables Player player = (Player)sender; PlayerInventory pi = player.getInventory(); ItemStack items[] = pi.getContents(); // Only go ahead if the players inventory contains at least 1 gold ingot // Displays a message saying that the player doesn't have any gold if none is found if (pi.contains(266)) { Integer ingots = 0; // Loop through players inventory for (Integer i=0; i < items.length; i++) { if (items[i] != null) { // If at least 1 gold ingot is in the inventory slot then add the amount of gold in this slot to total ingots found if (items[i].getTypeId() == 266) { ingots = ingots + items[i].getAmount(); } } } // Call convertGold to convert the gold ingots convertGold(sender, ingots); return true; } else { sender.sendMessage(ChatColor.DARK_RED + "You don't have any gold ingots to convert!"); return true; } } } // Convert <amount> of gold if (sender instanceof Player) { Integer ingots = 0; try { ingots = Integer.parseInt(args[0]); // if Permissions is not detected then all players can convert gold if (!config.usePermissions) { convertGold(sender, ingots); return true; } // if Permissions is detected only players with permission can convert gold else if (config.usePermissions && permissionsEnabled && permissionHandler.has((Player)sender, PERMISSION_USE)) { convertGold(sender, ingots); return true; } } catch (NumberFormatException e) { // This should only be done if anything other than reload, all or a number was entered. // Below line for debugging only //log.info("[Gold2iConomy] ERROR: " + e.toString()); return false; } } } else { sender.sendMessage(ChatColor.RED + "Gold2iConomy is disabled because no currency sytem is enabled"); return true; } return false; } return false; } // Convert Gold into iConomy money public boolean convertGold(CommandSender sender, Integer ingots) { Double conversion = config.cRate * ingots; Player player = (Player)sender; PlayerInventory pi = player.getInventory(); // If user has enough ingots then convert gold, otherwise inform user that they do not have enough gold ingots if (pi.contains(266, ingots)) { // If using iConomy if (config.iConomy && iConomyPlugin != null) { Holdings balance = iConomy.getAccount(player.getName()).getHoldings(); balance.add(conversion); sender.sendMessage(ChatColor.GREEN + "You converted " + ingots + " ingots into " + iConomy.format(conversion)); sender.sendMessage(ChatColor.GREEN + "You now have " + iConomy.format(player.getName())); } else if (config.BOSEconomy && BOSEconomyPlugin != null) { // If using BOSEconomy int money = Math.round(conversion.floatValue()); BOSEconomyPlugin.addPlayerMoney(player.getName(), money, true); sender.sendMessage(ChatColor.GREEN + "You converted " + ingots + " ingots into " + money + " " + BOSEconomyPlugin.getMoneyNamePluralCaps()); sender.sendMessage(ChatColor.GREEN + "You now have " + BOSEconomyPlugin.getPlayerMoney(player.getName()) + " " + BOSEconomyPlugin.getMoneyNamePluralCaps()); } // Remove gold ingots HashMap<Integer,ItemStack> difference = pi.removeItem(new ItemStack(266, ingots)); difference.clear(); return true; } else { sender.sendMessage(ChatColor.DARK_RED + "You do not have " + Integer.toString(ingots) + ChatColor.DARK_RED + " gold ingots!"); return true; } } // Reload configuration public boolean giReload(CommandSender sender) { config.loadConfig(); sender.sendMessage(ChatColor.GREEN + "[Gold2Economy] " + ChatColor.WHITE + "Reloaded. Rate is " + config.cRate.toString()); return true; } }
package protocol; import java.io.IOException; import application.address.model.Sender; import application.address.model.UserBTP; import application.address.model.UserTCP; import messageCenter.ReceiverBTP; import messageCenter.ReceiverTCP; public class TCP implements Back { public UserTCP sourceUser; public Thread server; private ReceiverTCP receiver; public Sender client; private int fileNumber; private int nextSeq; public TCP(UserTCP source, UserTCP destination) throws IOException { this.sourceUser = source; this.fileNumber = 0; // this.client = new Sender(destination, false); this.receiver = new ReceiverTCP(destination, true); this.server = new Thread(receiver); this.server.start(); this.client = new Sender(destination, false); } @Override public void sendText(String text) throws IOException { send(text.getBytes(), "default"); } @Override public void send(byte[] data, String fileExtension) throws IOException { //implementação semelhante ao UDP Packet p = new Packet(this.fileNumber, fileExtension, nextSeq, 0, true, data, data.length ); client.send(getPacketBytes(p)); } @Override public byte[] getPacketBytes(Packet p) { //implementar igual ao UDP return p.toString().getBytes(); } @Override public void receiveACK() { //não faz nada, já tem implementado implicitament no Socket } public Thread getServer() { return server; } public void setServer(Thread server) { this.server = server; } }
package mx.redts.adendas.dao; import java.util.List; import mx.redts.adendas.model.CClientes; public interface IClientesDAO { public List<CClientes> getCClientesList(); }
import static org.junit.Assert.*; import org.junit.Test; /** Perform tests of the Piece class */ public class TestBoard { private Board board = new Board(true); private Piece tester = new Piece(true, board, 0, 0, "pawn"); private Piece testerOOB = new Piece(true, board, 123, 15, "pawn"); private Piece tester0 = new Piece(true, board, 1, 1, "pawn"); private Piece oppTester0 = new Piece(false, board, 3, 3, "pawn"); private Piece bomb = new Piece(false, board, 3, 3, "bomb"); private Piece bombOOB = new Piece(false, board, -23, 4, "bomb"); private Piece oppTester1 = new Piece(false, board, 5, 3, "pawn"); private Piece oppTester2 = new Piece(false, board, 0, 0, "pawn"); private Piece oppTester = new Piece(false, board, 1, 1, "pawn"); /** Tests the constructor of DoubleChain */ @Test public void testCanSelect() { board.place(tester, 0,0); board.select(0,0); assertTrue(board.canSelect(1,1)); board.select(1,1); assertFalse(tester.hasCaptured()); assertEquals(tester, board.pieceAt(1,1)); } @Test public void testEmptyBoard() { Board empty = new Board(true); assertEquals("No one", empty.winner()); } @Test public void testPlace() { board.place(tester0,1,1); board.place(testerOOB, 123,15); board.place(bomb,-23,4); assertFalse(board.canSelect(9,9)); assertFalse(board.canSelect(-23,4)); assertFalse(board.canSelect(10, -9)); assertTrue(board.canSelect(1,1)); board.place(oppTester, 0,0); assertEquals(null, board.pieceAt(1,2)); assertEquals(tester0, board.pieceAt(1,1)); assertEquals(oppTester, board.pieceAt(0,0)); } @Test public void testPieceAt() { board.place(tester0,1,1); board.place(testerOOB, 123,15); board.place(bomb,-23,4); assertNull(board.pieceAt(-23,5)); assertNull(board.pieceAt(5,5)); } @Test public void testRemove() { board.place(tester,0,0); board.place(oppTester,1,1); board.place(oppTester0,3,3); board.place(oppTester1,5,3); assertEquals(oppTester0, board.remove(3,3)); assertNull(board.remove(5,5)); assertNull(board.remove(9,9)); } @Test public void testSelect() { board.place(tester,1,1); board.place(oppTester, 0,0); assertEquals(true, board.canSelect(1,1)); assertEquals(false, board.canSelect(0,0)); board.select(1,1); board.select(2,2); assertEquals(tester, board.pieceAt(2,2)); } @Test public void testEndTurn() { board.place(tester, 0,0); board.select(0,0); assertFalse(board.canEndTurn()); board.select(1,1); tester.move(1, 1); assertTrue(board.canEndTurn()); board.endTurn(); } @Test public void testWinner() { board.place(tester,0,0); board.place(oppTester, 1,1); assertNull(board.winner()); board.select(0,0); board.select(2,2); assertEquals("Fire", board.winner()); } @Test public void testWaterWinner() { board.place(tester0,1,1); board.place(oppTester0,3,3); board.select(1,1); board.select(2,2); board.endTurn(); board.select(3,3); board.select(1,1); assertEquals(oppTester0, board.pieceAt(1,1)); assertNull(board.pieceAt(2,2)); assertEquals("Water", board.winner()); } @Test public void testBombWinner() { board.place(tester0,1,1); board.place(bomb,3,3); board.select(1,1); board.select(2,2); board.endTurn(); board.select(3,3); board.select(1,1); assertNull(board.pieceAt(1,1)); assertNull(board.pieceAt(2,2)); assertEquals("No one", board.winner()); } @Test public void testMultiCapture() { board.place(tester,0,0); board.place(oppTester,1,1); board.place(oppTester0,3,3); board.place(oppTester1,5,3); board.select(0,0); board.select(2,2); board.select(4,4); board.select(6,2); assertNull(board.pieceAt(1,1)); assertNull(board.pieceAt(3,3)); assertNull(board.pieceAt(5,3)); } public static void main(String[] args) { jh61b.junit.textui.runClasses(TestBoard.class); } }
package com.atguigu.java; import java.util.Arrays; import java.util.List; import org.junit.Test; public class ArrayToCollection { /** * 将数组转成集合 */ @Test public void test(){ String[] names = {"aa"}; // List asList = Arrays.asList("aa","cc","dd"); List asList = Arrays.asList(new String[]{"aa","bb","cc"}); for (Object obj : asList) { System.out.println(obj); } } }
package Assign7; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.*; public class MyShopping { private Hashtable < Customer, Order > a; public void storeRecord(String filename) //: To store hashtable details into file. { } public void getRecord(String filename)// : to print record on console { FileReader fr=null; FileWriter fw=null; BufferedReader br=null; BufferedWriter bw=null; try { fw=new FileWriter(filename); br=new BufferedReader(fr); bw=new BufferedWriter(fw); String data; while((data=br.readLine())!=null) { bw.write(data); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); br.close(); fw.close(); fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.artogrid.bundle.syncbond.service.impl; import java.io.Serializable; import java.util.List; import org.springframework.orm.hibernate3.HibernateCallback; import com.artogrid.bundle.syncbond.service.SyncBondService; import com.artogrid.commons.response.Page; import com.artogrid.commons.utils.Constants; import com.artogrid.framework.core.service.impl.BaseServiceImpl; import com.artogrid.framework.model.BondOffer; import com.artogrid.framework.model.CompanyExtendInfo; import com.artogrid.framework.model.SyncMessageData; public class SyncBondServiceImpl extends BaseServiceImpl<BondOffer, Serializable> implements SyncBondService { //get Company Extand list -Bond public List<CompanyExtendInfo> getCompanyExtendInfoBondUrl(){ String serverName="Bond"; List<CompanyExtendInfo> extendInfoList = find("from CompanyExtendInfo where serverName = ? and status = ?", serverName, Constants.STATUS_VALID); return extendInfoList; } //TODO get TP Last Version public long getCompanyServerLastVersion(String bondUrl){ //TODO hessian get lastVersion return 0; } //get My Server Last Version public long getLastVersion(String companyId){ List<Long> list = find("select version from SyncMessageData where companyId = ? and status= ? order by version desc limit 1", companyId, Constants.STATUS_VALID); if(list.size()>0){ return list.get(0); } return 0; } //TODO get Miss Data public List<SyncMessageData> getMissDataByVersion(long version,String bondUrl){ return null; } //TODO save MissData public void saveSyncMessageData(List<SyncMessageData> data){ } }
package br.ufsc.ine5605.clavicularioeletronico.controladores; import br.ufsc.ine5605.clavicularioeletronico.telasgraficas.TelaSistemaNew; /** * Controlador principal do sistema, controla o menu principal e * chama os demais controladores * @author Flávio */ public class ControladorSistema { private static ControladorSistema instance; private TelaSistemaNew tela; private ControladorSistema() { tela = new TelaSistemaNew(); } public static ControladorSistema getInstance() { if (instance == null) { instance = new ControladorSistema(); } return instance; } public void inicia() { this.exibeMenuInicial(); } public void exibeMenuInicial() { tela.setVisible(true); } public void abreCadastroVeiculo() { ControladorVeiculo.getInstance().inicia(); } public void abreCadastroFuncionario() { ControladorFuncionario.getInstance().inicia(); } public void abreRetirarChaveClaviculario() { ControladorClaviculario.getInstance().abreTelaRetirarChave(); } public void abreDevolverChaveClaviculario() { ControladorClaviculario.getInstance().abreTelaDevolverChave(); } public void abreRelatorioCompleto() { ControladorClaviculario.getInstance().abreTelaRelatorioCompleto(); } public void abreRelatorioEvento() { ControladorClaviculario.getInstance().abreTelaRelatorioEvento(); } public void abreRelatorioFuncionario() { ControladorClaviculario.getInstance().abreTelaRelatorioFuncionario(); } public void abreRelatorioVeiculo() { ControladorClaviculario.getInstance().abreTelaRelatorioVeiculo(); } }
package com.imooc.ioc.demo1; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.core.io.ClassPathResource; /** * @Author: Asher Huang * @Date: 2019-10-12 * @Description: com.imooc.ioc.demo1 * @Version:1.0 */ public class SpringDemo1 { @Test /** * 传统方式开发 */ public void demo1(){ // 下面2行代码是传统方式实现 UserService userService=new UserServiceImpl(); userService.sayHello(); // 下面的代码是针对UserServiceImpl实现类里有新增属性时的: // 也就是说spring的依赖注入dependency injection,对于传统方式,需要更改代码,而对于spring来讲,只需要更改配置文件 UserServiceImpl userService1 = new UserServiceImpl(); userService1.setName("李四"); userService1.sayHello(); } @Test /** * 使用spring方式 */ public void demo2() { // 创建spring的工厂 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); // 通过工厂获得类 UserService userService = (UserService) applicationContext.getBean("UserService"); userService.sayHello(); } @Test /** * 使用spring方式来读取文件系统的配置文件 */ public void demo3() { // 创建spring的工厂。这里的路径,默认会读取项目路径下的名称为我们指定的applicationContext.xml文件。即: // /Users/asher/IdeaProjects/learnjavaexception/spring_ioc/applicationContext.xml // 如果想写成,/Users/asher/IdeaProjects/applicationContext.xml会报错,暂时还不知道怎么解决? ApplicationContext applicationContext=new FileSystemXmlApplicationContext("applicationContext.xml"); // 获得工厂类对象 UserService userService= (UserService) applicationContext.getBean("UserService"); userService.sayHello(); } @Test /** * 通过原始的BeanFactory方式读取配置文件 */ public void demo4() { // 通过旧方式的BeanFactory来创建工厂类 BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml")); // 获得工厂类对象 UserService userService = (UserService) beanFactory.getBean("UserService"); userService.sayHello(); } @Test /** * 通过原始的BeanFactory方式读取文件系统上的配置文件 */ public void demo5() { // 通过BeanFactory来创建工厂类 BeanFactory beanFactory=new FileSystemXmlApplicationContext("applicationContext.xml"); // 实例化工厂类对象 UserService userService= (UserService) beanFactory.getBean("UserService"); userService.sayHello(); } }
/* * Author: RINEARN (Fumihiro Matsui), 2020 * License: CC0 */ package org.vcssl.nano.plugin.system.terminal; import java.awt.Color; import java.awt.Font; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.lang.reflect.InvocationTargetException; import javax.swing.JFrame; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.text.DefaultEditorKit; import org.vcssl.connect.ConnectorException; /** * A window to display outputs of print functions etc. on GUI mode * GUIモード時に print 関数などの出力を表示するためのウィンドウです */ public class TerminalWindow { private static final int DEFAULT_WINDOW_X = 100; private static final int DEFAULT_WINDOW_Y = 100; private static final int DEFAULT_WINDOW_WIDTH = 600; private static final int DEFAULT_WINDOW_HEIGHT = 400; private static final String DEFAULT_WINDOW_TITLE = "Terminal"; private static final Color DEFAULT_BACKGROUND_COLOR = Color.BLACK; private static final Color DEFAULT_FOREGROUND_COLOR = Color.WHITE; private static final Font DEFAULT_FONT = new Font("Dialog", Font.PLAIN, 16); private JFrame frame = null; private JTextArea textArea = null; private JScrollPane scrollPane = null; private JPopupMenu textAreaPopupMenu = null; // ウィンドウが表示OFFの状態でも、次に print された時点で表示ONにするためのフラグ。 // 何も print しないスクリプトでも常にウィンドウが表示されると、アプリケーションの種類によっては嫌かもしれないので、 // 初期状態では表示されないようになっている。 // そしてスクリプト開始後に、print が呼ばれた時点でこのフラグが true なら、その時にウィンドウが表示され、フラグは false に切り替わる。 // ただし、スクリプト内で hide 関数が呼ばれた場合、それはウィンドウの表示が不要という意思表示なので、その時点でフラグを false にする。 private volatile boolean autoShowing = true; /** * A class to construct components of the window on the UI thread * UIスレッドで画面構築を行うためのクラスです */ private class InitRunner implements Runnable { @Override public void run() { // ウィンドウを生成 TerminalWindow.this.frame = new JFrame(); TerminalWindow.this.frame.setBounds( TerminalWindow.DEFAULT_WINDOW_X, TerminalWindow.DEFAULT_WINDOW_Y, TerminalWindow.DEFAULT_WINDOW_WIDTH, TerminalWindow.DEFAULT_WINDOW_HEIGHT ); TerminalWindow.this.frame.setTitle(TerminalWindow.DEFAULT_WINDOW_TITLE); // テキストエリアを生成 TerminalWindow.this.textArea = new JTextArea(); TerminalWindow.this.textArea.setBackground(TerminalWindow.DEFAULT_BACKGROUND_COLOR); TerminalWindow.this.textArea.setForeground(TerminalWindow.DEFAULT_FOREGROUND_COLOR); TerminalWindow.this.textArea.setFont(TerminalWindow.DEFAULT_FONT); // テキストエリアにスクロールバーを付けてウィンドウ上に配置 TerminalWindow.this.scrollPane = new JScrollPane( TerminalWindow.this.textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS ); TerminalWindow.this.frame.getContentPane().add(TerminalWindow.this.scrollPane); // テキストエリアの右クリックメニューを生成 TerminalWindow.this.textAreaPopupMenu = new JPopupMenu(); TerminalWindow.this.textAreaPopupMenu.add(new DefaultEditorKit.CutAction()).setText("Cut"); TerminalWindow.this.textAreaPopupMenu.add(new DefaultEditorKit.CopyAction()).setText("Copy"); TerminalWindow.this.textAreaPopupMenu.add(new DefaultEditorKit.PasteAction()).setText("Paste"); // テキストエリアの右クリックイベントをハンドルするリスナーを生成して登録 TerminalWindow.this.textArea.addMouseListener(new TextAreaRightClickListener()); // テキストエリアを表示(ウィンドウは print するまで表示したくない用途もあるのでここではまだ表示しない) TerminalWindow.this.textArea.setVisible(true); TerminalWindow.this.scrollPane.setVisible(true); } } /** * A class to make the window visible on the UI thread * UIスレッドでウィンドウの表示をONにするためのクラスです */ private class ShowRunner implements Runnable { @Override public void run() { TerminalWindow.this.frame.setVisible(true); } } /** * A class to check whether the window is visible or not, on the UI thread * UIスレッドでウィンドウの表示/非表示状態を取得するためのクラスです */ private class VisiblityCheckRunner implements Runnable { boolean visiblity = false; @Override public void run() { this.visiblity = TerminalWindow.this.frame.isVisible(); } public boolean isVisible() { return this.visiblity; } } /** * A class to make the window invisible on the UI thread * UIスレッドでウィンドウの表示をOFFにするためのクラスです */ private class HideRunner implements Runnable { @Override public void run() { TerminalWindow.this.frame.setVisible(false); } } /** * A class to print a string to the text field on the window, on the UI thread * UIスレッドでウィンドウに print するためのクラスです */ private class PrintRunner implements Runnable { String printContent = null; public PrintRunner(String printContent) { this.printContent = printContent; } @Override public void run() { TerminalWindow.this.textArea.append(this.printContent); } } /** * A class to clear contents of the text field on the window, on the UI thread * UIスレッドでウィンドウの print 内容をクリアするためのクラスです */ private class ClearRunner implements Runnable { @Override public void run() { TerminalWindow.this.textArea.setText(""); } } /** * A class to dispose the window on the UI thread * UIスレッドでウィンドウを破棄するためのクラスです */ private class DisposeRunner implements Runnable { // disposesNow に true が指定されていれば、有無を言わさず今すぐに破棄する // false が指定されている場合は、画面が表示中ならすぐに破棄はせず、 // ユーザーがウィンドウを閉じた時点で破棄されるように設定する boolean disposesNow = false; public DisposeRunner(boolean disposesNow) { this.disposesNow = disposesNow; } @Override public void run() { if (TerminalWindow.this.frame == null) { return; } // disposesNow に true が指定されている場合や、 // false でも画面が非表示になっている場合は、今すぐに破棄する if (disposesNow || !TerminalWindow.this.frame.isVisible()) { TerminalWindow.this.frame.setVisible(false); TerminalWindow.this.frame.dispose(); // そうでなければ、ユーザーにとって不都合にならないタイミングで破棄するように設定 } else { TerminalWindow.this.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } // どちらにしても参照はこの時点で解除しておく TerminalWindow.this.textArea = null; TerminalWindow.this.scrollPane = null; TerminalWindow.this.textAreaPopupMenu = null; TerminalWindow.this.frame = null; } } /** * An event listener class to pop-up right-click menu * 右クリックメニューを表示するためのイベントリスナークラスです */ private final class TextAreaRightClickListener implements MouseListener { @Override public final void mouseClicked(MouseEvent e) { if(javax.swing.SwingUtilities.isRightMouseButton(e)){ TerminalWindow.this.textAreaPopupMenu.show( TerminalWindow.this.textArea, e.getX(), e.getY() ); } } @Override public final void mousePressed(MouseEvent e) { } @Override public final void mouseReleased(MouseEvent e) { } @Override public final void mouseEntered(MouseEvent e) { } @Override public final void mouseExited(MouseEvent e) { } } /** * Constructs the window * ウィンドウを構築します */ public void init() { if (SwingUtilities.isEventDispatchThread()) { new InitRunner().run(); } else { SwingUtilities.invokeLater(new InitRunner()); } } /** * Resets state for re-executing a script (or executing other script) * スクリプトを再実行(または別のスクリプトを実行)するために、初期状態に戻します */ public void reset() { this.autoShowing = true; this.clear(); } /** * Makes the window visible * ウィンドウを表示します */ public void show() { if (SwingUtilities.isEventDispatchThread()) { new ShowRunner().run(); } else { SwingUtilities.invokeLater(new ShowRunner()); } } /** * Makes the window invisible * ウィンドウを非表示にします */ public void hide() { this.autoShowing = false; if (SwingUtilities.isEventDispatchThread()) { new HideRunner().run(); } else { SwingUtilities.invokeLater(new HideRunner()); } } /** * Prints a string to the text area on the window * ウィンドウ上のテキストエリアに文字列を print します * @throws ConnectorException */ public void print(String printContent) throws ConnectorException { // ウィンドウが表示状態かどうかを取得 boolean isFrameVisible = false; if (SwingUtilities.isEventDispatchThread()) { isFrameVisible = this.frame.isVisible(); } else { VisiblityCheckRunner visibleChecker = new VisiblityCheckRunner(); try { SwingUtilities.invokeAndWait(visibleChecker); } catch (InvocationTargetException | InterruptedException e) { throw new ConnectorException(e); } isFrameVisible = visibleChecker.isVisible(); } if (this.autoShowing && !isFrameVisible) { this.autoShowing = false; this.show(); } if (SwingUtilities.isEventDispatchThread()) { new PrintRunner(printContent).run(); } else { SwingUtilities.invokeLater(new PrintRunner(printContent)); } } /** * Clears contents of the text area on the window * ウィンドウ上のテキストエリアの内容をクリアします */ public void clear() { if (SwingUtilities.isEventDispatchThread()) { new ClearRunner().run(); } else { SwingUtilities.invokeLater(new ClearRunner()); } } /** * Disposes the window * ウィンドウを破棄します */ public void dispose(boolean disposesNow) { // disposesNow に true が指定されていれば、有無を言わさず今すぐに破棄する // false が指定されている場合は、画面が表示中ならすぐに破棄はせず、 // ユーザーがウィンドウを閉じた時点で破棄されるように設定する if (SwingUtilities.isEventDispatchThread()) { new DisposeRunner(disposesNow).run(); } else { SwingUtilities.invokeLater(new DisposeRunner(disposesNow)); } } }
package algo3.fiuba.vista.vista_tablero; import algo3.fiuba.controladores.controladores_de_carta.ControladorCartaCampo; import algo3.fiuba.controladores.controladores_de_carta.ControladorCementerio; import algo3.fiuba.controladores.ControladorMazo; import algo3.fiuba.modelo.jugador.Jugador; import algo3.fiuba.utils.CartaVistaUtils; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.*; import javafx.scene.paint.Color; public abstract class Tablero extends GridPane { private Label cementerio; private double ANCHO_MAXIMO_CARTA = 90.0; private double ALTURA_MAXIMA_CARTA = 105.0; private Jugador jugador; private VistaMazo zonaMazo; protected VistaMano zonaMano; private VistaZonaNoMonstruos zonaNoMonstruos; private ZonaMonstruosVista zonaMonstruos; private VistaCartaCampo zonaCartaDeCampo; private CartaVistaUtils cartaVistaUtils; public Tablero(Jugador jugador) { cartaVistaUtils = new CartaVistaUtils(); zonaMonstruos = new ZonaMonstruosVista(jugador); zonaNoMonstruos = new VistaZonaNoMonstruos(jugador); this.zonaMano = new VistaMano(jugador); ImageView fondoMazo = new ImageView(new Image(cartaVistaUtils.getImagenCartaBocaAbajo(), ANCHO_MAXIMO_CARTA, ALTURA_MAXIMA_CARTA, false, false)); this.zonaMazo = new VistaMazo(fondoMazo, jugador); this.zonaMazo.setOnMouseClicked(new ControladorMazo(zonaMazo, jugador, zonaMano)); this.zonaNoMonstruos = new VistaZonaNoMonstruos(jugador); this.zonaMonstruos = new ZonaMonstruosVista(jugador); ImageView fondoCementerio = new ImageView(new Image("/algo3/fiuba/resources/img/cartavacia.jpg", ANCHO_MAXIMO_CARTA, ALTURA_MAXIMA_CARTA, false, false)); this.cementerio = new Label("CEMENTERIO", fondoCementerio); ImageView cartaCampoFondo = new ImageView(new Image("/algo3/fiuba/resources/img/cartavacia.jpg", ANCHO_MAXIMO_CARTA, ALTURA_MAXIMA_CARTA, false, false)); this.zonaCartaDeCampo = new VistaCartaCampo(jugador); this.zonaCartaDeCampo.setOnMouseClicked(new ControladorCartaCampo(zonaCartaDeCampo, jugador, zonaMano)); } public abstract void dibujar(); public void update() { this.zonaMazo.dibujar(); this.zonaMano.dibujar(); this.zonaMonstruos.dibujar(); this.zonaNoMonstruos.dibujar(); this.cementerio.setTextFill(Color.WHITE); this.cementerio.setContentDisplay(ContentDisplay.CENTER); this.cementerio.setOnMouseClicked(new ControladorCementerio()); this.zonaCartaDeCampo.dibujar(); } public void setMano(Integer colIndex, Integer rowIndex) { this.zonaMano.dibujar(); this.add(zonaMano, colIndex, rowIndex); } public void setMazo(Integer colIndex, Integer rowIndex, VistaMano zonaMano) { this.zonaMazo.dibujar(); this.add(zonaMazo, colIndex, colIndex); } public void setCampo(Integer colIndex, Integer rowIndex, Integer colIndex2, Integer rowIndex2) { this.zonaMonstruos.dibujar(); this.zonaNoMonstruos.dibujar(); this.add(zonaNoMonstruos, colIndex, rowIndex); this.add(zonaMonstruos, colIndex2, rowIndex2); } public void setCementerio(Integer colIndex, Integer rowIndex) { cementerio.setTextFill(Color.WHITE); cementerio.setContentDisplay(ContentDisplay.CENTER); cementerio.setOnMouseClicked(new ControladorCementerio()); this.add(cementerio, colIndex, rowIndex); } public void setCartaCampo(Integer colIndex, Integer rowIndex) { this.zonaCartaDeCampo.dibujar(); this.add(zonaCartaDeCampo, colIndex, rowIndex); } public ZonaMonstruosVista getZonaMonstruos() { return zonaMonstruos; } }
package com.contract.system.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table public class Slot { @Id @GeneratedValue private long slotid; private String slotname; private String starttime; private String endtime; public long getSlotid() { return slotid; } public void setSlotid(long slotid) { this.slotid = slotid; } public String getSlotname() { return slotname; } public void setSlotname(String slotname) { this.slotname = slotname; } public String getStarttime() { return starttime; } public void setStarttime(String starttime) { this.starttime = starttime; } public String getEndtime() { return endtime; } public void setEndtime(String endtime) { this.endtime = endtime; } }
package a2; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; class SymLit{ int addr; String name; SymLit(String n,int a){ name = n; addr = a; } } public class Pass2 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub SymLit [] SYMTAB = new SymLit[50]; SymLit [] LITTAB = new SymLit[50]; //int [] POOLTAB = new int[10]; //storing data in symbol table FileReader fr=new FileReader("SymbolTable.txt"); BufferedReader br=new BufferedReader(fr); String line; int sym_ptr = 1; while((line = br.readLine()) != null){ String s[] = line.split("\t"); SYMTAB[sym_ptr] = new SymLit(s[1],Integer.parseInt(s[2])); sym_ptr++; } //storing data in literal table FileReader fr1=new FileReader("LiteralTable.txt"); BufferedReader br1=new BufferedReader(fr1); int lit_ptr = 1; while((line = br1.readLine()) != null){ String s[] = line.split("\t"); LITTAB[lit_ptr] = new SymLit(s[1],Integer.parseInt(s[2])); lit_ptr++; } //read intermediate code line by line FileReader fr2=new FileReader("ic.txt"); BufferedReader br2=new BufferedReader(fr2); OutputStream os = new FileOutputStream(new File("/home/TE/SPOSL/3171/A2/FinalCode.txt")); while((line = br2.readLine()) != null){ String loc_cntr = ""; String s[] = line.split(" "); loc_cntr = s[s.length -1];//get location counter if(s[0].charAt(1) == 'I'){ //Imperative Statement int insNo = Integer.parseInt(s[0].charAt(4)+""); if(s[0].charAt(5) != ')'){ insNo = 10; }if(s.length == 3){ char regval = '0'; char sl = s[1].charAt(1); int index = Integer.parseInt(s[1].charAt(3)+""); int addr = 0; if(sl == 'L'){ addr = LITTAB[index].addr; } else if (sl == 'S'){ addr = SYMTAB[index].addr; } line = (loc_cntr + ") " + insNo + " " + regval + " " + addr + "\n" ); } else if(s.length > 3){ char regval = s[1].charAt(1);//register is present char sl = s[2].charAt(1); int index = Integer.parseInt(s[2].charAt(3)+""); int addr = 0; if(sl == 'L'){ addr = LITTAB[index].addr; } else if (sl == 'S'){ addr = SYMTAB[index].addr; } line = (loc_cntr + ") " + insNo + " " + regval + " " + addr + "\n" ); }else{ line = ( loc_cntr + ") " + insNo + " 0 000" + "\n"); } } else if(s[0].charAt(1) == 'D'){ //Declarative Statement int insNo = Integer.parseInt(s[0].charAt(4)+""); if(insNo == 1){ //only DC statements String constant =""; for(int i =3;i< s[1].length() ;i++){ if(s[1].charAt(i)== ')') break; constant = constant + s[1].charAt(i); } int cons = Integer.parseInt(constant); line = (loc_cntr + ") 0 0 " + cons + "\n"); } else{ //for DS statements line = "\n"; } } else{ //for AD statements line = "\n"; } os.write(line.getBytes(), 0, line.length()); } br.close(); br1.close(); br2.close(); os.close(); } }
package com.rk.jarjuggler.gui; import javax.swing.*; import javax.swing.tree.TreeNode; import com.intellij.util.ui.ColumnInfo; import com.intellij.util.ui.treetable.ListTreeTableModelOnColumns; import com.intellij.util.ui.treetable.TreeTableModel; import com.rk.jarjuggler.model.DirNode; import com.rk.jarjuggler.model.LibNode; public class DirNodeTreeTableModel extends ListTreeTableModelOnColumns implements TreeTableModel { static final ColumnInfo[] columnInfos = new ColumnInfo[] { new ColumnInfo<DirNode, Object>("Placeholder") { public Object valueOf(DirNode object) { return object.getName(); } }, // new ColumnInfo<DirNode, Object>("Name") { // public Object valueOf(DirNode object) { // return object.getName(); // } // // public int getWidth(JTable table) { // return 200; // } // }, // new ColumnInfo<DirNode, Object>("URL") { // public Object valueOf(DirNode object) { // return object.getUrl(); // } // // public int getWidth(JTable table) { // return 400; // } // }, new ColumnInfo<DirNode, Object>("Jar") { public Object valueOf(DirNode object) { if (object instanceof LibNode) { return ((LibNode)object).hasJar() ? "Y" : null; } else { return null; } } public int getWidth(JTable table) { return 50; } }, new ColumnInfo<DirNode, Object>("Src") { public Object valueOf(DirNode object) { if (object instanceof LibNode) { return ((LibNode)object).hasSrc() ? "Y" : null; } else { return null; } } public int getWidth(JTable table) { return 50; } }, new ColumnInfo<DirNode, Object>("Javadoc") { public Object valueOf(DirNode object) { if (object instanceof LibNode) { return ((LibNode)object).hasJavadoc() ? "Y" : null; } else { return null; } } public int getWidth(JTable table) { return 70; } }, new ColumnInfo<DirNode, Object>("URL") { public Object valueOf(DirNode object) { return object.getUrl(); } public int getWidth(JTable table) { return 400; } }, }; public DirNodeTreeTableModel(TreeNode root) { super(root, columnInfos); getColumnInfos()[0] = new TreeColumnInfo(); } class TreeColumnInfo extends ColumnInfo { public TreeColumnInfo() { super("Tree"); } public Object valueOf(Object object) { return DirNodeTreeTableModel.this; } public Class getColumnClass() { return TreeTableModel.class; } public int getWidth(JTable table) { return 200; } } }
package com.example.elearning.repositories; import com.example.elearning.entities.Chapitre; import org.springframework.data.jpa.repository.JpaRepository; public interface ChapitreRepository extends JpaRepository<Chapitre,Integer> { }
package com.tvm.thread.exceptionHandler; public class Task implements Runnable{ @Override public void run() { int i = Integer.parseInt("TTT"); //The below line of code will never be executed due to exception in the above line System.out.println("Finished Thread Class execution"+i); } }
package com.akanar.dao; import java.util.List; import com.akanar.exceptions.BusinessException; import com.akanar.model.AccountInfo; import com.akanar.model.CustomerInfo; import com.akanar.model.TransactionInfo; import com.akanar.model.UserInfo; public interface AkanarDAO { // Get data public CustomerInfo getAccountInfoByEmail(String email) throws BusinessException; public AccountInfo getAccountByUser(String username) throws BusinessException; public List<TransactionInfo> getTransactionsByAccountId(long account_id) throws BusinessException; // Store data public AccountInfo setAccountInfo(AccountInfo accountinfo) throws BusinessException; public void setTransactionInfo(TransactionInfo transactioninfo) throws BusinessException; // Update data public AccountInfo setBalance(AccountInfo accountinfo) throws BusinessException; public UserInfo updatePassword(UserInfo userinfo) throws BusinessException; }
package com.example.demo.web; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.example.demo.entity.Dictionary; import com.example.demo.service.DictionaryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RequestBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.ObjDoubleConsumer; @Controller @RequestMapping("/dictionary") public class DictionaryWeb { private final String crud="/dictionary/DictionaryCrud"; //增删改查页面 @RequestMapping("/index") public String index(){ return "/dictionary/dictionaryUi"; } @Autowired DictionaryService dictionaryService; @RequestMapping("/getdictionary") @ResponseBody public Map<String,Object> getdictionary(int page, int rows,String filter,String sort,String order){ System.out.println("page="+page+" rows="+rows+" filter="+filter+" "+sort+" "+ order); List<Dictionary> lists=dictionaryService.selectAll(); int total=dictionaryService.selectCount(new EntityWrapper<>()); //分页 Page<Map<String,Object>> pg=new Page(page,rows); lists=dictionaryService.selectListByFilter(filter,sort,order,pg); Map<String,Object> map=new HashMap<String,Object>(); map.put("total",total); map.put("rows",lists); return map; } @RequestMapping("/toAdd") //跳转新增页面 public String toAdd(Model model){ Dictionary dictionary=new Dictionary(); model.addAttribute("readonly",false); model.addAttribute("vis_add",true); //增加按钮显示 model.addAttribute("vis_save",false); //保存按钮隐藏 model.addAttribute("dictionary",dictionary); //用户信息 return crud; } @RequestMapping("/add") //新增 @ResponseBody public String add(Model model,@RequestBody Dictionary dictionary){ System.out.println(dictionary); dictionaryService.insert(dictionary); return "success"; } @RequestMapping("/del") //删除 @ResponseBody public String del(Integer id){ dictionaryService.deleteById(id); return "sucess"; } @RequestMapping("/toUpdate") //跳到修改页面 public String toUpdate(Model model,Integer id){ Dictionary dictionary=dictionaryService.selectById(id); model.addAttribute("readonly",false); //可以读写 model.addAttribute("vis_save",true); //保存按钮显示 model.addAttribute("vis_add",false); //增加按钮隐藏 model.addAttribute("dictionary",dictionary); //用户信息 return crud; } @RequestMapping("/update") //修改 @ResponseBody public String update(Model model,@RequestBody Dictionary dictionary){ System.out.println(dictionary); dictionaryService.updateById(dictionary); return "sucess"; } @RequestMapping("/toView") //跳到查看页面 public String toView(Model model,Integer id){ Dictionary dictionary=dictionaryService.selectById(id); model.addAttribute("readonly",true); model.addAttribute("vis_save",false); //保存按钮隐藏 model.addAttribute("vis_add",false); //增加按钮隐藏 model.addAttribute("dictionary",dictionary); //用户信息 return crud; } }
package br.com.estore.web.model; public enum PersonTypeBean { Individuals(1),LegalEntity(2); private int value; private PersonTypeBean(int value) { this.setValue(value); } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }
package tutuorial1; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyInput extends KeyAdapter { private Handler handler; private boolean[] keyDown = new boolean[4]; public KeyInput(Handler handler){ this.handler=handler; for(int i = 0; i < 4; i++){ keyDown[i] = false; } } public void keyPressed(KeyEvent e){ int key = e.getKeyCode(); } public void keyReleased(KeyEvent e){ int key = e.getKeyCode(); } }
package com.lv.redis.rediscombat.util; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.ScanResult; import java.util.List; import java.util.Map; import java.util.Set; /** * @author 吕明亮 * @Date : 2019/9/2 16:16 * @Description: */ @Component public class JedisUtil { /** * jedis连接池 */ public static JedisPool pool = null; static { if (pool == null) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(500); config.setMaxIdle(5); config.setMaxWaitMillis(100); config.setTestOnBorrow(true); //pool = new JedisPool(config, "127.0.0.1", 6379, 100000, ""); pool = new JedisPool(config, "127.0.0.1", 6379, 100000); } } public String ip = "127.0.0.1"; private int port = 6379; private String auth = ""; public static Jedis jedis; /** * 直接获取jedis * * @param host * @param port * @return */ public static Jedis getJedis(String host, int port) { if (jedis == null) { jedis = new Jedis(host, port); } return jedis; } public JedisUtil() { if (pool == null) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(500); config.setMaxIdle(5); config.setMaxWaitMillis(100); config.setTestOnBorrow(true); //pool = new JedisPool(config, this.ip, this.port, 100000, this.auth); pool = new JedisPool(config, this.ip, this.port, 100000); } } public void ping() { Jedis jedis = null; try { jedis = pool.getResource(); System.out.println(jedis.ping()); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } } /** * jedisPool 废弃了归还连接 returnBrokenResource ,直接jedis.close() 即可 * * @param jedis */ public void close(Jedis jedis) { if (jedis != null) { //System.out.println("关闭连接:" + jedis); jedis.close(); } } public void poolPing() { JedisPool jedisPool = new JedisPool(); Jedis jedis = jedisPool.getResource(); System.out.println(jedis.ping()); } public void poolPings() { Jedis jedis = pool.getResource(); System.out.println(jedis.ping()); } /************* key 的基本操作**************/ /** * 用于删除已存在的键。不存在的 key 会被忽略 * * @param key * @return */ public Long del(String... key) { Jedis jedis = null; try { jedis = pool.getResource(); return jedis.del(key); } catch (Exception e) { close(jedis); e.printStackTrace(); return 0L; } finally { close(jedis); } } /** * 用于序列化给定 key ,并返回被序列化的值。 * * @param key * @return byte[] 序列号的byte数组 */ public byte[] dump(String key) { Jedis jedis = null; byte[] result = null; try { jedis = pool.getResource(); result = jedis.dump(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return result; } /** * 用于检查给定 key 是否存在 * * @param key * @return boolean(存在返回true, 不存在返回false) */ public Boolean exists(String key) { Jedis jedis = null; try { jedis = pool.getResource(); return jedis.exists(key); } catch (Exception e) { close(jedis); e.printStackTrace(); return false; } finally { close(jedis); } } /** * 设置 key 的过期时间,key 过期后将不再可用。单位以秒计 * * @param key * @param times */ public void expire(String key, int times) { Jedis jedis = null; try { jedis = pool.getResource(); jedis.expire(key, times); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } } /** * 用于以UNIX 时间戳(unix timestamp)格式设置 key 的过期时间。key 过期后将不再可用 * * @param key * @param unixTime */ public void expireAt(String key, long unixTime) { Jedis jedis = null; try { jedis = pool.getResource(); jedis.expireAt(key, unixTime); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } } /** * 以毫秒为单位设置 key 的生存时间,而不像 EXPIRE 命令那样,以秒为单位 * * @param key * @param milliseconds */ public void pexpire(String key, long milliseconds) { Jedis jedis = null; try { jedis = pool.getResource(); jedis.pexpire(key, milliseconds); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } } /** * 用于设置 key 的过期时间,以毫秒计。key 过期后将不再可用 * * @param key * @param milliseconds */ public void pexpireAt(String key, long milliseconds) { Jedis jedis = null; try { jedis = pool.getResource(); jedis.pexpireAt(key, milliseconds); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } } /** * 用于查找所有符合给定模式 pattern 的 key 。。 * * @param pattern * @return */ public Set<String> keys(String pattern) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.keys(pattern); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于将当前数据库的 key 移动到给定的数据库 db 当中 * * @param key * @param dbIndex * @return */ public Long move(String key, int dbIndex) { Jedis jedis = null; Long total = 0L; try { jedis = pool.getResource(); total = jedis.move(key, dbIndex); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return total; } /** * 以秒为单位查看过期时间 * * @param key * @return */ public Long ttl(String key) { Jedis jedis = null; Long passDueTime = 0L; try { jedis = pool.getResource(); passDueTime = jedis.ttl(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return passDueTime; } /** * 以毫秒为单位返回 key 的剩余过期时间 * * @param key * @return */ public Long pttl(String key) { Jedis jedis = null; Long passDueTime = 0L; try { jedis = pool.getResource(); passDueTime = jedis.pttl(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return passDueTime; } /** * 从当前数据库中随机返回一个 key * * @return */ public String randomKey() { Jedis jedis = null; String randomKey = null; try { jedis = pool.getResource(); randomKey = jedis.randomKey(); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return randomKey; } /** * 用于修改 key 的名称 * * @param oldKeyName * @param newKeyName * @return 改名成功时提示 OK ,失败时候返回一个错误 ,key 不存在时返回 ERR no such key * 当 OLD_KEY_NAME 和 NEW_KEY_NAME 相同,或者 OLD_KEY_NAME 不存在时,返回一个错误。 当 NEW_KEY_NAME 已经存在时, RENAME 命令将覆盖旧值 */ public String reName(String oldKeyName, String newKeyName) { Jedis jedis = null; String result = null; try { jedis = pool.getResource(); result = jedis.rename(oldKeyName, newKeyName); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return result; } /** * 新的 key 不存在时修改 key 的名称 * * @param oldKeyName * @param newKeyName * @return 修改成功时,返回 1 。 如果 NEW_KEY_NAME 已经存在,返回 0 */ public Long reNameNx(String oldKeyName, String newKeyName) { Jedis jedis = null; Long result = null; try { jedis = pool.getResource(); result = jedis.renamenx(oldKeyName, newKeyName); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return result; } /** * 返回 key 所储存的值的类型 * * @param key * @return */ public String type(String key) { Jedis jedis = null; String result = null; try { jedis = pool.getResource(); result = jedis.type(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return result; } /***************************************** Redis 字符串(String) ************************************************/ /** * SET 命令用于设置给定 key 的值。如果 key 已经存储其他值, SET 就覆写旧值,且无视类型 * * @param key * @param value * @return */ public String set(String key, String value) { Jedis jedis = null; String result = null; try { jedis = pool.getResource(); result = jedis.set(key, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return result; } /** * 用于获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误 * * @param key * @return */ public String get(String key) { Jedis jedis = null; String value = null; try { jedis = pool.getResource(); value = jedis.get(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return value; } /** * 获取存储在指定 key 中字符串的子字符串。字符串的截取范围由 start 和 end 两个偏移量决定(包括 start 和 end 在内) * * @param key * @param startOffset * @param endOffset * @return 如果没有返回null */ public String getRange(String key, int startOffset, int endOffset) { Jedis jedis = null; String value = null; try { jedis = pool.getResource(); value = jedis.getrange(key, startOffset, endOffset); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return value; } /** * 用于设置指定 key 的值,并返回 key 的旧值 * * @param key * @param value * @return */ public String getSet(String key, String value) { Jedis jedis = null; String result = null; try { jedis = pool.getResource(); result = jedis.getSet(key, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return result; } /** * 返回所有(一个或多个)给定 key 的值。 如果给定的 key 里面,有某个 key 不存在,那么这个 key 返回特殊值 null * * @param keys * @return */ public List<String> mget(String... keys) { Jedis jedis = null; List<String> values = null; try { jedis = pool.getResource(); values = jedis.mget(keys); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return values; } /** * 指定的 key 设置值及其过期时间。如果 key 已经存在, SETEX 命令将会替换旧的值 * * @param key * @param value * @param seconds 单位: * @return 成功返回OK 失败和异常返回null */ public String setEx(String key, String value, int seconds) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.setex(key, seconds, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 在指定的 key 不存在时,为 key 设置指定的值 * * @param key * @param value * @return */ public Long setNx(String key, String value) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.setnx(key, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 指定的字符串覆盖给定 key 所储存的字符串值,覆盖的位置从偏移量 offset 开始 * * @param key * @param value * @param offset * @return */ public Long setRange(String key, String value, int offset) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.setrange(key, offset, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 获取指定 key 所储存的字符串值的长度。当 key 储存的不是字符串值时,返回一个错误 * * @param key * @return */ public Long strLen(String key) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.strlen(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于同时设置一个或多个 key-value 对 * * @param keysValues * @return */ public String mSet(String... keysValues) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.mset(keysValues); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 当所有 key 都成功设置,返回 1 。 如果所有给定 key 都设置失败(至少有一个 key 已经存在),那么返回 0 * * @param keysValues * @return */ public Long mSetNx(String... keysValues) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.msetnx(keysValues); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 以毫秒为单位设置 key 的生存时间 * * @param key * @param milliseconds * @param value * @return */ public String pSetEx(String key, Long milliseconds, String value) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.psetex(key, milliseconds, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将 key 中储存的数字值增一。 * 如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。 * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。 * 本操作的值限制在 64 位(bit)有符号数字表示之内 * * @param key * @return */ public Long incr(String key) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.incr(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将 key 中储存的数字加上指定的增量值。 * 如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCRBY 命令。 * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。 * 本操作的值限制在 64 位(bit)有符号数字表示之内 * * @param key * @param integer * @return */ public Long incrBy(String key, Long integer) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.incrBy(key, integer); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 为 key 中所储存的值加上指定的浮点数增量值。 * 如果 key 不存在,那么 INCRBYFLOAT 会先将 key 的值设为 0 ,再执行加法操作 * * @param key * @param value * @return */ public Double incrByFloat(String key, Double value) { Jedis jedis = null; Double res = null; try { jedis = pool.getResource(); res = jedis.incrByFloat(key, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将 key 中储存的数字值减一。 * 如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 DECR 操作。 * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。 * 本操作的值限制在 64 位(bit)有符号数字表示之内 * * @param key * @return */ public Long decr(String key) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.decr(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将 key 所储存的值减去指定的减量值。 * 如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 DECRBY 操作。 * 如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。 * 本操作的值限制在 64 位(bit)有符号数字表示之内 * * @param key * @param decrment * @return */ public Long decrBy(String key, Long decrment) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.decrBy(key, decrment); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于为指定的 key 追加值。 * 如果 key 已经存在并且是一个字符串, APPEND 命令将 value 追加到 key 原来的值的末尾。 * 如果 key 不存在, APPEND 就简单地将给定 key 设为 value ,就像执行 SET key value 一样。 * * @param key * @param value * @return */ public Long append(String key, String value) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.append(key, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /****************************** Redis 哈希(Hash) *********************************/ /** * 用于为哈希表中的字段赋值 。 * 如果哈希表不存在,一个新的哈希表被创建并进行 HSET 操作。 * 如果字段已经存在于哈希表中,旧值将被覆盖。 * * @param key * @param field * @param value * @return */ public Long hset(String key, String field, String value) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.hset(key, field, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key同时设置 hash的多个field * * @param key * @param hash * @return */ public Long hset(String key, Map<String, String> hash) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.hset(key, hash); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于删除哈希表 key 中的一个或多个指定字段,不存在的字段将被忽略 * * @param key * @param fields * @return 被成功删除字段的数量,不包括被忽略的字段 */ public Long hdel(String key, String... fields) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.hdel(key, fields); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于查看哈希表的指定字段是否存在 * * @param key * @param field * @return 如果哈希表含有给定字段,返回 1 。 如果哈希表不含有给定字段,或 key 不存在,返回 0 */ public Boolean hExists(String key, String field) { Jedis jedis = null; Boolean res = false; try { jedis = pool.getResource(); res = jedis.hexists(key, field); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于返回哈希表中指定字段的值 * * @param key * @param field * @return */ public String hget(String key, String field) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.hget(key, field); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key同时设置 hash的多个field * * @param key * @param hash * @return */ public String hmset(String key, Map<String, String> hash) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.hmset(key, hash); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于返回哈希表中,一个或多个给定字段的值。 * 如果指定的字段不存在于哈希表,那么返回一个 nil 值 * * @param key * @param fields * @return */ public List<String> hmget(String key, String... fields) { Jedis jedis = null; List<String> list = null; try { jedis = pool.getResource(); list = jedis.hmget(key, fields); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return list; } /** * 用于返回哈希表中,所有的字段和值。 * 在返回值里,紧跟每个字段名(field name)之后是字段的值(value),所以返回值的长度是哈希表大小的两倍 * * @param key * @return */ public Map<String, String> hGetAll(String key) { Jedis jedis = null; Map<String, String> res = null; try { jedis = pool.getResource(); res = jedis.hgetAll(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于为哈希表中的字段值加上指定增量值。 * 增量也可以为负数,相当于对指定字段进行减法操作。 * 如果哈希表的 key 不存在,一个新的哈希表被创建并执行 HINCRBY 命令。 * 如果指定的字段不存在,那么在执行命令前,字段的值被初始化为 0 。 * 对一个储存字符串值的字段执行 HINCRBY 命令将造成一个错误。 * 本操作的值被限制在 64 位(bit)有符号数字表示之内。 * * @param key * @param field * @param value * @return */ public long hincrBy(String key, String field, long value) { Jedis jedis = null; long res = 0L; try { jedis = pool.getResource(); res = jedis.hincrBy(key, field, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 于为哈希表中的字段值加上指定浮点数增量值。 * 如果指定的字段不存在,那么在执行命令前,字段的值被初始化为 0 * * @param key * @param field * @param value * @return */ public Double hincrbyfloat(String key, String field, Double value) { Jedis jedis = null; Double res = 0d; try { jedis = pool.getResource(); res = jedis.hincrByFloat(key, field, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 命令用于获取哈希表中的所有域(field) * * @param key * @return */ public Set<String> hkeys(String key) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.hkeys(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于获取哈希表中字段的数量 * * @param key * @return 当 key 不存在时,返回 0 */ public long hlen(String key) { Jedis jedis = null; long res = 0L; try { jedis = pool.getResource(); res = jedis.hlen(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于为哈希表中不存在的的字段赋值 。 * 如果哈希表不存在,一个新的哈希表被创建并进行 HSET 操作。 * 如果字段已经存在于哈希表中,操作无效。 * 如果 key 不存在,一个新哈希表被创建并执行 HSETNX 命令 * * @param key * @param field * @param value * @return */ public Long hsetnx(String key, String field, String value) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.hsetnx(key, field, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回哈希表所有域(field)的值 * * @param key * @return */ public List<String> hvals(String key) { Jedis jedis = null; List<String> res = null; try { jedis = pool.getResource(); res = jedis.hvals(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /************************************ Redis 列表(List)*******************************************/ /** * 将一个或多个值插入到列表头部。 如果 key 不存在,一个空列表会被创建并执行 LPUSH 操作。 当 key 存在但不是列表类型时,返回一个错误 * * @param key * @param strs * @return 列表的长度 */ public Long lpush(String key, String... strs) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.lpush(key, strs); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将一个值插入到已存在的列表头部,列表不存在时操作无效 * * @param key * @param strs * @return 列表的长度 */ public Long lpushx(String key, String... strs) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.lpushx(key, strs); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将一个或多个值插入到列表尾部。 如果 key 不存在,一个空列表会被创建并执行 LPUSH 操作。 当 key 存在但不是列表类型时,返回一个错误 * * @param key * @param strs * @return 列表的长度 */ public Long rpush(String key, String... strs) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.rpush(key, strs); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将一个值插入到已存在的列表尾部,列表不存在时操作无效 * * @param key * @param strs * @return 列表的长度 */ public Long rpushx(String key, String... strs) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.rpushx(key, strs); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 用于返回列表的长度。 如果列表 key 不存在,则 key 被解释为一个空列表,返回 0 。 如果 key 不是列表类型,返回一个错误 * * @param key * @return */ public Long llen(String key) { Jedis jedis = null; Long length = 0L; try { jedis = pool.getResource(); length = jedis.llen(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return length; } /** * 通过索引获取列表中的元素。你也可以使用负数下标,以 -1 表示列表的最后一个元素, -2 表示列表的倒数第二个元素,以此类推 * * @param key * @param index * @return */ public String lindex(String key, long index) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.lindex(key, index); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key从list的头部删除一个value,并返回该value * * @param key * @return */ public String lpop(String key) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.lpop(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } public List<String> blpop(int timeout, String key) { Jedis jedis = null; List<String> list = null; try { jedis = pool.getResource(); list = jedis.blpop(timeout, key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return list; } /** * 通过key从list的尾部删除一个value,并返回该value * * @param key * @return */ public String rpop(String key) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.rpop(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回列表中指定区间内的元素,区间以偏移量 START 和 END 指定。 其中 0 表示列表的第一个元素, 1 表示列表的第二个元素,以此类推。 * 你也可以使用负数下标,以 -1 表示列表的最后一个元素, -2 表示列表的倒数第二个元素,以此类推 * * @param key * @param start * @param end * @return */ public List<String> lrange(String key, long start, long end) { Jedis jedis = null; List<String> res = null; try { jedis = pool.getResource(); res = jedis.lrange(key, start, end); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * Lrem 根据参数 COUNT 的值,移除列表中与参数 VALUE 相等的元素。 * COUNT 的值可以是以下几种: * count > 0 : 从表头开始向表尾搜索,移除与 VALUE 相等的元素,数量为 COUNT 。 * count < 0 : 从表尾开始向表头搜索,移除与 VALUE 相等的元素,数量为 COUNT 的绝对值。 * count = 0 : 移除表中所有与 VALUE 相等的值。 * * @param key * @param count * @param value * @return */ public Long lrem(String key, long count, String value) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.lrem(key, count, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过索引来设置元素的值。 * 当索引参数超出范围,或对一个空列表进行 LSET 时,返回一个错误 * * @param key * @param index * @param value * @return */ public String lset(String key, Long index, String value) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.lset(key, index, value); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /*****************************Redis 集合(Set)**************************************/ public Long sadd(String key, String... members) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.sadd(key, members); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回集合中元素的数量 * 通过key获取set中value的个 * * @param key * @return */ public Long scard(String key) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.scard(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回给定集合之间的差集。不存在的集合 key 将视为空集。 * 差集的结果来自前面的 FIRST_KEY ,而不是后面的 OTHER_KEY1,也不是整个 FIRST_KEY OTHER_KEY1..OTHER_KEYN 的差集 * * @param keys * @return */ public Set<String> sdiff(String... keys) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.sdiff(keys); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将给定集合之间的差集存储在指定的集合中。如果指定的集合 key 已存在,则会被覆盖 * * @param dstkey * @param keys * @return */ public Long sdiffstore(String dstkey, String... keys) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.sdiffstore(dstkey, keys); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * <p> * 通过key判断value是否是set中的元素 * </p> * * @param key * @param member * @return */ public Boolean sismember(String key, String member) { Jedis jedis = null; Boolean res = null; try { jedis = pool.getResource(); res = jedis.sismember(key, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * <p> * 通过key获取set中所有的value * </p> * * @param key * @return */ public Set<String> smembers(String key) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.smembers(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 指定成员 member 元素从 source 集合移动到 destination 集合。 * SMOVE 是原子性操作。 * 如果 source 集合不存在或不包含指定的 member 元素,则 SMOVE 命令不执行任何操作,仅返回 0 。否则, member 元素从 source 集合中被移除,并添加到 destination 集合中去。 * 当 destination 集合已经包含 member 元素时, SMOVE 命令只是简单地将 source 集合中的 member 元素删除。 * 当 source 或 destination 不是集合类型时,返回一个错误。 * * @param srckey 要移除的 * @param dstkey 添加 * @param member set中的value * @return */ public Long smove(String srckey, String dstkey, String member) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.smove(srckey, dstkey, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * <p> * 通过key随机删除个set中的value并返回该 * </p> * * @param key * @return */ public String spop(String key) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.spop(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * <p> * 通过key获取set中随机的value,不删除元 * </p> * * @param key * @return */ public String srandmember(String key) { Jedis jedis = null; String res = null; try { jedis = pool.getResource(); res = jedis.srandmember(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 被成功移除的元素的数量,不包括被忽略的元素。 * * @param key * @param values * @return */ public Long srem(String key, String... values) { Jedis jedis = null; Long removeTotal = null; try { jedis = pool.getResource(); removeTotal = jedis.srem(key, values); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return removeTotal; } /** * 通过key返回有set的并 * * @param keys 可以使一个string 也可以是个string数组 * @return 返回给定集合的并集。不存在的集合 key 被视为空集 */ public Set<String> sunion(String... keys) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.sunion(keys); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 将给定集合的并集存储在指定的集合 destination 中。如果 destination 已经存在,则将其覆盖 * * @param dstkey * @param keys 可以使一个string 也可以是个string数组 * @return */ public Long sunionstore(String dstkey, String... keys) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.sunionstore(dstkey, keys); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } public ScanResult<String> sscan(String key, String cursor) { Jedis jedis = null; ScanResult<String> res = null; try { jedis = pool.getResource(); res = jedis.sscan(key, cursor); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /*******************************************Redis 有序集合(sorted set)****************************/ /** * 用于将一个或多个成员元素及其分数值加入到有序集当中。 * 如果某个成员已经是有序集的成员,那么更新这个成员的分数值,并通过重新插入这个成员元素,来保证该成员在正确的位置上。 * 分数值可以是整数值或双精度浮点数。 * 如果有序集合 key 不存在,则创建一个空的有序集并执行 ZADD 操作。 * 当 key 存在但不是有序集类型时,返回一个错误。 * 注意: 在 Redis 2.4 版本以前, ZADD 每次只能添加一个元素。 * * @param key * @param score * @param member * @return */ public Long zadd(String key, Double score, String member) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zadd(key, score, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key向zset中添加value,score,其中score就是用来排序 如果该value已经存在则根据score更新元素 * * @param key * @param scoreMembers * @return */ public Long zadd(String key, Map<String, Double> scoreMembers) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zadd(key, scoreMembers); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key返回zset中的value个数 * * @param key * @return */ public Long zcard(String key) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zcard(key); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 计算有序集合中指定分数区间的成员数量 * * @param key * @param min * @param max * @return */ public Long zcount(String key, String min, String max) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zcount(key, min, max); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * Zincrby 命令对有序集合中指定成员的分数加上增量 increment * 可以通过传递一个负数值 increment ,让分数减去相应的值,比如 ZINCRBY key -5 member ,就是让 member 的 score 值减去 5 。 * 当 key 不存在,或分数不是 key 的成员时, ZINCRBY key increment member 等同于 ZADD key increment member 。 * 当 key 不是有序集类型时,返回一个错误。 * 分数值可以是整数值或双精度浮点数 * * @param key * @param score * @param member * @return */ public Double zincrby(String key, double score, String member) { Jedis jedis = null; Double res = null; try { jedis = pool.getResource(); res = jedis.zincrby(key, score, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * Zinterstore 命令计算给定的一个或多个有序集的交集,其中给定 key 的数量必须以 numkeys 参数指定,并将该交集(结果集)储存到 destination 。 * 默认情况下,结果集中某个成员的分数值是所有给定集下该成员分数值之和。 * * @param deskey * @param sets * @return */ public Long zinterstore(String deskey, String... sets) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zinterstore(deskey, sets); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 在计算有序集合中指定字典区间内成员数量 * * @param key * @param min * @param max * @return */ public Long zlexcount(String key, String min, String max) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zlexcount(key, min, max); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回有序集中,指定区间内的成员。 * 其中成员的位置按分数值递增(从小到大)来排序。 * 具有相同分数值的成员按字典序(lexicographical order )来排列。 * 如果你需要成员按 * 值递减(从大到小)来排列,请使用 ZREVRANGE 命令。 * 下标参数 start 和 stop 都以 0 为底,也就是说,以 0 表示有序集第一个成员,以 1 表示有序集第二个成员,以此类推。 * 你也可以使用负数下标,以 -1 表示最后一个成员, -2 表示倒数第二个成员,以此类推 * * @param key * @param start * @param end * @return */ public Set<String> zRange(String key, Long start, Long end) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.zrange(key, start, end); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 字典区间返回有序集合的成员 * * @param key * @param min * @param max * @return */ public Set<String> zRangeByLex(String key, String min, String max) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.zrangeByLex(key, min, max); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key返回指定score内zset中的value * * @param key * @param max * @param min * @return */ public Set<String> zrangeByScore(String key, String max, String min) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.zrangeByScore(key, max, min); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key返回指定score内zset中的value * * @param key * @param max * @param min * @return */ public Set<String> zrangeByScore(String key, double max, double min) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.zrangeByScore(key, max, min); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key返回zset中value的排 下标从小到大排序 * 返回有序集中指定成员的排名。其中有序集成员按分数值递增(从小到大)顺序排列 * * @param key * @param member * @return */ public Long zrank(String key, String member) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zrank(key, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key删除在zset中指定的value * * @param key * @param members 可以使一个string 也可以是个string数组 * @return */ public Long zrem(String key, String... members) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zrem(key, members); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key删除给定区间内的元素 * * @param key * @param start * @param end * @return */ public Long zremrangeByRank(String key, long start, long end) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zremrangeByRank(key, start, end); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key删除指定score内的元素 * * @param key * @param start * @param end * @return */ public Long zremrangeByScore(String key, double start, double end) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zremrangeByScore(key, start, end); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key将获取score从start到end中zset的value socre从大到小排序 当start0 end-1时返回全 * * @param key * @param start * @param end * @return */ public Set<String> zrevrange(String key, long start, long end) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.zrevrange(key, start, end); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回有序集中指定分数区间内的所有的成员。有序集成员按分数值递减(从大到小)的次序排列。 * 具有相同分数值的成员按字典序的逆序(reverse lexicographical order )排列。 * 除了成员按分数值递减的次序排列这一点外, ZREVRANGEBYSCORE 命令的其他方面和 ZRANGEBYSCORE 命令一样 * * @param key * @param max * @param min * @return */ public Set<String> zrevrangeByScore(String key, String max, String min) { Jedis jedis = null; Set<String> res = null; try { jedis = pool.getResource(); res = jedis.zrevrangeByScore(key, max, min); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 通过key返回zset中value的排 下标从大到小排序 * * @param key * @param member * @return */ public Long zrevrank(String key, String member) { Jedis jedis = null; Long res = null; try { jedis = pool.getResource(); res = jedis.zrevrank(key, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } /** * 返回有序集中,成员的分数值。 如果成员元素不是有序集 key 的成员,或 key 不存在,返回 null * * @param key * @param member * @return */ public Double zscore(String key, String member) { Jedis jedis = null; Double res = null; try { jedis = pool.getResource(); res = jedis.zscore(key, member); } catch (Exception e) { close(jedis); e.printStackTrace(); } finally { close(jedis); } return res; } }
package anthonysierra.com.notificationchannels; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String notificationChannelId = "com_anthonysierra_NotificationChannels_01"; NotificationManager notificationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); createNotificationChannel(); } /** * Sends a notification to the user via the the channel. * * @param view */ public void sendNotification(final View view) { final Notification notification = new Notification.Builder(this) .setContentTitle("Fake notification") .setContentText("Some useful text") .setSmallIcon(android.R.drawable.alert_light_frame) .setChannel(notificationChannelId) .build(); notificationManager.notify(1, notification); } /** * Creates the notification channel that will show up in the settings page for this app. */ private void createNotificationChannel() { notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); final NotificationChannel channel = new NotificationChannel(notificationChannelId, "Hello", NotificationManager.IMPORTANCE_LOW); notificationManager.createNotificationChannel(channel); } }
package seedu.project.logic.parser; import static seedu.project.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.project.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.project.logic.commands.AddCommand; import seedu.project.logic.commands.AddTagCommand; import seedu.project.logic.commands.AnalyseCommand; import seedu.project.logic.commands.ClearCommand; import seedu.project.logic.commands.Command; import seedu.project.logic.commands.CompareCommand; import seedu.project.logic.commands.CompletedCommand; import seedu.project.logic.commands.DefineTagCommand; import seedu.project.logic.commands.DeleteCommand; import seedu.project.logic.commands.EditCommand; import seedu.project.logic.commands.ExitCommand; import seedu.project.logic.commands.ExportCommand; import seedu.project.logic.commands.FindCommand; import seedu.project.logic.commands.HelpCommand; import seedu.project.logic.commands.HistoryCommand; import seedu.project.logic.commands.ImportCommand; import seedu.project.logic.commands.ListCommand; import seedu.project.logic.commands.ListProjectCommand; import seedu.project.logic.commands.ListTagCommand; import seedu.project.logic.commands.RedoCommand; import seedu.project.logic.commands.SelectCommand; import seedu.project.logic.commands.SortByDeadlineCommand; import seedu.project.logic.commands.TaskHistoryCommand; import seedu.project.logic.commands.UndoCommand; import seedu.project.logic.parser.exceptions.ParseException; /** * Parses user input. */ public class ProjectParser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input * @throws ParseException if the user input does not conform the expected format */ public Command parseCommand(String userInput) throws ParseException { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return new AddCommandParser().parse(arguments); case AddCommand.COMMAND_ALIAS: return new AddCommandParser().parse(arguments); case CompareCommand.COMMAND_WORD: return new CompareCommandParser().parse(arguments); case CompareCommand.COMMAND_ALIAS: return new CompareCommandParser().parse(arguments); case CompletedCommand.COMMAND_WORD: return new CompletedCommandParser().parse(arguments); case CompletedCommand.COMMAND_ALIAS: return new CompletedCommandParser().parse(arguments); case AnalyseCommand.COMMAND_WORD: return new AnalyseCommand(); case AnalyseCommand.COMMAND_ALIAS: return new AnalyseCommand(); case DefineTagCommand.COMMAND_WORD: return new DefineTagCommandParser().parse(arguments); case DefineTagCommand.COMMAND_ALIAS: return new DefineTagCommandParser().parse(arguments); case AddTagCommand.COMMAND_WORD: return new AddTagCommandParser().parse(arguments); case AddTagCommand.COMMAND_ALIAS: return new AddTagCommandParser().parse(arguments); case TaskHistoryCommand.COMMAND_WORD: return new TaskHistoryCommandParser().parse(arguments); case TaskHistoryCommand.COMMAND_ALIAS: return new TaskHistoryCommandParser().parse(arguments); case EditCommand.COMMAND_WORD: return new EditCommandParser().parse(arguments); case EditCommand.COMMAND_ALIAS: return new EditCommandParser().parse(arguments); case SelectCommand.COMMAND_WORD: return new SelectCommandParser().parse(arguments); case SelectCommand.COMMAND_ALIAS: return new SelectCommandParser().parse(arguments); case DeleteCommand.COMMAND_WORD: return new DeleteCommandParser().parse(arguments); case DeleteCommand.COMMAND_ALIAS: return new DeleteCommandParser().parse(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case ClearCommand.COMMAND_ALIAS: return new ClearCommand(); case FindCommand.COMMAND_WORD: return new FindCommandParser().parse(arguments); case FindCommand.COMMAND_ALIAS: return new FindCommandParser().parse(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ListCommand.COMMAND_ALIAS: return new ListCommand(); case ListTagCommand.COMMAND_ALIAS: return new ListTagCommand(); case ListTagCommand.COMMAND_WORD: return new ListTagCommand(); case ListProjectCommand.COMMAND_WORD: return new ListProjectCommand(); case ListProjectCommand.COMMAND_ALIAS: return new ListProjectCommand(); case HistoryCommand.COMMAND_WORD: return new HistoryCommand(); case HistoryCommand.COMMAND_ALIAS: return new HistoryCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case UndoCommand.COMMAND_WORD: return new UndoCommand(); case UndoCommand.COMMAND_ALIAS: return new UndoCommand(); case RedoCommand.COMMAND_WORD: return new RedoCommand(); case RedoCommand.COMMAND_ALIAS: return new RedoCommand(); case ImportCommand.COMMAND_WORD: return new ImportCommandParser().parse(arguments); case ImportCommand.COMMAND_ALIAS: return new ImportCommandParser().parse(arguments); case ExportCommand.COMMAND_WORD: return new ExportCommandParser().parse(arguments); case ExportCommand.COMMAND_ALIAS: return new ExportCommandParser().parse(arguments); case SortByDeadlineCommand.COMMAND_WORD: return new SortByDeadlineCommand(); case SortByDeadlineCommand.COMMAND_ALIAS: return new SortByDeadlineCommand(); default: throw new ParseException(MESSAGE_UNKNOWN_COMMAND); } } }
/* * 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 Cafe; /** * * @author renan */ public class SystemOut { public void outPrintCoffeOrder(Order order, Calculate calculate) { System.out.println( "Tamanho da xicara: " + order.getOrderCoffeSize() + "\n" + "Sabores: " + order.getOrderCoffeFlavors() + "\n" + "Sabor dos adicionais: " + order.getOrderCoffeAddictionFlavor() + "\n" + "Valor Total: R$" + calculate.calculate(order) ); } public void outPrintAll(Order order, Calculate calculate) { outPrintCoffeOrder(order, calculate); System.out.println("Valor Total: R$" + calculate.calculate(order)); } }
package com.cn.ouyjs.RabbitMq; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import java.util.concurrent.CountDownLatch; /** * @author ouyjs * @date 2019/8/1 17:57 */ @SpringBootTest(classes = ThreadTest.class) @RunWith(SpringJUnit4ClassRunner.class) public class ThreadTest { private final String url = "www.baidu.com"; private RestTemplate restTemplate = new RestTemplate(); private static final int USER_NUMS = 1; @Test public void main(String[] args) { for (int i = 0; i < USER_NUMS; i++ ) { new Thread(new MyThread()).start(); } } public class MyThread implements Runnable{ @Override public void run() { String result = restTemplate.getForEntity(url,String.class).getBody(); System.out.println(result); } } }
package com.example.demo.mapper; import com.baomidou.mybatisplus.plugins.pagination.Pagination; import com.example.demo.entity.Register; import com.baomidou.mybatisplus.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; /** * <p> * Mapper 接口 * </p> * * @author weifucheng * @since 2017-11-24 */ public interface RegisterMapper extends BaseMapper<Register> { @Select("select * from register") public List<Register> selectAll(Pagination page); @Select("select * from register ${sql}") public List<Register> selectListByFilter(@Param("sql") String sql,Pagination page); @Select("select * from register ${sql}") public List<Register> selectListByFilter(@Param("sql") String sql); @Select("${sql}") public List<Map<String,Object>> selectListBysql(@Param("sql") String sql); @Select("select * from register ${sql}") public List<Map<String,Object>> selectListMapByFilter(@Param("sql") String sql,Pagination page); @Select("select count(1) from register ${sql}") public int selectCountByFilter(@Param("sql") String sql); @Select("${sql}") public List<Map<String,Object>> selectListMapByFilter(@Param("sql") String sql,@Param("list") List list); @Select("${sql}") public Integer selectListMapCountByFilter(@Param("sql") String sql,@Param("list") List list); }
package com.rengu.operationsoanagementsuite.Entity; import java.io.Serializable; import java.util.List; public class DeployStatusEntity implements Serializable { private String ip; private boolean deploying = true; private double progress = 0; private double transferRate = 0; private List<DeployLogDetailEntity> errorFileList; private List<DeployLogDetailEntity> completedFileList; public DeployStatusEntity() { } public DeployStatusEntity(String ip) { this.ip = ip; this.deploying = true; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public boolean isDeploying() { return deploying; } public void setDeploying(boolean deploying) { this.deploying = deploying; } public double getProgress() { return progress; } public void setProgress(double progress) { this.progress = progress; } public double getTransferRate() { return transferRate; } public void setTransferRate(double transferRate) { this.transferRate = transferRate; } public List<DeployLogDetailEntity> getErrorFileList() { return errorFileList; } public void setErrorFileList(List<DeployLogDetailEntity> errorFileList) { this.errorFileList = errorFileList; } public List<DeployLogDetailEntity> getCompletedFileList() { return completedFileList; } public void setCompletedFileList(List<DeployLogDetailEntity> completedFileList) { this.completedFileList = completedFileList; } }
package nesto.base.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.os.Looper; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import nesto.base.global.A; /** * Created on 2016/4/8. * By nesto */ public class AppUtil { @Retention(RetentionPolicy.SOURCE) @IntDef({Toast.LENGTH_SHORT, Toast.LENGTH_LONG}) public @interface Duration { } private static Toast toast = null; public static void showToast(Object text) { showToast(text, Toast.LENGTH_SHORT); } public static void showToast(Object text, @Duration int length) { //先检查是否在主线程中运行,再进行处理 if (Looper.myLooper() == Looper.getMainLooper()) { Context context = A.getContext(); String showText = String.valueOf(text); if (toast == null) { toast = Toast.makeText(context, showText, length); } else { toast.setText(showText); toast.setDuration(length); } toast.show(); } else { LogUtil.e("show toast run in wrong thread"); } } public static void showToast(@StringRes int textId) { showToast(textId, Toast.LENGTH_SHORT); } public static void showToast(@StringRes int textResId, @Duration int length) { String text = A.getInstance().getBaseContext().getString(textResId); showToast(text, length); } public static void hideSoftKeyboard(Context context, EditText editText) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(editText.getWindowToken(), 0); } public static String getCurrentTime() { Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HHmmss", Locale.getDefault()); return dateFormat.format(now); } public static boolean checkPhoneNum(String input) { Pattern p = Pattern.compile("^(?:(?:\\+|00)?(86|886|852|853))?(1\\d{10})$"); Matcher m = p.matcher(input.replaceAll("-", "")); boolean isPhoneNumber = true; // group中 0为原字符串 // 1为匹配到的移动电话国家/地区码 // 2为国内有效号码 while (m.find()) { isPhoneNumber = (m.group(2) != null); } return m.matches() && isPhoneNumber; } /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * 获取文件名称 拍照时调用 * * @param path dir path * @return image path */ public static String getPictureName(String path) { String pictureName; String state = Environment.getExternalStorageState();// 获取sd卡根目录 if (!state.equals(Environment.MEDIA_MOUNTED)) {// 检测sd卡是否可以读写 showToast("can't find your storage!", Toast.LENGTH_LONG); } File directory = new File(path); if (!directory.exists()) {// 判断文件(夹)是否存在 Log.v("takePicture", "Making directory."); if (!directory.mkdirs()) {// 创建一个文件(夹),如不成功toast showToast("can't create folder", Toast.LENGTH_LONG); } } pictureName = getCurrentTime() + ".jpg"; return path + File.separator + pictureName; } /** * 添加动态扫描库 * * @param absolutePath 绝对路径 */ public static void addToMedia(final String absolutePath) { final Context context = A.getContext(); if (absolutePath == null) return; Uri data = Uri.parse(absolutePath); context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data)); new MediaScannerConnection.MediaScannerConnectionClient() {// 添加扫描库 MediaScannerConnection msc = null; { msc = new MediaScannerConnection(context, this); msc.connect(); } @Override public void onScanCompleted(String path, Uri uri) { msc.disconnect(); } @Override public void onMediaScannerConnected() { msc.scanFile(absolutePath, null); } }; } public static void acquireScreenOn(Activity activity) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } public static void releaseScreenOn(Activity activity) { activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } public static void hideSoftKeyboard(@NonNull Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService( Activity.INPUT_METHOD_SERVICE); View view = activity.getCurrentFocus(); if (view != null) { inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } } public static void setupUI(View view, final Activity activity) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { try { // 寻找class ListenerInfo Class clazz = Class.forName("android.view.View$ListenerInfo"); // 获得field mListenerInfo和mOnTouchListener Field listenerInfo = View.class.getDeclaredField("mListenerInfo"); listenerInfo.setAccessible(true); Field field = clazz.getDeclaredField("mOnTouchListener"); field.setAccessible(true); Object object = listenerInfo.get(view); final View.OnTouchListener listener; // 不为空时在原来OnTouchListener的基础上增加hideSoftKeyboard if (object != null && (listener = (View.OnTouchListener) field.get(object)) != null) { view.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { hideSoftKeyboard(activity); listener.onTouch(v, event); return false; } }); } else { // 出错或为空时直接设置 setNewOnTouchListener(view, activity); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) { setNewOnTouchListener(view, activity); } } //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView, activity); } } } private static void setNewOnTouchListener(View v, final Activity activity) { v.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { hideSoftKeyboard(activity); return false; } }); } //将json从assets复制到cache中 public static void copyToCache(String name) { InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { fileOutputStream = A.getContext().openFileOutput(name, Context.MODE_PRIVATE); inputStream = A.getContext().getAssets().open("" + name); String s = isToString(inputStream); fileOutputStream.write(s.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } } private static String isToString(InputStream is) { String result = ""; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while (-1 != (len = is.read(buffer))) { outputStream.write(buffer, 0, len); } result = new String(outputStream.toByteArray()); } catch (Exception e) { e.printStackTrace(); } return result; } }
package com.qf.demo.service.Impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.qf.demo.dao.StuMapper; import com.qf.demo.entity.Student; import com.qf.demo.service.Stuservice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StuImplservice extends ServiceImpl<StuMapper, Student> implements Stuservice { @Autowired private StuMapper stuMapper; }
package com.example.lamelameo.picturepuzzle.unused; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.core.view.GestureDetectorCompat; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import java.util.ArrayList; import java.util.Random; public class ImageAdapter extends BaseAdapter { private Context mContext; private ArrayList<Drawable> mBitmaps; private int mGridWidth; private boolean isShown; private String TAG = "ImageAdapter"; private ArrayList<ArrayList<ImageView>> cellRows, cellCols; private ArrayList<ImageView> gridCells; private int gridRows; private ArrayList<Integer> positionPool; private Random rng; private int bounds; private View.OnTouchListener swipeListener; public ArrayList<ImageView> getRow(int index) { return cellRows.get(index); } public ArrayList<ImageView> getCol(int index) { return cellCols.get(index); } public ImageAdapter(Context c, ArrayList<Drawable> bitmaps, int gridWidth, View.OnTouchListener onTouchListener) { mContext = c; mBitmaps = bitmaps; mGridWidth = gridWidth; swipeListener = onTouchListener; gridRows = (int)Math.sqrt(bitmaps.size()); // initialise objects for randomisation of images rng = new Random(); bounds = gridRows*gridRows-1; positionPool = new ArrayList<>(); for (int x=0; x<gridRows*gridRows; x++) { positionPool.add(x); } //TODO: if allow for m x n grid size then have to change stuff here // initialise lists to hold grid objects gridCells = new ArrayList<ImageView>(); cellRows = new ArrayList<>(); cellCols = new ArrayList<>(); for (int x=0; x<gridRows; x++) { cellRows.add(new ArrayList<ImageView>()); cellCols.add(new ArrayList<ImageView>()); } } public int getGridRows() { return gridRows; } public int getCount() { return mBitmaps.size(); } public Object getItem(int position) { return gridCells.get(position); } public long getItemId(int position) { return position; } public int getItemViewType(int position) { return 0; } public int getViewTypeCount() { return 1; } @Override public View getView(final int position, View convertView, ViewGroup parent) { Log.i(TAG, "getViewTest: "); final ImageView imageView; // int rngBitmapIndex; // final LayoutInflater inflater = ((Activity) mContext).getLayoutInflater(); if(convertView == null) { Log.i(TAG, "convertView=null: "+position); // View item = inflater.inflate(R.layout.puzzle_view, parent, false); imageView = new ImageView(mContext); convertView = imageView; // set cell size using params //TODO: divide based on what grid size is selected int size = mGridWidth/gridRows; // cell size in px based on grid size which may be scaled down // Log.i("cellsize", "getView: "+size); imageView.setLayoutParams(new ViewGroup.LayoutParams(size, size)); //TODO: an extra call to getview where convertview=null for position = 0 which causes a bug where an empty // cell to appears in pos 7 (8thcell) after moving empty from it to one above (4thcell) // probably due to the extra empty imageview added to row/col lists which had no tag so set neighbour cell empty // used to stop extra call to getView where convertView=null to add an extra imageview to row/col and // prevent error with setting imageviews drawable (bounds=0 gives an error) if (position == 0 && bounds == 0) { Log.i(TAG, "pos0 bound0 "); return imageView; } // add imageviews to row and column lists for access //TODO: divide/multiply by amount of cols/rows int cellRow = (int)Math.floor(position/(float)gridRows); int cellCol = position - cellRow*gridRows; gridCells.add(imageView); cellRows.get(cellRow).add(imageView); cellCols.get(cellCol).add(imageView); // setting images and tags for cells if (position == mBitmaps.size() - 1) { // leave last cell with no image imageView.setTag(position); // set all other cells with a randomised image excluding the last cells image as it must be empty } else { //TODO: HAVE TO MAKE A NEW RANDOMISE FUNCTION AS THIS PRODUCES UNSOLVABLE PUZZLES // get random number from a pool of ints: zero - number of cells-1, and set cell image as the bitmap at this index int randIndex = rng.nextInt(bounds); // gets a randomised number within the pools bounds // Log.i(TAG, "randomNum " + randIndex); int rngBitmapIndex = positionPool.get(randIndex); // get the bitmap index from the pool using the randomised number // Log.i(TAG, "randomIndex " + rngBitmapIndex); positionPool.remove((Integer) rngBitmapIndex); // remove used number from the pool - use Integer else it takes as Arrayindex // Log.i(TAG, "randomPool " + positionPool); bounds -= 1; // lower the bounds by 1 to match the new pool size so the next cycle can function properly // Log.i(TAG, "randomBounds " + bounds); // set the cells starting image imageView.setImageDrawable(mBitmaps.get(rngBitmapIndex)); //set cell tags corresponding to the set image for tracking/identification purposes imageView.setTag(rngBitmapIndex); } imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "onClick:"); } }); imageView.setOnTouchListener(swipeListener); //TODO: changed to onitemclicklistener implemented in the activity instead due to problems with 1st cell clicks } else { Log.i(TAG, "convertView=NOTNULL"); imageView = (ImageView) convertView; } return imageView; } private Integer[] mImageIds = { // get image from default pics or take a photo and create grid of smaller images //TODO: set onclicklistener for each item which changes the set image }; }
/** * WebSocket integration for Spring's messaging module. */ @NonNullApi @NonNullFields package org.springframework.web.socket.messaging; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
public class ObjectParseParameter { public ObjectParseParameter() { String s = null; Long number = null; foo1(s, number); System.out.println(s); System.out.println(number); } private void foo(String s, Long number) { s = "LTTD"; number = 1L; } private void foo1(Object s, Object number) { s = "LTTD"; number = 1L; } public static void main(String[] args) { new ObjectParseParameter(); } }
package modele; /** * Créé par victor le 28/03/18. */ public class Case { private Lien entree = Lien.NONE; private Lien sortie = Lien.NONE; public final int ligne; public final int colonne; public final int symbole; private Chemin chemin; Case(int ligne, int colonne, int symbole) { this.ligne = ligne; this.colonne = colonne; this.symbole = symbole; } public Chemin getChemin() { return chemin; } public void setChemin(Chemin chemin) { this.chemin = chemin; } public boolean hasChemin() { return this.chemin != null; } public boolean hasSymbol() { return this.symbole != 0; } public boolean isPair(Case other) { return this.symbole == other.symbole && this.hashCode() != other.hashCode(); } @Override public String toString() { return String.valueOf(this.symbole); } private Lien getCote(Case other) { if (this.ligne == other.ligne) { if (other.colonne == this.colonne - 1) { return Lien.LEFT; } else if (other.colonne == this.colonne + 1) { return Lien.RIGHT; } } else if (this.colonne == other.colonne) { if (other.ligne == this.ligne - 1) { return Lien.TOP; } else if (other.ligne == this.ligne + 1) { return Lien.BOTTOM; } } return Lien.NONE; } public boolean estVoisine(Case other) { return this.getCote(other) != Lien.NONE; } public void setEntree(Case other) { this.entree = this.getCote(other); } public void setSortie(Case other) { this.sortie = this.getCote(other); } public Lien getEntree() { return entree; } public Lien getSortie() { return sortie; } public void reset() { this.chemin = null; this.entree = Lien.NONE; this.sortie = Lien.NONE; } }
package com.nsi.clonebin.controller; import com.nsi.clonebin.model.dto.UserRegistrationDTO; import com.nsi.clonebin.model.entity.UserAccount; import com.nsi.clonebin.service.UserAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/registration") public class RegistrationController { private final UserAccountService userAccountService; @Autowired public RegistrationController(UserAccountService userAccountService) { this.userAccountService = userAccountService; } @ModelAttribute("userAccount") public UserRegistrationDTO userRegistrationDTO() { return new UserRegistrationDTO(); } @GetMapping public String showRegistrationFrom() { return "registration"; } @PostMapping public String registerUser(@ModelAttribute("userAccount") UserRegistrationDTO registrationDTO) { UserAccount userAccount = userAccountService.getByUsername(registrationDTO.getUsername()); if (userAccount == null) { userAccountService.save(registrationDTO); return "redirect:/registration?success"; } return "redirect:/registration?duplicateUsername"; } }
package com.example.zhengzeqin.mymessageboard.model; import org.litepal.crud.DataSupport; import java.io.Serializable; /** * Created by zhengzeqin on 2017/11/26. */ public class UserModel extends DataSupport implements Serializable { /**/ private int id; //用户名 private String userName; /*账户*/ private String userAccount; /*密码*/ private String userPassword; /*-1: 普通会员 1:管理者 0:黑名单*/ private int authority; /*是否当前操作对象*/ private boolean isCurrentUse; /*是否之前登录*/ private boolean isHadLogin; /*setter getter*/ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public int getAuthority() { return authority; } public void setAuthority(int authority) { this.authority = authority; } public boolean isCurrentUse() { return isCurrentUse; } public void setCurrentUse(boolean currentUse) { isCurrentUse = currentUse; } public boolean isHadLogin() { return isHadLogin; } public void setHadLogin(boolean hadLogin) { isHadLogin = hadLogin; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } // public UserModel(String userAccount, String userPassword, int authority, boolean isCurrentUse) { // this.userAccount = userAccount; // this.userPassword = userPassword; // this.authority = authority; // this.isCurrentUse = isCurrentUse; // } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.vebo.util; import java.text.DecimalFormat; /** * * @author mohfus */ public class DoubleUtil { private DecimalFormat formatador; public DoubleUtil() { formatador = new DecimalFormat("###.00"); } public Double stringParaDouble(String numero) { try { Double retorno = formatador.parse(numero).doubleValue(); return retorno; } catch(Exception e) { return null; } } public String doubleParaString(Double numero) { try { String retorno = formatador.format(numero); return retorno; } catch(Exception e) { return ""; } } public String doubleParaString(Double numero, String formato) { try { DecimalFormat formatadorEspecifico = new DecimalFormat(formato); String retorno = formatadorEspecifico.format(numero); return retorno; } catch(Exception e) { return ""; } } }
package controllers; import com.fasterxml.jackson.databind.JsonNode; import java.util.List; import model.ProductNODATABASE; import play.libs.Json; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; /** * CONTROLLER */ public class ProductsNODATABASE extends Controller{ // das NEUE PLAY Framework verlangt hier im Controller KEINE STATISCHEN METHODEN, ergibt sonst Fehler! public Result list() { List<ProductNODATABASE> products = ProductNODATABASE.findAll(); // JsonNode : Jackson // Json: Json Helper aus play.libs JsonNode json = Json.toJson(products); return ok(json); } public Result details(String ean) { return ok(); } // hiermit bekommen wir den Request Body! @BodyParser.Of(BodyParser.Json.class) public Result newProduct() { JsonNode json = request().body().asJson(); ProductNODATABASE newProduct = Json.fromJson(json, ProductNODATABASE.class); // zur Produktliste hinzufuegen! ProductNODATABASE.addProduct(newProduct); // man kann es wieder zurueckgeben, ist aber eine Designfrage return ok(Json.toJson(newProduct)); } }
package basis.chapter01; /** * Created by Administrator on 2015/4/11. * */ public class SleepTest{ public static void main (String[] args){ String[] arg = {"one","two","three","four"}; long start = System.nanoTime(); for (int i=0; i<arg.length;i++){ try { System.out.println(arg[i]); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } long end = System.nanoTime(); System.out.println("总的时间" + (end-start)/1000000); } }
package com.rcmapps.viperonandroid.di; import android.content.Context; import com.rcmapps.viperonandroid.repository.SharedPreferenceRepo; import com.rcmapps.viperonandroid.repository.impls.SharedPreferenceRepoImpl; public class AppModuleImpl implements AppModule { private final SharedPreferenceRepoImpl sharedPreferenceRepo; public AppModuleImpl(Context context) { sharedPreferenceRepo = new SharedPreferenceRepoImpl(context); } @Override public SharedPreferenceRepo getSharedPrefRepo() { return sharedPreferenceRepo; } }
package main.java.oop.static3; public class Test03 { public static void main(String[] args) { // Static Method 는 객체 생성 없이 접근 가능하다. long totla = Calculator.plus(10L, 20L); System.out.println(totla); } }
import java.io.*; import java.util.*; import java.util.function.*; import java.util.stream.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static String isValid(String s){ Map<Long, Long> frequencyMap = s.chars(). boxed(). collect(Collectors.groupingBy(Function.identity(), Collectors.counting())). values(). stream(). collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); if(frequencyMap.size() <= 1) { return "YES"; } if(frequencyMap.size() == 2) { Map.Entry[] frequencyEntries = new Map.Entry[2]; int index = 0; for(Map.Entry fme : frequencyMap.entrySet()) { frequencyEntries[index++] = fme; } long f1 = (Long)frequencyEntries[0].getKey(); long f1Count = (Long)frequencyEntries[0].getValue(); long f2 = (Long)frequencyEntries[1].getKey(); long f2Count = (Long)frequencyEntries[1].getValue(); if(Math.min(f1, f2) == 1 && (f1 == Math.min(f1, f2) ? f1Count : f2Count) == 1) { return "YES"; } else if(Math.abs(f1 - f2) > 1) { return "NO"; } else if(Math.min(f1Count, f2Count) > 1) { return "NO"; } return "YES"; } else { return "NO"; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); String result = isValid(s); System.out.println(result); } }
/* * ResultXML.java * TODO writer,reader */ package Graph; import java.lang.reflect.*; import java.util.Vector; import org.graphstream.graph.Graph; import org.graphstream.graph.implementations.DefaultGraph; import org.graphstream.stream.file.FileSource; import org.graphstream.stream.file.FileSourceFactory; import java.io.*; public class ResultXML { Graph g = new DefaultGraph("g"); //==== Object for opening and saving GraphML files public ResultXML() { } //################################################################################################ // Save the graph in DGS file format public boolean writeFile(Graph graph, String fileName) { Graph writeGraph = graph; try { //=== See if the file exists, if so overwrite it, if not create a new file and write to it File newFile = new File(fileName); if (newFile.exists()) { writeGraph.write(fileName); } else { writeGraph.write(fileName); } return true; } catch(Exception e){ System.out.println("Exception "+ e); return false; } } //################################################################################################ // Open the DGS file and generate a graph public boolean openFile(File openMe) { //==== If the file exists, open it and save the graph to this.graphML, if it doesn't return false if( openMe.exists() ) { try { g.read("openMe"); return true; } catch (Exception e) { System.out.println("Exception "+ e); return false; } } else return false; } public Graph getGraph() { return this.g; } //end getXML /* //################################################################################################# //==== Generate XML manually using a Graph as the base public String writeManualXML(Graph g) { //==== Get the tables and schemas from the graph Table nodes = g.getNodeTable(); Table edges = g.getEdgeTable(); Schema nodeSchema = nodes.getSchema(); Schema edgeSchema = edges.getSchema(); //==== Generate the XML header, and data schema for visualization String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!-- A paper and all its citations and references -->\n" + "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">\n" + "<graph edgedefault=\"directed\">\n\n"; //====================================== //==== Generate the Nodes table XML //====================================== String nodesTableXML = "<!-- nodes -->\n"; //==== Go through the nodes table, writing a line of XML for each row for (int j=0; j<nodes.getRowCount(); j++) { String row = ""; for (int k=0; k<nodeSchema.getColumnCount(); k++) { //=== first column is the node key, start a new node element if(k==0) { row = "<node id=\"" + nodes.get(j,k) + "\">\n"; } //=== the remaining columns are nested data for the node else { row = row + " <data key=\"" + nodeSchema.getColumnName(k) + "\">" + nodes.get(j,k) + "</data>\n"; } } // end for, loop through columns //=== close off the node, and add it to the nodeTableXML row = row + "</node>\n"; nodesTableXML = nodesTableXML + row; } //end for, loop through rows //====================================== //==== Generate the Edges table XML //====================================== String edgesTableXML = "<!-- edges -->\n"; //==== Go through the edges table, writing a line of XML for each row for (int j=0; j<edges.getRowCount(); j++) { String row = "<edge source=\"" + edges.get(j,0) + "\" " + "target=\"" + edges.get(j, 1) + "\"></edge>\n"; edgesTableXML = edgesTableXML + row; } //==== Generate XML footer String footer = "</graph>\n</graphml>"; return (header + nodesTableXML + edgesTableXML + footer); } //end default constructor */ } //end ResultXML class
class LFUCache { PriorityQueue<Node> q = new PriorityQueue<>(); int cap; HashMap<Integer, Node> map = new HashMap<>(); int time = 0; public LFUCache(int capacity) { cap = capacity; } public int get(int key) { if(!map.containsKey(key))return -1; Node n = map.get(key); q.remove(n); n.time = time++; n.count++; q.add(n); return n.value; } public void put(int key, int value) { if(map.containsKey(key)){ Node n = map.get(key); q.remove(n); n.time=time++; n.count++; n.value = value; q.add(n); } else{ if(cap<=q.size()){ if(cap==0)return; Node a = q.poll(); map.remove(a.key); } Node n = new Node(value,time++,key); map.put(key,n); q.add(n); } } } class Node implements Comparable{ int count = 0; int time; int value; int key; Node(int value, int time, int key){ this.time = time; this.value = value; this.key = key; } public int compareTo(Object o){ Node c = (Node) o; if(this.count==c.count && this.time==c.time) return 0; if(this.count>c.count || this.count==c.count && this.time>c.time)return 1; return -1; } } /** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
package com.masters.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.masters.models.Courses; import com.masters.models.User; @RestController @RequestMapping("/getCourses") public class CoursesController { @Autowired // This means to get the bean called userRepository private com.masters.repositories.CoursesRepository coursesRepository; @GetMapping("/courses") public List<Courses> getCoursesById(@RequestParam("user_id") Long user_id) { return (List<Courses>) coursesRepository.getCoursesById(user_id); } @GetMapping("/courseByTitle") public List<Courses> getCoursesById(@RequestParam("user_id") Long user_id, @RequestParam("title") String title) { return (List<Courses>) coursesRepository.getCourseByTitle(user_id, title); } @PostMapping("/createCourse") @ResponseBody public Courses CreateCourse( @RequestParam Long user_id, @RequestParam String title) { return coursesRepository.save(new Courses(user_id, title, null)); } @DeleteMapping("/deleteCourse/{id}") public void deleteCourse(@PathVariable long id) { coursesRepository.deleteCourseById(id); } @PutMapping("/editCourse") public void editCourse( @RequestParam Long course_id, @RequestParam String title) { coursesRepository.editCourse(course_id, title); } }
package com.pitang.business; import java.util.LinkedHashMap; import java.util.Map; public class Environment { private String name; private ResourcePool pool; private Map<String, Property> properties; private Environment() { super(); this.properties = new LinkedHashMap<>(); } public Environment(final String name, final ResourcePool pool) { this(); this.name = name; this.pool = pool; } public String getName() { return this.name; } public void setName(final String name) { this.name = name; } public ResourcePool getPool() { return this.pool; } public void setPool(final ResourcePool pool) { this.pool = pool; } public Map<String, Property> getProperties() { return this.properties; } public void setProperties(final Map<String, Property> properties) { this.properties = properties; } @Override public int hashCode() { return (this.name == null) ? 0 : this.name.hashCode(); } @Override public boolean equals(final Object obj) { boolean result = false; if((obj != null) && ((this == obj) || ((this.getClass() == obj.getClass()) && (this.name != null) && this.name.equals(((Environment) obj).name)))) { result = true; } return result; } }
package com.grandsea.ticketvendingapplication.view; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.grandsea.ticketvendingapplication.R; import com.grandsea.ticketvendingapplication.util.ToastUtil; /** * Created by Grandsea09 on 2017/10/9. */ public class SelectTicketViewOld extends LinearLayout implements View.OnClickListener { private ImageView ivIcon,ivMinus,ivAdd; private TextView tvTicketsInfo; // private EditText etNumber; private TextView etNumber; private int ticketMax=0; private int number; public SelectTicketViewOld(Context context) { this(context,null); } public SelectTicketViewOld(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public SelectTicketViewOld(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.view_select_tickets, this); ivIcon = ((ImageView) findViewById(R.id.vst_icon)); ivMinus = ((ImageView) findViewById(R.id.vst_ivMinus)); ivAdd = ((ImageView) findViewById(R.id.vst_ivAdd)); tvTicketsInfo = ((TextView) findViewById(R.id.vst_tvTicketsInfo)); // etNumber = ((EditText) findViewById(R.id.vst_number)); etNumber = ((TextView) findViewById(R.id.vst_number)); ivMinus.setOnClickListener(this); ivAdd.setOnClickListener(this); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SelectTicketViewOld, defStyleAttr, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.SelectTicketViewOld_img: int resourceId = a.getResourceId(attr, -1); if (-1!=resourceId) ivIcon.setImageResource(resourceId); break; case R.styleable.SelectTicketViewOld_textContent: String text = a.getString(attr); if (!TextUtils.isEmpty(text)) tvTicketsInfo.setText(text); break; } } a.recycle(); } public int getNumber() { return number; } public void setTicketMax(int ticketMax) { this.ticketMax = ticketMax; if (number>ticketMax){ number=ticketMax; etNumber.setText(number+""); } } public void setSelectEnable(boolean selectEnable){ ivAdd.setEnabled(selectEnable); ivAdd.setImageResource(R.mipmap.shift_add_gray); ivMinus.setEnabled(selectEnable); ivMinus.setImageResource(R.mipmap.shift_minus_gray); etNumber.setTextColor(getContext().getResources().getColor(R.color.color_bfbfbf)); } @Override public void onClick(View v) { String s = etNumber.getText().toString().trim(); number = Integer.parseInt(s); if (v==ivMinus){ if (number >0) { number--; }else { ToastUtil.showToast(getContext(),"不能小于0"); return; } etNumber.setText(number+""); if (null!= selectTicketListenerOld) { selectTicketListenerOld.changed(number); } }else if (v==ivAdd){ if (number <ticketMax){ number++; }else { // ToastUtil.showToast(getContext(),"剩余:"+ticketMax+" 张");//此票只 // ToastUtil.showToast(getContext(),"已达购票上限(注:一次最多购买6张)");//此票只 return; } etNumber.setText(number+""); if (null!= selectTicketListenerOld) { selectTicketListenerOld.changed(number); } } } public ImageView getIvIcon() { return ivIcon; } public ImageView getIvMinus() { return ivMinus; } public ImageView getIvAdd() { return ivAdd; } public TextView getTvTicketsInfo() { return tvTicketsInfo; } public TextView getEtNumber() { return etNumber; } public interface SelectTicketListenerOld { void changed(int day); } private SelectTicketListenerOld selectTicketListenerOld; public SelectTicketListenerOld getSelectTicketListenerOld() { return selectTicketListenerOld; } public void setSelectTicketListenerOld(SelectTicketListenerOld selectTicketListenerOld) { this.selectTicketListenerOld = selectTicketListenerOld; } }
/* * 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 com.bionic.bibonline.entitiesbeans.authors; import com.bionic.bibonline.entitiesbeans.AbstractFacade; import com.bionic.bibonline.entities.Authors; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; /** * * @author G_Art */ @Stateless public class AuthorsFacade extends AbstractFacade<Authors> implements AuthorsFacadeLocal { private static final Logger log = Logger.getLogger(AuthorsFacade.class.getName()); @PersistenceContext(unitName = "BibOnline.PU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public AuthorsFacade() { super(Authors.class); } @Override public List<Authors> findByName(String name) { TypedQuery<Authors> query = em.createNamedQuery("Authors.findByName", Authors.class); query.setParameter("name", name); try{ return query.getResultList(); }catch(Exception ex){ log.log(Level.SEVERE, "FindByName",ex); return null; } } }
package com.example.Web.Model.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class KorisnikTreninziDTO { private Long idKorisnika; public KorisnikTreninziDTO(){} }
public class Scoreboard implements ScoreboardADT { //create a jobList called list private JobList list; //iterator to get through list private java.util.Iterator<Job> jItr; public Scoreboard(){ //Initialize list to a job list list = new JobList(); } @Override public int getTotalScore() { //Starting score is 0 int retScore = 0; //iterator for list of jobs jItr = list.iterator(); //while there is a next job calculate score for current job while(jItr.hasNext()){ retScore += jItr.next().getPoints(); //System.out.println("how many items"); } return retScore; } @Override public void updateScoreBoard(Job job) { //add a job to "list" when it is completed list.add(job); } @Override public void displayScoreBoard() { if(list.size() > 1 ){ /* displays completed jobs * using iterator through the list of Jobs * that are completed */ System.out.println("Total Score: " + this.getTotalScore()); System.out.println("The jobs completed: "); jItr = list.iterator(); while(jItr.hasNext()){ Job displayJob = jItr.next(); System.out.println("Job Name: " + displayJob.getJobName()); System.out.println("Points earned for this job: " + displayJob.getPoints()); System.out.println("--------------------------------------------"); } } } }
package com.xmcc.service; import com.xmcc.common.JsonData; import com.xmcc.entity.ProductCategory; import java.util.List; public interface ProductCategoryService { //获取商品类目列表 public JsonData list(); }
package by.belotserkovsky.dao; import by.belotserkovsky.pojos.User; /** * Created by K.Belotserkovsky */ public interface IUserDao extends IDao<User> { User getByUserName(String userName); }
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Dbutil { //连接数据库 private String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; private String DB_URL = "jdbc:mysql://localhost:3306/db_dorm?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; private String USER = "root"; private String PASS = "ykf971245"; //连接数据库函数 public Connection getCon() throws ClassNotFoundException, SQLException { Class.forName(JDBC_DRIVER); Connection con = DriverManager.getConnection(DB_URL,USER,PASS); return con; } //断开数据库函数 public void closeCon(Connection con) throws SQLException { if(con != null){ con.close(); } } }
package dao; import app.BaseDao; import model.Item; import org.sql2o.Connection; import java.util.List; public class InventoryDao extends BaseDao{ public List<Item> getAllItems(){ String sql = "SELECT inv.id, inv.name, cat.name category, stock, price " + "FROM inventory inv JOIN category cat " + "ON inv.category = cat.id"; try(Connection con = db.open()){ return con.createQuery(sql).executeAndFetch(Item.class); } } public List<Item> getItemsByCategory(Integer categoryID){ String sql = "SELECT inv.id, inv.name, cat.name category, stock, price " + "FROM inventory inv JOIN category cat " + "ON inv.category = cat.id WHERE inv.category = :id"; try(Connection con = db.open()){ return con.createQuery(sql) .addParameter("id", categoryID) .executeAndFetch(Item.class); } } public Item getItem(Integer id){ String sql = "SELECT inv.id, inv.name, cat.name category, stock, price " + "FROM inventory inv JOIN category cat " + "ON inv.category = cat.id WHERE inv.id = :id"; try(Connection con = db.open()){ return con.createQuery(sql) .addParameter("id", id) .executeAndFetchFirst(Item.class); } } public void insertItem(String name, Integer category, Integer stock, Integer price){ String sql = "INSERT INTO inventory(name, category, stock, price) VALUES(:name, :category, :stock, :price)"; try(Connection con = db.open()){ con.createQuery(sql) .addParameter("name", name) .addParameter("category", category) .addParameter("stock", stock) .addParameter("price", price) .executeUpdate(); } } public void updateItem(Integer id, String name, Integer category, Integer stock, Integer price){ String sql = "UPDATE inventory SET name = :name, category = :cat, stock = :stock, price = :price WHERE id = :id"; try(Connection con = db.open()){ con.createQuery(sql) .addParameter("name", name) .addParameter("cat", category) .addParameter("stock", stock) .addParameter("price", price) .addParameter("id", id) .executeUpdate(); } } public void deleteItem(Integer id){ String sql = "DELETE FROM inventory WHERE id = :id"; try(Connection con = db.open()){ con.createQuery(sql) .addParameter("id", id) .executeUpdate(); } } public Integer getStock(Integer id){ String sql = "SELECT stock FROM inventory WHERE id = :id"; try(Connection con = db.open()){ return con.createQuery(sql) .addParameter("id", id) .executeScalar(Integer.class); } } }
package org.wuxinshui.boosters.designPatterns.singleton; /** * Copyright [2017$] [Wuxinshui] * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by wuxinshui on 2017/2/14. */ //利用反射破坏单例模式 public class ReflectSingleton { public static void main(String[] args) throws Exception { StaticSingleton singleton = StaticSingleton.getInstance(); Constructor constructor=singleton.getClass().getDeclaredConstructor(); //值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。 // 值为 false 则指示反射的对象应该实施 Java 语言访问检查。 constructor.setAccessible(true); StaticSingleton singleton2= (StaticSingleton) constructor.newInstance(); StaticSingleton singleton3= (StaticSingleton) constructor.newInstance(); System.out.println("singleton2==singleton3 :"+(singleton2==singleton3)); } }