text
stringlengths
10
2.72M
package com.human.ex; public class quiz0228_11 { public static void main(String[] args) { //가위바위보 java.util.Scanner sc = new java.util.Scanner(System.in); System.out.print("선택하시오(1: 가위 2: 바위 3: 보) : "); int a = Integer.parseInt(sc.nextLine()); java.util.Random rn = new java.util.Random(); int b = rn.nextInt(3) + 1; switch (a) { case 1: switch (b) { case 1: System.out.println("비겼음"); break; case 2: System.out.println("컴퓨터 이김"); break; case 3: System.out.println("사용자 이김"); break; } break; case 2: switch (b) { case 1: System.out.println("사용자 이김"); break; case 2: System.out.println("비겼음"); break; case 3: System.out.println("컴퓨터 이김"); break; } break; case 3: switch (b) { case 1: System.out.println("컴퓨터 이김"); break; case 2: System.out.println("사용자 이김"); break; case 3: System.out.println("비겼음"); break; } break; default: System.out.println("1-3 중에서만 입력하세요"); } sc.close(); } }
package ejercicio3; public class Persona { private String nombre, edad, telefono, regalo; public Persona(String nombre, String edad, String telefono, String regalo) { this.nombre = nombre; this.edad = edad; this.telefono = telefono; this.regalo = regalo; } public String toString(){ return "Empleado" + "\nNombre: " + getNombre()+ "\nEdad: " + getEdad() + "\nTelefono: " + getTelefono() + "\nRegalo: " + getRegalo(); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getEdad() { return edad; } public void setEdad(String edad) { this.edad = edad; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getRegalo() { return regalo; } public void setRegalo(String regalo) { this.regalo = regalo; } }
package com.github.silencesu.helper.http; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.silencesu.helper.http.request.param.extend.CookicesParams; import com.github.silencesu.helper.http.request.param.extend.HeaderParams; import com.github.silencesu.helper.http.request.param.get.GetParams; import com.github.silencesu.helper.http.request.param.post.PostFormParams; import com.github.silencesu.helper.http.request.param.post.PostJsonParams; import com.github.silencesu.helper.http.request.param.post.PostParams; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Map; /** * Http调用助手 * * @author SilenceSu * @Email Silence.Sx@Gmail.com * Created by Silence on 2020/10/13. */ public class HttpHelper { private static final Logger logger = LoggerFactory.getLogger(HttpHelper.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private static final OkHttpClient okClient = new OkHttpClient(); static { //设置基本参数 okClient.dispatcher().setMaxRequests(500); okClient.dispatcher().setMaxRequestsPerHost(10); } public static <T extends GetParams> String get(String url, T params) { return get(url, params, null); } public static <T extends GetParams> String get(String url, T getRequest, HttpCallBack callback) { HttpUrl.Builder urlBuilder = HttpUrl.parse(url) .newBuilder(); Map<String, String> params = getRequest.getParams(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); } } Request request = new Request.Builder().url(urlBuilder.build()).get().build(); if (callback == null) { try (Response response = okClient.newCall(request).execute()) { return response.body().string(); } catch (IOException e) { logger.error("请求地址错误" + url + e.getMessage()); } } else { okClient.newCall(request).enqueue(callback); } return null; } public static <T extends PostParams> String post(String url, T params) { return post(url, params, null); } public static <T extends PostParams> String post(String url, T params, HttpCallBack callback) { /** * 构建requestbody */ RequestBody requestBody = null; if (params instanceof PostJsonParams) { String jsonStr = null; try { jsonStr = objectMapper.writeValueAsString(((PostJsonParams) params).params()); } catch (JsonProcessingException e) { e.printStackTrace(); } requestBody = RequestBody.create(jsonStr, JSON); } else if (params instanceof PostFormParams) { FormBody.Builder builder = new FormBody.Builder(); Map<String, String> paramMap = ((PostFormParams) params).params(); if (!paramMap.isEmpty()) { for (Map.Entry<String, String> entry : paramMap.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } } requestBody = builder.build(); } /** * 检查是否有headers */ Headers requestHeaders = null; if (params instanceof HeaderParams) { Headers.Builder headerBuilder = new Headers.Builder(); Map<String, String> headsMap = ((HeaderParams) params).headers(); if (!headsMap.isEmpty()) { for (Map.Entry<String, String> entry : headsMap.entrySet()) { headerBuilder.add(entry.getKey(), entry.getValue()); } } //cookie加上 requestHeaders = headerBuilder.build(); } /** * 构建请求对象 */ Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(url); if (requestBody != null) { requestBuilder.post(requestBody); } if (requestHeaders != null) { requestBuilder.headers(requestHeaders); } /** * 检查是否有cookic参数 */ if (params instanceof CookicesParams) { Map<String, String> cookiceMap = ((CookicesParams) params).cookices(); if (!cookiceMap.isEmpty()) { StringBuilder buffer = new StringBuilder(); for (Map.Entry<String, String> entry : cookiceMap.entrySet()) { buffer.append(entry.getKey()); buffer.append("="); buffer.append(entry.getValue()); buffer.append(";"); } requestBuilder.addHeader("Cookie", buffer.toString()); } } if (callback == null) { try (Response response = okClient.newCall(requestBuilder.build()).execute()) { return response.body().string(); } catch (IOException e) { logger.error("请求地址错误" + url + e.getMessage()); } } else { okClient.newCall(requestBuilder.build()).enqueue(callback); } return null; } }
package br.com.salon.carine.lima.dto; import java.io.Serializable; import br.com.salon.carine.lima.validations.DateFilterValidator; @DateFilterValidator public class FiltroDataAtendimentoDTO implements Serializable { private static final long serialVersionUID = 1L; private String dataInicio; private String dataFim; public FiltroDataAtendimentoDTO() { } public FiltroDataAtendimentoDTO(String dataInicio, String dataFim) { this.dataInicio = dataInicio; this.dataFim = dataFim; } public String getDataInicio() { return dataInicio; } public void setDataInicio(String dataInicio) { this.dataInicio = dataInicio; } public String getDataFim() { return dataFim; } public void setDataFim(String dataFim) { this.dataFim = dataFim; } }
package io.breen.socrates.test.python; import com.fasterxml.jackson.databind.ObjectMapper; import io.breen.socrates.Globals; import io.breen.socrates.file.python.Object; import io.breen.socrates.util.Pair; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public class PythonInspector { private final String moduleName; private final ProcessBuilder builder; private final Process process; public PythonInspector(Path targetModulePath) throws IOException { if (!Files.isRegularFile(targetModulePath)) throw new IllegalArgumentException("module path must be a path to a file"); String fileName = targetModulePath.getFileName().toString(); String[] parts = fileName.split("\\."); moduleName = parts[0]; Path testerPath = Globals.extractOrGetFile(Paths.get("tester.py")); if (testerPath == null) throw new RuntimeException("could not locate tester.py"); builder = new ProcessBuilder( Globals.interpreter.path.toString(), // turns off writing bytecode files (.py[co]) "-B", testerPath.toString() ); builder.redirectError(ProcessBuilder.Redirect.INHERIT); Map<String, String> env = builder.environment(); env.put( "PYTHONPATH", /* * Note: this leading path separator is very important! It ensures that PYTHONPATH * has the empty string as an entry, which tells the Python interpreter to look * in the current working directory of the Python process to find modules. */ System.getProperty("path.separator") ); Path parentDir = targetModulePath.getParent(); builder.directory(parentDir.toFile()); process = builder.start(); } private static boolean equals(java.lang.Object expected, ResultObject other) { if (expected == null) { return other.value == null; } else if (expected instanceof Boolean) { Boolean b = (Boolean)expected; if (other == null || !other.type.equals("bool")) return false; return b.equals(other.value); } else if (expected instanceof Number) { Double expectedDouble = ((Number)expected).doubleValue(); if (other == null || (!other.type.equals("int") && !other.type.equals("float"))) return false; Number otherNumber = (Number)other.value; Double otherDouble = otherNumber.doubleValue(); return expectedDouble.equals(otherDouble); } else if (expected instanceof String) { String s = (String)expected; if (other == null || !other.type.equals("str")) return false; return s.equals(other.value); } else if (expected instanceof List) { List list = (List)expected; if (other == null || !other.type.equals("list")) return false; if (!(other.value instanceof List)) return false; List otherList = (List)other.value; return list.equals(otherList); } else if (expected.getClass().isArray()) { java.lang.Object[] arr = (java.lang.Object[])expected; if (other == null || !other.type.equals("list")) return false; if (!(other.value instanceof List)) return false; List otherList = (List)other.value; if (arr.length != otherList.size()) return false; for (int i = 0; i < arr.length; i++) if (!arr[i].equals(otherList.get(i))) return false; return true; } else if (expected instanceof Map) { Map map = (Map)expected; if (other == null || !other.type.equals("dict")) return false; if (!(other.value instanceof Map)) return false; return map.equals(other.value); } throw new IllegalArgumentException(); } private static boolean isPrimitive(java.lang.Object object) { return object instanceof String || object instanceof Number || object instanceof Boolean || object instanceof Map; } public static String toPythonString(java.lang.Object o) { if (o == null) return "None"; if (o instanceof Object) { /* * The case when this object was created using a !python:object definition in a * a criteria file. We display this object as if it were a call to the constructor * with the keyword arguments of its fields. (This might not be correct Python code, * since this constructor may not exist. However, this string is not being eval()'d * by any Python code --- it's just for illustration.) */ Object pyObj = (Object)o; StringBuilder builder = new StringBuilder(); builder.append(pyObj.type.typeName); builder.append("("); int i = 0; int numEntries = pyObj.fields.size(); for (Map.Entry<String, java.lang.Object> entry : pyObj.fields.entrySet()) { builder.append(entry.getKey() + "=" + toPythonString(entry.getValue())); if (++i != numEntries) builder.append(", "); } builder.append(")"); return builder.toString(); } else if (o instanceof Number) { return o.toString(); } else if (o instanceof String) { String s = (String)o; return "'" + s + "'"; } else if (o instanceof Boolean) { Boolean b = (Boolean)o; if (b) return "True"; else return "False"; } else if (o instanceof List) { List<java.lang.Object> l = (List)o; StringBuilder builder = new StringBuilder(); builder.append("["); int i = 0; int numItems = l.size(); for (java.lang.Object item : l) { builder.append(toPythonString(item)); if (++i != numItems) builder.append(", "); } builder.append("]"); return builder.toString(); } else if (o instanceof Map) { Map<java.lang.Object, java.lang.Object> m = (Map)o; StringBuilder builder = new StringBuilder(); builder.append("{"); int i = 0; int numEntries = m.size(); for (Map.Entry<java.lang.Object, java.lang.Object> entry : m.entrySet()) { builder.append( toPythonString(entry.getKey()) + ": " + toPythonString(entry.getValue()) ); if (++i != numEntries) builder.append(", "); } builder.append("}"); return builder.toString(); } throw new IllegalArgumentException( "cannot make Python string for: " + o ); } public static String callToString(String functionName, List<java.lang.Object> args) { StringBuilder builder = new StringBuilder(functionName); builder.append("("); for (int i = 0; i < args.size(); i++) { builder.append(toPythonString(args.get(i))); if (i != args.size() - 1) builder.append(", "); } builder.append(")"); return builder.toString(); } private Map<String, java.lang.Object> newRequestMap() { Map<String, java.lang.Object> request = new HashMap<>(); request.put("name", moduleName); return request; } private boolean isErrorResponse(Map<String, java.lang.Object> response) { return response.containsKey("error") && (boolean)response.get("error"); } private PythonError errorFromResponse(Map<String, java.lang.Object> response) { return new PythonError( (String)response.get("error_type"), (String)response.get("error_message") ); } private ResultObject toPythonObject(Map<String, java.lang.Object> response) { return new ResultObject(response.get("value"), (String)response.get("type")); } public boolean variableExists(String variableName) throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "exists"); Map<String, String> targetMap = new HashMap<>(); targetMap.put("type", "variable"); targetMap.put("name", variableName); request.put("target", targetMap); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) throw errorFromResponse(response); return (boolean)response.get("value"); } public boolean variableEquals(String variableName, java.lang.Object value) throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "eval"); Map<String, String> targetMap = new HashMap<>(); targetMap.put("type", "variable"); targetMap.put("name", variableName); request.put("target", targetMap); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) throw errorFromResponse(response); return equals(value, toPythonObject(response)); } /** * Asks the Python interpreter to import the Python module. If the Python interpreter is able to * import the module, it returns true and this method returns (true, null). If the interpreter * cannot import the module due to an error (e.g., a syntax error) at import-time, it returns * false and the error string generated by the interpreter. * * @return A pair indicating what happened while importing the module * * @throws IOException If a low-level error occurs communicating with the interpreter * @throws PythonError If Python exits with an error (in our code, not the student's) */ public Pair<Boolean, String> canImportModule() throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "load"); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) { throw errorFromResponse(response); } boolean passed = (boolean)response.get("value"); if (passed) { return new Pair<>(true, null); } else { String output = (String)response.get("output"); return new Pair<>(false, output); } } /** * Asks the Python interpreter to check whether a function exists (by name). * * @return true if the interpreter could find the function, false otherwise * * @throws IOException If a low-level error occurs communicating with the interpreter * @throws PythonError If Python exits with an error */ public boolean functionExists(String functionName) throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "exists"); Map<String, String> targetMap = new HashMap<>(); targetMap.put("type", "function"); targetMap.put("name", functionName); request.put("target", targetMap); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) throw errorFromResponse(response); return (boolean)response.get("value"); } /** * Asks the Python interpreter to check whether a class exists (by name). * * @return true if the interpreter could find the class, false otherwise * * @throws IOException If a low-level error occurs communicating with the interpreter * @throws PythonError If Python exits with an error */ public boolean classExists(String className) throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "exists"); Map<String, String> targetMap = new HashMap<>(); targetMap.put("type", "class"); targetMap.put("name", className); request.put("target", targetMap); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) throw errorFromResponse(response); return (boolean)response.get("value"); } /** * Asks the Python interpreter to check whether a method exists (by name). The name of the class * containing the method must also be specified. If the class name specifies a class that * doesn't exist, this method throws a PythonError. * * @return true if the interpreter could find the method, false otherwise * * @throws IOException If a low-level error occurs communicating with the interpreter * @throws PythonError If Python exits with an error */ public boolean methodExists(String className, String functionName) throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "exists"); Map<String, String> targetMap = new HashMap<>(); targetMap.put("type", "method"); targetMap.put("name", functionName); targetMap.put("class_name", className); request.put("target", targetMap); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) throw errorFromResponse(response); return (boolean)response.get("value"); } /** * Asks the Python interpreter to run a Python function with the specified arguments and * determine whether it equals the value specified. If the function doesn't produce the expected * value and/or output, the Boolean value returned is false. In either case, the string returned * is the output produced by the function (if any), followed by the newline character, and the * string representation of the return value (i.e., as if the function were evaluated on the * Python REPL). * * @return A pair indicating whether the expected value is the same * * @throws IOException If a low-level error occurs communicating with the interpreter * @throws PythonError If a Python error occurs evaluating the function */ public Pair<Boolean, String> functionProduces(String functionName, List<java.lang.Object> args, Map<String, java.lang.Object> kwargs, String input, java.lang.Object returnValue, String output) throws IOException, PythonError { return methodProduces(functionName, null, args, kwargs, input, null, returnValue, output); } /** * Asks the Python interpreter to run a Python method with the specified arguments and determine * whether it equals the value specified. The "before" state of the called object is also * specified. If the method doesn't produce the expected value and/or output, or the fields of * the called object that are specified by the "after" object do not match, the Boolean value * returned is false. In either case, the string returned is the output produced by the method * (if any), followed by the newline character, and the string representation of the return * value (i.e., as if the function were evaluated on the Python REPL). * * @return A pair indicating whether the expected value is the same * * @throws IOException If a low-level error occurs communicating with the interpreter * @throws PythonError If a Python error occurs evaluating the function */ public Pair<Boolean, String> methodProduces(String methodName, Object before, List<java.lang.Object> args, Map<String, java.lang.Object> kwargs, String input, Object after, java.lang.Object returnValue, String output) throws IOException, PythonError { ObjectMapper mapper = new ObjectMapper(); Map<String, java.lang.Object> request = newRequestMap(); request.put("type", "eval"); Map<String, String> targetMap = new HashMap<>(); if (before != null) targetMap.put("type", "method"); else targetMap.put("type", "function"); targetMap.put("name", methodName); request.put("target", targetMap); // parameters of the test, not to the function Map<String, java.lang.Object> parametersMap = new HashMap<>(); if (args != null && !args.isEmpty()) { // keep track of the indices of arguments that should be constructed in Python List<Integer> indices = new ArrayList<>(args.size()); List<java.lang.Object> argsList = new ArrayList<>(args.size()); for (int i = 0; i < args.size(); i++) { java.lang.Object o = args.get(i); if (o instanceof Object) { Object obj = (Object)o; Map<String, java.lang.Object> fieldsMap = new HashMap<>(); for (Map.Entry<String, java.lang.Object> field : obj.fields.entrySet()) // TODO should recursively convert field value fieldsMap.put(field.getKey(), field.getValue()); Map<String, java.lang.Object> objMap = new HashMap<>(); objMap.put("class_name", obj.type.typeName); objMap.put("fields", fieldsMap); argsList.add(objMap); indices.add(i); } else { // argument is of primitive type argsList.add(o); } } parametersMap.put("args", argsList); parametersMap.put("object_indices", indices); } if (kwargs != null && !kwargs.isEmpty()) parametersMap.put("kwargs", kwargs); if (input != null) parametersMap.put("input", input); if (before != null) { Map<String, java.lang.Object> beforeMap = new HashMap<>(); beforeMap.put("class_name", before.type.typeName); beforeMap.put("fields", before.fields); parametersMap.put("before", beforeMap); } request.put("parameters", parametersMap); mapper.writeValue(process.getOutputStream(), request); Map<String, java.lang.Object> response = mapper.readValue( process.getInputStream(), Map.class ); if (isErrorResponse(response)) throw errorFromResponse(response); String str = ""; if (response.containsKey("output")) str += response.get("output"); if (!response.get("type").equals("NoneType")) str += toPythonString(response.get("value")); if (output != null) if (!response.containsKey("output") || !output.equals(response.get("output"))) // we expect output, but this function produces no output/incorrect output return new Pair<>(false, str); if (after != null) { Map<String, java.lang.Object> fields = (Map)response.get("after"); for (Map.Entry<String, java.lang.Object> field : after.fields.entrySet()) { java.lang.Object afterValue = fields.get(field.getKey()); if (!afterValue.equals(field.getValue())) { // TODO should not compare with object equals // object state after method call does not match expected state return new Pair<>(false, str); } } } return new Pair<>(equals(returnValue, toPythonObject(response)), str); } public class ResultObject { public final java.lang.Object value; public final String type; public ResultObject(java.lang.Object value, String type) { this.value = value; this.type = type; } } }
package sonto.db; import java.util.Map; import sonto.models.Model; public abstract class DBIface { public String host; public int port; public String name; public String user; public String password; public DBIface (String host, int port, String name, String user, String password) { this.host = host; this.port = port; this.name = name; this.user = user; this.password = password; } abstract public boolean connect(String host, int port, String name, String user, String password) throws Exception ; abstract public void disconnect () throws Exception; abstract public void create_table(Class<Model> model, Map<String, String> options) throws Exception; abstract public void update(Model model); abstract public void insert (Model model); abstract public void delete (Model model); }
/* * Copyright (c) 2013-2014, Neuro4j.org * * 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 org.neuro4j.studio.core.util; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Group of entries with additional Session data. */ public class LogSession extends Group { /** * Describes the !SESSION header name * * @since 3.5 */ public static final String SESSION = "!SESSION"; //$NON-NLS-1$ private String sessionData; private Date date; public LogSession() { super(null); } public Date getDate() { return date; } public void setDate(String dateString) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //$NON-NLS-1$ try { date = formatter.parse(dateString); } catch (ParseException e) { // do nothing } } public String getSessionData() { return sessionData; } void setSessionData(String data) { this.sessionData = data; } public void processLogLine(String line) { // process "!SESSION <dateUnknownFormat> ----------------------------" if (line.startsWith(SESSION)) { line = line.substring(SESSION.length()).trim(); // strip "!SESSION " int delim = line.indexOf("----"); //$NON-NLS-1$ // single "-" may be in date, so take few for sure if (delim == -1) { return; } String dateBuffer = line.substring(0, delim).trim(); setDate(dateBuffer); } } public void write(PrintWriter writer) { writer.write(sessionData); writer.println(); super.write(writer); } }
package com.gsitm.login.controller; import com.gsitm.login.service.LoginService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; /** * @programName : LoginController.java * @author : 허빛찬샘 * @date : 2018. 6. 09. * @function : Login의 전반적인 Controller * * [이름] [수정일] [내용] * ---------------------------------------------------------- * 허빛찬샘 2018-06-09 초안 작성 * 허빛찬샘 2018-06-11 내용추가 */ @Controller public class LoginController { private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Resource(name = "loginService") private LoginService loginService; /** * @methodName : login * @author : 허빛찬샘 * @date : 2018. 6. 11. * @function : 로그인 화면 이동 */ @RequestMapping(value = "/login.do", method = RequestMethod.GET) public ModelAndView login(@RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView(); if (error != null) model.addObject("error", "Invalid username and password!"); model.setViewName("/login"); if (logout != null) { model.addObject("msg", "You've been logged out successfully."); model.setViewName("/login"); } return model; } }
package atm; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Account extends JFrame{ public Container c; public Font f; public JButton btn1,btn2; public JLabel j; Account() { display(); } public void display() { c = this.getContentPane(); c.setLayout(null); f = new Font("Arial", Font.BOLD,15); btn1 = new JButton("CREATE ACCOUNT"); btn1.setFont(f); btn1.setBounds(70,50,190,30); c.add(btn1); btn1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { dispose(); CreateAccount menu = new CreateAccount(); menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menu.setBounds(400,200,350,300); menu.setVisible(true); menu.setTitle("ATM"); } }); j = new JLabel("OR"); j.setBounds(150,90,40,40); j.setFont(f); c.add(j); btn2 = new JButton("LOGIN"); btn2.setFont(f); btn2.setBounds(120,140,100,30); c.add(btn2); btn2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { dispose(); User mu = new User(); mu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mu.setBounds(400,200,350,300); mu.setVisible(true); mu.setTitle("ATM"); } }); } public static void main(String[] args) { Account menu = new Account(); menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menu.setBounds(400,200,350,300); menu.setVisible(true); menu.setTitle("ATM"); } }
package day03wrapperclassconcatenatelogicaloperators; import java.security.DomainLoadStoreParameter; public class WrapperClass01 { /* Wrapper Class: Java created some objects whose values are coming from primitive data types but the objects have methods as well Wrapper Class for boolean ==> Boolean **** Wrapper Class for char ==> Character Wrapper Class for byte ==> Byte Wrapper Class for short ==> Short **** Wrapper Class for int ==> Integer Wrapper Class for long ==> Long Wrapper Class for float ==> Float Wrapper Class for double ==> Double */ public static void main(String[] args) { Integer i = 12; Boolean b = true; //Find the min and max value of byte data type Byte byteMin = Byte.MIN_VALUE; System.out.println(byteMin);//-128 Byte byteMax = Byte.MAX_VALUE; System.out.println(byteMax);//127 //Find the min and max value of short data type Short shortMin = Short.MIN_VALUE; System.out.println(shortMin); Short shortMax = Short.MAX_VALUE; System.out.println(shortMax); Integer integerMin = Integer.MIN_VALUE; System.out.println(integerMin); Integer integerMax = Integer.MAX_VALUE; System.out.println(integerMax); Long longMin = Long.MIN_VALUE; System.out.println(longMin); Long longMax = Long.MAX_VALUE; System.out.println(longMax); Float floatmin = Float.MIN_VALUE; System.out.println(floatmin); Float floatMax = Float.MAX_VALUE; System.out.println(floatMax); Double doubleMin = Double.MIN_VALUE; System.out.println(doubleMin); Double doubleMax = Double.MAX_VALUE; System.out.println(doubleMax); //Homework: Find all min and all max values of primitive data types } }
/* * 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 sd.com.br.gui.Cadastros; import clientesemmaven.Conexoes; import edu.ifpb.dac.Funcionario; import ifpb.dac.service.DAOIT; import java.awt.Color; import javax.swing.JOptionPane; /** * * @author Sergiod */ public class CadastroFuncionario extends javax.swing.JFrame { /** * Creates new form CadastroFuncionario */ public CadastroFuncionario() { initComponents(); jPanel1.setBackground(Color.WHITE); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTSenha = new javax.swing.JTextField(); jTEmail = new javax.swing.JTextField(); jTCpf = new javax.swing.JTextField(); jTNome = new javax.swing.JTextField(); jBCadastrar = new javax.swing.JButton(); jBCancelar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel7.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N jLabel7.setText("Cadastrar Novo Funcionario"); jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel1.setText("Nome: "); jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel2.setText("CPF:"); jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel3.setText("Email:"); jLabel4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabel4.setText("Senha:"); jTSenha.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTSenha.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jTEmail.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTEmail.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jTCpf.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTCpf.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jTNome.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jTNome.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jBCadastrar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jBCadastrar.setText("Cadastrar"); jBCadastrar.setPreferredSize(new java.awt.Dimension(95, 33)); jBCadastrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBCadastrarActionPerformed(evt); } }); jBCancelar.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N jBCancelar.setText("cancelar"); jBCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBCancelarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jTNome, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jLabel2)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jTCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jLabel3)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jTEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jLabel4)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jTSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(82, 82, 82) .addComponent(jLabel7)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(90, 90, 90) .addComponent(jBCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jBCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(41, 41, 41)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel7) .addGap(50, 50, 50) .addComponent(jLabel1) .addGap(5, 5, 5) .addComponent(jTNome, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(17, 17, 17) .addComponent(jLabel2) .addGap(5, 5, 5) .addComponent(jTCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(17, 17, 17) .addComponent(jLabel3) .addGap(5, 5, 5) .addComponent(jTEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(17, 17, 17) .addComponent(jLabel4) .addGap(5, 5, 5) .addComponent(jTSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jBCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jBCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jBCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelarActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_jBCancelarActionPerformed private void jBCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCadastrarActionPerformed // TODO add your handling code here: if((jTNome.getText().length() > 0) && (jTCpf.getText().length() > 0) && (jTEmail.getText().length() > 0) && (jTSenha.getText().length() > 0)){ Funcionario funcionario = new Funcionario(); funcionario.setNome(jTNome.getText()); funcionario.setCpf(jTCpf.getText()); funcionario.setEmail(jTEmail.getText()); funcionario.setSenha(jTSenha.getText()); DAOIT dao = Conexoes.DAO(); dao.salvar(funcionario); JOptionPane.showMessageDialog(rootPane, "Cadastro realizado com sucesso."); jTNome.setText(""); jTCpf.setText(""); jTEmail.setText(""); jTSenha.setText(""); } else { JOptionPane.showMessageDialog(rootPane, "Preencha todos os campos corretamente!"); } }//GEN-LAST:event_jBCadastrarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CadastroFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadastroFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadastroFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadastroFuncionario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CadastroFuncionario().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBCadastrar; private javax.swing.JButton jBCancelar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTCpf; private javax.swing.JTextField jTEmail; private javax.swing.JTextField jTNome; private javax.swing.JTextField jTSenha; // End of variables declaration//GEN-END:variables }
package Main; import java.util.Scanner; /** * Created by Samarth on 5/31/16. */ public class QuickSortInPlace { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = scanner.nextInt(); } quickSort(array, 0, array.length - 1); } public static void quickSort(int[] array, int l, int r) { if (l < r) { int pIdx = partition(array, l, r); quickSort(array, l, pIdx - 1); quickSort(array, pIdx + 1, r); } } public static int partition(int[] array, int left, int right) { int pivot = array[right]; for (int j = left; j <= right; j++) { if (array[j] <= pivot) { int temp = array[j]; array[j] = array[left]; array[left] = temp; left++; } } print(array); return left - 1; } public static void print(int[] array) { for (int i = 0; i < array.length; ++i) { System.out.print(Integer.toString(array[i]) + " "); } System.out.println(""); } }
package com.dbs.portal.ui.component.view; public class DefaultFreeGridView extends BaseFreeGridView{ public DefaultFreeGridView(int noOfColumn, int noOfRow) { super(noOfColumn, noOfRow); } public DefaultFreeGridView(String caption, int noOfColumn, int noOfRow){ super(caption,noOfColumn,noOfRow); } // public DefaultFreeGridView(int noOfColumn, int noOfRow, int componentHeight, int conponentWidth){ // super(noOfColumn,noOfRow,componentHeight,conponentWidth); // } // // public DefaultFreeGridView(String caption, int noOfColumn, int noOfRow, int componentHeight, int conponentWidth){ // super(caption,noOfColumn,noOfRow,componentHeight,conponentWidth); // } @Override public void postUpdate() { } }
package elasticsearch.service.impl.abst; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.deletebyquery.DeleteByQueryAction; import org.elasticsearch.action.deletebyquery.DeleteByQueryRequestBuilder; import org.elasticsearch.action.deletebyquery.DeleteByQueryResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.plugin.deletebyquery.DeleteByQueryPlugin; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.sort.SortOrder; import com.alibaba.fastjson.JSON; import elasticsearch.bean.SearchParam; import elasticsearch.bean.SearchParamCollection; import elasticsearch.util.ClientUtil; import elasticsearch.util.ElasticUtil; import util.ConstantUtil; /** * Elastic CRD基础抽象类 * * @author kida * */ public abstract class ElasticBase { private Client client = ConstantUtil.esClient; private static final Logger LOG = Logger.getLogger(ElasticBase.class); /** * 单个插入 * * @param entityJSON * @param types */ public void insert(String entityJSON, String indices, String types) { IndexResponse indexResponse = client.prepareIndex(indices, types) .setSource(entityJSON).execute().actionGet(); LOG.info("function insert execed , id is: " + indexResponse.getId() + " , index is: " + indexResponse.getIndex() + " , type is: " + indexResponse.getType()); } /** * 批量插入数据 * * @param entityJSONList * @param types */ public void batchInsert(List<String> entityJSONList, String indices, String types) { // 暂存JSON String entityJSON; // 执行返回 BulkResponse bulkResponse; // 获取批量处理值 int counter = Integer.parseInt(ConstantUtil.BATCH_COUNT); BulkRequestBuilder brb = client.prepareBulk(); if (null != entityJSONList && !entityJSONList.isEmpty()) { for (int i = 0; i < entityJSONList.size(); i++) { entityJSON = entityJSONList.get(i); brb.add(client.prepareIndex(indices, types) .setSource(entityJSON)); // 批量插入按照指定的阀值进行插入 if (i % counter == 0 && i > 0) { bulkResponse = brb.execute().actionGet(); brb = client.prepareBulk(); if (bulkResponse.hasFailures()) { LOG.info( "function batchInsert is failure , insert total " + i + " rows"); break; } } } // 因为会出现循环后没有达到阀值的数据,也是需要插入的 bulkResponse = brb.execute().actionGet(); if (bulkResponse.hasFailures()) { LOG.info("function batchInsert is failure , faile in the end "); } } } /** * 单个删除 * * @param id * @param types */ public void deleteById(String id, String indices, String types) { DeleteResponse deleteResponse = client.prepareDelete(indices, types, id) .execute().actionGet(); LOG.info("function deleteById execed , id is: " + deleteResponse.getId() + " , index is: " + deleteResponse.getIndex() + " , type is: " + deleteResponse.getType()); } /** * 批量删除 * * @param pc */ public void batchDelete(SearchParamCollection spc, String indices) { if (null != spc) { List<SearchParam> spList = spc.getpList(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); QueryBuilder queryBuilder = ElasticUtil.queryByBool(spList, boolQueryBuilder); // 由于用到插件,这里需要将插件的类传入 client = ClientUtil.getInstance() .getClient(DeleteByQueryPlugin.class); DeleteByQueryResponse response = new DeleteByQueryRequestBuilder( client, DeleteByQueryAction.INSTANCE).setIndices(indices) .setTypes(spc.getTypes()).setQuery(queryBuilder) .execute().actionGet(); LOG.info("function batchDelete execed , use time: " + response.getTookInMillis() + " , total delete : " + response.getTotalDeleted()); } } /** * 使用传统的先查询id然后删除的方法(已弃用) * * @param spc */ public void batchDeleteByParam(SearchParamCollection spc, String indices) { boolean flag = true; int counter = Integer.parseInt(ConstantUtil.BATCH_COUNT); BulkResponse bulkResponse; SearchResponse response; SearchHit hit; if (null != spc) { List<SearchParam> spList = spc.getpList(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); QueryBuilder queryBuilder = ElasticUtil.queryByBool(spList, boolQueryBuilder); if (null != queryBuilder) { BulkRequestBuilder brb = client.prepareBulk(); while (flag) { response = client.prepareSearch(indices) .setTypes(spc.getTypes()).setQuery(queryBuilder) .setFrom(spc.getBeginRow()) .setSize(spc.getBeginRow() + spc.getPageSize()) .execute().actionGet(); SearchHits hits = response.getHits(); if (hits.totalHits() > 0) { if (hits.totalHits() <= (spc.getBeginRow() + spc.getPageSize())) { flag = false; } else { spc.setBeginRow( spc.getBeginRow() + spc.getPageSize()); } for (int i = 0; i < spc.getPageSize(); i++) { hit = hits.getAt(i); brb.add(client.prepareDelete(indices, spc.getTypes(), String.valueOf(hit.getId()))); if (i % counter == 0) { bulkResponse = brb.execute().actionGet(); if (bulkResponse.hasFailures()) { LOG.info( "function batchDeleteByParam is failure , delete total " + i + " rows"); break; } } } brb.execute().actionGet(); } else { break; } } } } } /** * 根据提供参数进行查询 * * @param spc * @param obj * @return */ public <T> List<T> queryByParam(SearchParamCollection spc, String indices, Class<T> obj) { SearchRequestBuilder responseBuilder; SearchResponse response; List<T> reList = new ArrayList<>(); if (null != spc) { // 收集查询条件 List<SearchParam> spList = spc.getpList(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); QueryBuilder queryBuilder = ElasticUtil.queryByBool(spList, boolQueryBuilder); // 根据条件进行查询 if (null != queryBuilder) { responseBuilder = client.prepareSearch(indices) .setTypes(spc.getTypes()).setQuery(queryBuilder) .setFrom(spc.getBeginRow()) .setSize(spc.getBeginRow() + spc.getPageSize()) .addSort(spc.getSortField(), SortOrder.valueOf(spc.getSortType())); response = responseBuilder.execute().actionGet(); SearchHits hits = response.getHits(); // 查询结果放入list中返回 if (hits.totalHits() > 0) { for (SearchHit hit : hits) { String jsonStr = JSON.toJSONString(hit.getSource()); Object objs = ElasticUtil.json2Model(jsonStr, obj); reList.add((T) objs); } } } } return reList; } /** * 根据名称删除索引 * * @param indices */ public void deleteIndex(String indices) { DeleteIndexResponse dResponse = client.admin().indices() .prepareDelete(indices).execute().actionGet(); if (dResponse.isAcknowledged()) { LOG.info("delete index " + indices + " successfully!"); } else { LOG.info("Fail to delete index " + indices); } } }
package com.zemoso.training.repository; import com.zemoso.training.entity.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; public interface BookRepository extends JpaRepository<Book, UUID> { @Modifying @Transactional @Query(value = "update Book b set b.isActive = false where b.bookId = :bookId") int disableBookByBookId(@Param("bookId") UUID bookId); @Query(value = "select b from Book b where b.numberOfReads > :numberOfReads") List<Book> findPopularBooks(@Param("numberOfReads") int numberOfReads); @Query(value = "select b from Book b where b.creationDate > current_date - (:recentBooks + 0) order by b.creationDate desc") List<Book> findRecentlyAddedBooks(@Param("recentBooks") int recentBooks); List<Book> findBookByCategoryCategoryId(UUID categoryId); }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context.aot; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.core.SpringProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.aot.TestContextAotGenerator.FAIL_ON_ERROR_PROPERTY_NAME; /** * Unit tests for {@link TestContextAotGenerator}. * * @author Sam Brannen * @since 6.1 */ class TestContextAotGeneratorUnitTests { @BeforeEach @AfterEach void resetFlag() { SpringProperties.setProperty(FAIL_ON_ERROR_PROPERTY_NAME, null); } @Test void failOnErrorEnabledByDefault() { assertThat(createGenerator().failOnError).isTrue(); } @ParameterizedTest @ValueSource(strings = {"true", " True\t"}) void failOnErrorEnabledViaSpringProperty(String value) { SpringProperties.setProperty(FAIL_ON_ERROR_PROPERTY_NAME, value); assertThat(createGenerator().failOnError).isTrue(); } @ParameterizedTest @ValueSource(strings = {"false", " False\t", "x"}) void failOnErrorDisabledViaSpringProperty(String value) { SpringProperties.setProperty(FAIL_ON_ERROR_PROPERTY_NAME, value); assertThat(createGenerator().failOnError).isFalse(); } private static TestContextAotGenerator createGenerator() { return new TestContextAotGenerator(null); } }
package com.goldenasia.lottery.data; import com.goldenasia.lottery.base.net.RequestConfig; /** * Created by Sakura on 2016/10/10. */ @RequestConfig(api = "?c=game&a=ggc&op=detail") public class GgcCardDetailCommand { private String sc_id; public String getSc_id() { return sc_id; } public void setSc_id(String sc_id) { this.sc_id = sc_id; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.parsing; import java.util.ArrayList; import java.util.List; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanReference; import org.springframework.lang.Nullable; /** * ComponentDefinition based on a standard BeanDefinition, exposing the given bean * definition as well as inner bean definitions and bean references for the given bean. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public class BeanComponentDefinition extends BeanDefinitionHolder implements ComponentDefinition { private final BeanDefinition[] innerBeanDefinitions; private final BeanReference[] beanReferences; /** * Create a new BeanComponentDefinition for the given bean. * @param beanDefinition the BeanDefinition * @param beanName the name of the bean */ public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName) { this(new BeanDefinitionHolder(beanDefinition, beanName)); } /** * Create a new BeanComponentDefinition for the given bean. * @param beanDefinition the BeanDefinition * @param beanName the name of the bean * @param aliases alias names for the bean, or {@code null} if none */ public BeanComponentDefinition(BeanDefinition beanDefinition, String beanName, @Nullable String[] aliases) { this(new BeanDefinitionHolder(beanDefinition, beanName, aliases)); } /** * Create a new BeanComponentDefinition for the given bean. * @param beanDefinitionHolder the BeanDefinitionHolder encapsulating * the bean definition as well as the name of the bean */ public BeanComponentDefinition(BeanDefinitionHolder beanDefinitionHolder) { super(beanDefinitionHolder); List<BeanDefinition> innerBeans = new ArrayList<>(); List<BeanReference> references = new ArrayList<>(); PropertyValues propertyValues = beanDefinitionHolder.getBeanDefinition().getPropertyValues(); for (PropertyValue propertyValue : propertyValues.getPropertyValues()) { Object value = propertyValue.getValue(); if (value instanceof BeanDefinitionHolder beanDefHolder) { innerBeans.add(beanDefHolder.getBeanDefinition()); } else if (value instanceof BeanDefinition beanDef) { innerBeans.add(beanDef); } else if (value instanceof BeanReference beanRef) { references.add(beanRef); } } this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[0]); this.beanReferences = references.toArray(new BeanReference[0]); } @Override public String getName() { return getBeanName(); } @Override public String getDescription() { return getShortDescription(); } @Override public BeanDefinition[] getBeanDefinitions() { return new BeanDefinition[] {getBeanDefinition()}; } @Override public BeanDefinition[] getInnerBeanDefinitions() { return this.innerBeanDefinitions; } @Override public BeanReference[] getBeanReferences() { return this.beanReferences; } /** * This implementation returns this ComponentDefinition's description. * @see #getDescription() */ @Override public String toString() { return getDescription(); } /** * This implementation expects the other object to be of type BeanComponentDefinition * as well, in addition to the superclass's equality requirements. */ @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof BeanComponentDefinition && super.equals(other))); } }
package com.fixit.core.dao.sql.impl; import org.springframework.stereotype.Repository; import com.fixit.core.dao.sql.UserStatisticsDao; import com.fixit.core.data.sql.UserStatistics; @Repository public class UserStatisticsDaoImpl extends SqlDaoImpl<UserStatistics, String> implements UserStatisticsDao { public final static String TABLE_NAME = "UserStatistics"; public final static String PROP_USER_ID = "userId"; public final static String PROP_JOBS_ORDERED = "jobsOrdered"; public final static String PROP_REVIEWS_MADE = "reviewsMade"; public final static String PROP_REGISTRATION_DATE = "registrationDate"; @Override public String getTableName() { return TABLE_NAME; } @Override public Class<UserStatistics> getEntityClass() { return UserStatistics.class; } }
package com.example.gamedb.db.repository; import android.app.Application; import android.os.AsyncTask; import com.example.gamedb.db.GameDatabase; import com.example.gamedb.db.dao.PlatformDao; import com.example.gamedb.db.entity.Platform; public class PlatformRepository { private PlatformDao mPlatformDao; public PlatformRepository(Application application) { GameDatabase database = GameDatabase.getDatabase(application); mPlatformDao = database.platformDao(); } public void insert(Platform... platforms) { new InsertAsyncTask(mPlatformDao).execute(platforms); } public void update(Platform... platforms) { new UpdateAsyncTask(mPlatformDao).execute(platforms); } public void deleteAll(Long date) { new DeleteAsyncTask(mPlatformDao).execute(date); } private static class InsertAsyncTask extends AsyncTask<Platform, Void, Void> { private PlatformDao mDao; public InsertAsyncTask(PlatformDao platformDao) { mDao = platformDao; } @Override protected Void doInBackground(Platform... platforms) { mDao.insert(platforms); return null; } } private static class UpdateAsyncTask extends AsyncTask<Platform, Void, Void> { private PlatformDao mDao; public UpdateAsyncTask(PlatformDao platformDao) { mDao = platformDao; } @Override protected Void doInBackground(Platform... platforms) { mDao.update(platforms); return null; } } private static class DeleteAsyncTask extends AsyncTask<Long, Void, Void> { private PlatformDao mDao; public DeleteAsyncTask(PlatformDao platformDao) { mDao = platformDao; } @Override protected Void doInBackground(Long... dates) { mDao.deleteAll(dates[0]); return null; } } }
package com.konew.musicapp.controller; import com.konew.musicapp.model.LoginModel; import com.konew.musicapp.model.RegisterModel; import com.konew.musicapp.security.jwt.UserResponse; import com.konew.musicapp.service.AuthorizationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api/auth") public class AuthorizationController { AuthorizationService authorizationService; @Autowired public AuthorizationController(AuthorizationService authorizationService) { this.authorizationService = authorizationService; } @PostMapping("/login") public ResponseEntity<UserResponse> userLogin(@Valid @RequestBody LoginModel loginModel) { return authorizationService.userLogin(loginModel); } @PostMapping("/register") public ResponseEntity<?> register(@Valid @RequestBody RegisterModel registerModel) { return authorizationService.register(registerModel); } }
package egovframework.adm.prop.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import egovframework.adm.prop.service.ApprovalService; import egovframework.com.cmm.EgovMessageSource; import egovframework.com.pag.controller.PagingManageController; import egovframework.rte.fdl.property.EgovPropertyService; @Controller public class StudentManagerController { /** log */ protected Log log = LogFactory.getLog(this.getClass()); /** EgovPropertyService */ @Resource(name = "propertiesService") protected EgovPropertyService propertiesService; /** EgovMessageSource */ @Resource(name="egovMessageSource") EgovMessageSource egovMessageSource; /** PagingManageController */ @Resource(name = "pagingManageController") private PagingManageController pagingManageController; /** approvalService */ @Resource(name = "approvalService") private ApprovalService approvalService; /** * 수강생관리 리스트 페이지 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/studentManagerList.do") public String pageList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { Map<?, ?> view = approvalService.selectStudentManagerIsClosed(commandMap); model.addAttribute("view", view); List<?> seqList = approvalService.selectSubjSeqList(commandMap); model.addAttribute("seqList", seqList); List<?> list = null; if(commandMap.get("ses_search_subjseq") !=null){ list = approvalService.selectStudentManagerList(commandMap); } model.addAttribute("list", list); model.addAllAttributes(commandMap); return "adm/prop/studentManagerList"; } /** * 수강생관리 엑셀 다운로드 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/studentManagerExcelDown.do") public ModelAndView excelDownload(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ List<?> list = approvalService.selectStudentManagerList(commandMap); model.addAttribute("list", list); Map<String, Object> map = new HashMap<String, Object>(); map.put("list", list); return new ModelAndView("studentManagerExcelView", "studentManagerMap", map); } /** * 선정할 교육대상자 리스트 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/acceptTargetMemberList.do") public String acceptTargetMemberList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { Map<?, ?> view = approvalService.selectStudentManagerIsClosed(commandMap); model.addAttribute("view", view); List<?> list = approvalService.selectAcceptTargetMemberList(commandMap); model.addAttribute("list", list); model.addAllAttributes(commandMap); return "adm/prop/acceptTargetMemberList"; } /** * 선정할 교육대상자 추가하기 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/acceptTargetMemberAction.do") public String acceptTargetMemberAction(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String url = "/adm/prop/acceptTargetMemberList.do"; Map<String, Object> resultMap = approvalService.acceptTargetMember(commandMap); boolean isok = (Boolean) resultMap.get("isok"); if(isok) { resultMsg = egovMessageSource.getMessage("success.common.save"); }else{ if(null != resultMap.get("missAreaCodeMsg")) { resultMsg = resultMap.get("missAreaCodeMsg").toString(); } else { resultMsg = egovMessageSource.getMessage("fail.common.save"); } } model.addAttribute("isOpenerReload", "OK"); model.addAttribute("isClose", "OK"); model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); return "forward:" + url; } /** * 수강신청 처리상태(승인, 취소, 반려, 삭제) 이하 정보 수정 및 수강생으로 등록처리 프로세스 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/studentManagerAction.do") public String studentManagerAction(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String url = "/adm/prop/studentManagerList.do"; boolean isok = approvalService.studentManagerProcess(commandMap); if(isok) { resultMsg = egovMessageSource.getMessage("success.common.save"); }else{ resultMsg = egovMessageSource.getMessage("fail.common.save"); } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); return "forward:" + url; } /** * 수강신청 결제 방법 변경 페이지(무통장, 교육청일경우 결제계좌에서 전송이 안되어 없을시 변경해줌 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/studentPayTypeView.do") public String studentPayTypeView(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { model.addAllAttributes(commandMap); return "adm/prop/studentPayTypeView"; } /** * 수강신청 결제 방법 변경 프로세스(무통장, 교육청일경우 결제계좌에서 전송이 안되어 없을시 변경해줌 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/studentPayTypeAction.do") public String studentPayTypeAction(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { String resultMsg = ""; String url = "/adm/prop/studentPayTypeView.do"; boolean isok = approvalService.studentPayTypeProcess(commandMap); if(isok) { resultMsg = egovMessageSource.getMessage("success.common.save"); }else{ resultMsg = egovMessageSource.getMessage("fail.common.save"); } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); return "forward:" + url; } /** * 설문 척도 보기 리스트 - ajax * * @param HttpServletResponse * response, HttpServletRequest request, Map commandMap * @return * @exception Exception */ @RequestMapping(value = "/adm/prop/updateMemberSubjSeqInfo.do") public ModelAndView updateMemberSubjSeqInfo( HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap) throws Exception { Object result = null; ModelAndView modelAndView = new ModelAndView(); Map<String, Object> map = approvalService.updateMemberSubjSeqInfo(commandMap); Map resultMap = new HashMap(); resultMap.put("result", map.get("resultYn")); modelAndView.addAllObjects(resultMap); modelAndView.setViewName("jsonView"); return modelAndView; } /** * 기수변경 화면으로 이동 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/studentManagerView.do") public String studentManagerView(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { log.error(commandMap); //List<Map<String, Object>> resultList = approvalService.studentManagerView(commandMap); //최초 신청 기수 Map subjseqInfo = approvalService.selectStudentSubjseqView(commandMap); //재수강 가능한 기수 리스트 조회 List<Map<String, Object>> resultList = approvalService.studentSubjseqList(commandMap); model.addAttribute("subjseqInfo", subjseqInfo); model.addAttribute("resultList", resultList); model.addAllAttributes(commandMap); return "adm/prop/studentManagerView"; } /** * 기수변경 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/adm/prop/updateSubjseq.do") public String updateSubjseq(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception { log.error("기수변경"); //Map<String, Object> map = approvalService.updateMemberSubjSeqInfo(commandMap); try { Map<String, Object> map = approvalService.updateMemberSubjseqProc(commandMap); model.addAttribute("map", map); String resultMsg = ""; if("Y".equals(map.get("resultYn"))) { resultMsg = egovMessageSource.getMessage("success.common.save"); }else if("A".equals(map.get("resultYn"))){ resultMsg = egovMessageSource.getMessage("common.isExist.msg"); }else{ resultMsg = egovMessageSource.getMessage("fail.common.save"); } model.addAttribute("resultMsg", resultMsg); model.addAllAttributes(commandMap); } catch (Exception e) { System.out.println("e -------> "+e); } return "adm/prop/studentManagerView"; } }
package KataProblems.week8.SimpleMaze; public class SimpleMaze { public static char[][] newMaze; public static boolean pathFound; public static boolean hasExit(String[] maze) { int maxLength=0; boolean singleK=false; int rowPos=-1; int colPos=-1; pathFound=false; // get starting position and ensure only one starting position for (int i=0; i<maze.length; i++){ maxLength = Math.max(maze[i].length(),maxLength); for (int j=0; j<maze[i].length();j++){ if (maze[i].charAt(j)=='k' && !singleK){ singleK=true; rowPos=i; colPos=j; } else if (maze[i].charAt(j)=='k' && singleK){ throw new RuntimeException(); } } } // ensure maze rectangular to avoid boiler plate code newMaze = new char[maze.length][maxLength]; for (int k=0; k<maze.length; k++){ while(maze[k].length()<maxLength){ maze[k]=maze[k].concat(" "); } for (int l=0; l<maze[k].length(); l++){ newMaze[k][l]=maze[k].charAt(l); } } //check if Solved at starting position if (solved(rowPos,colPos, maze.length, maxLength)){return true;} // dfs findPath(rowPos, colPos); printFinalMaze(); return pathFound; } // recurse until either 1) exit found 2) no additional paths available public static void findPath(int row, int col){ if (!pathFound) { // check left if (newMaze[row][col-1]==' '){ newMaze[row][col-1]='k'; if (solved(row,col-1,newMaze.length,newMaze[0].length)){ pathFound = true; return; } findPath(row,col-1); } // check up if (newMaze[row-1][col]==' '){ newMaze[row-1][col]='k'; if (solved(row-1,col,newMaze.length,newMaze[0].length)){ pathFound = true; return; } findPath(row-1,col); } // check right if (newMaze[row][col+1]==' '){ newMaze[row][col+1]='k'; if (solved(row,col+1,newMaze.length,newMaze[0].length)){ pathFound = true; return; } findPath(row,col+1); } // check down if (newMaze[row+1][col]==' '){ newMaze[row+1][col]='k'; if (solved(row+1,col,newMaze.length,newMaze[0].length)){ pathFound = true; return; } findPath(row+1,col); } } } public static boolean solved(int row, int col, int numRows, int maxLength){ if (row==0 || row==numRows-1 || col==0 || col==maxLength-1){ return true; } return false; } public static void printFinalMaze(){ for (int row=0; row<newMaze.length; row++){ for (int col=0; col<newMaze[0].length; col++){ System.out.print(newMaze[row][col]); } System.out.println(); } System.out.println(); } }
package com.example.gtraderprototype.model; import android.content.Context; import android.provider.ContactsContract; import android.util.Log; import com.example.gtraderprototype.entity.Difficulty; import com.example.gtraderprototype.entity.GameInstance; import com.example.gtraderprototype.entity.Player; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.util.ArrayList; public class GameInstanceInteractor extends Interactor{ final String localStateFilename = "states"; private GameInstance gameInstance; public GameInstanceInteractor(Database db){ super(db); } public GameInstance getGameInstance(){ return gameInstance; } public Difficulty getGameDifficulty(){ return gameInstance.getDifficulty(); } public ArrayList<String> getLocalGames(Context context){ File file = new File(context.getFilesDir(), localStateFilename); ArrayList<String> gameIDs = new ArrayList<>(); try{ if(file.exists()){ Log.d("GTrader", "Retrieving games..."); BufferedReader br = new BufferedReader(new FileReader(file)); String temp = ""; temp = br.readLine(); while(temp!=null){ gameIDs.add(temp); temp = br.readLine(); } Log.d("GTrader", gameIDs.toString()); } }catch(Exception e){ Log.d("ERR", e.toString()); } return gameIDs; } public void setInstance(GameInstance instance){ this.gameInstance = instance; Log.d("GTrader", instance.toString()); } public void newGame(Difficulty difficulty, Player player, Context context){ this.gameInstance = new GameInstance(difficulty, player); try{ FileOutputStream outputStream; String fileContents = gameInstance.getGameID(); outputStream = context.openFileOutput(localStateFilename, Context.MODE_APPEND); outputStream.write((fileContents+"\r\n").getBytes()); outputStream.close(); }catch (Exception e) { e.printStackTrace(); } Log.d("GTrader", "New instance: "+gameInstance.toString()); Database.saveState(gameInstance); } public void removeGame(String gameID, Context context){ ArrayList<String> currentSaves = getLocalGames(context); File file = new File(context.getFilesDir(), localStateFilename); file.delete(); try{ FileOutputStream outputStream; outputStream = context.openFileOutput(localStateFilename, Context.MODE_APPEND); for(String save: currentSaves){ if(!save.equals(gameID)){ outputStream.write((save+"\r\n").getBytes()); } } outputStream.close(); Database.removeState(gameID); }catch (Exception e) { e.printStackTrace(); } } public void saveGameToDB(){ Database.saveState(this.gameInstance); } }
package com.tushar.lms.book.serviceimpl; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.modelmapper.ModelMapper; import org.modelmapper.convention.MatchingStrategies; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tushar.lms.book.entity.Book; import com.tushar.lms.book.repository.BookRepository; import com.tushar.lms.book.requestmodel.NewBookRequest; import com.tushar.lms.book.responsemodel.AllBooksListResponse; import com.tushar.lms.book.responsemodel.GetBookResponse; import com.tushar.lms.book.responsemodel.IssuedBookResponse; import com.tushar.lms.book.responsemodel.NewBookResponse; import com.tushar.lms.book.service.BookService; @Service public class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository; @Autowired private ModelMapper modelMapper; Logger logger = LoggerFactory.getLogger(BookServiceImpl.class); @Override public NewBookResponse addNewBook(NewBookRequest addNewBook) { logger.info("Inside BookServiceImpl ---------> addNewBook"); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Book newBook = modelMapper.map(addNewBook, Book.class); newBook.setBookId(UUID.randomUUID().toString()); Book savedBok = bookRepository.save(newBook); NewBookResponse returnBook = modelMapper.map(savedBok, NewBookResponse.class); return returnBook; } @Override public List<AllBooksListResponse> getAllBooks() { logger.info("Inside BookServiceImpl ---------> getAllBooks"); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); List<Book> books = bookRepository.findAll(); List<AllBooksListResponse> bookDtos = books.stream() .map(book -> modelMapper.map(book, AllBooksListResponse.class)).collect(Collectors.toList()); return bookDtos; } @Override public GetBookResponse getBook(String bookId) { logger.info("Inside BookServiceImpl ---------> getBook"); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); Book foundBook = bookRepository.findByBookId(bookId); GetBookResponse bookDto = modelMapper.map(foundBook, GetBookResponse.class); return bookDto; } @Override public List<IssuedBookResponse> getIssuedBooks(String userId) { logger.info("Inside BookServiceImpl ---------> getIssuedBooks"); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); List<Book> books = bookRepository.findByUserId(userId); List<IssuedBookResponse> issuedBookDtos = books.stream() .map(book -> modelMapper.map(book, IssuedBookResponse.class)).collect(Collectors.toList()); return issuedBookDtos; } @Override public List<AllBooksListResponse> getAvailableBooks() { logger.info("Inside BookServiceImpl ---------> getAvailableBooks"); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); List<Book> books = bookRepository.getAvailableBooks(); List<AllBooksListResponse> bookDtos = books.stream() .map(book -> modelMapper.map(book, AllBooksListResponse.class)).collect(Collectors.toList()); return bookDtos; } @Override public Boolean setAvailableStatus(String bookId, String userId) { logger.info("Inside BookServiceImpl ---------> setAvailableStatus"); Book bookToBeFound = bookRepository.findByBookId(bookId); if (bookToBeFound.getAvailable()) { bookToBeFound.setUserId(userId); bookToBeFound.setAvailable(false); Book savedBook = bookRepository.save(bookToBeFound); if (savedBook != null) { return true; } } if (!bookToBeFound.getAvailable()) { bookToBeFound.setUserId(""); bookToBeFound.setAvailable(true); Book savedBook = bookRepository.save(bookToBeFound); if (savedBook != null) { return true; } } return false; } }
package cz.muni.pv239.marek.exercise5.fragments; import android.app.ListFragment; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import cz.muni.pv239.marek.exercise5.R; /** * Created by Andy on 04-Jan-15. */ public class StepTitleFragment extends ListFragment { public StepTitleFragment() { } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); String[] stepTitles = getResources().getStringArray(R.array.step_titles); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, stepTitles); setListAdapter(adapter); } @Override public void onListItemClick(ListView l, View v, int position, long id) { OnStepChangedListener listener = (OnStepChangedListener) getActivity(); listener.OnSelectionChanged(position); } }
package com.stk123.model.bo; import com.stk123.common.util.JdbcUtils.Column; import java.io.Serializable; import com.stk123.common.util.JdbcUtils.Table; import java.sql.Timestamp; @SuppressWarnings("serial") @Table(name="STK_EARNINGS_FORECAST") public class StkEarningsForecast implements Serializable { @Column(name="CODE") private String code; @Column(name="FORECAST_YEAR") private String forecastYear; @Column(name="FORECAST_NET_PROFIT") private Double forecastNetProfit; @Column(name="INSERT_TIME") private Timestamp insertTime; @Column(name="PE") private Double pe; private Stk stk; public String getCode(){ return this.code; } public void setCode(String code){ this.code = code; } public String getForecastYear(){ return this.forecastYear; } public void setForecastYear(String forecastYear){ this.forecastYear = forecastYear; } public Double getForecastNetProfit(){ return this.forecastNetProfit; } public void setForecastNetProfit(Double forecastNetProfit){ this.forecastNetProfit = forecastNetProfit; } public Timestamp getInsertTime(){ return this.insertTime; } public void setInsertTime(Timestamp insertTime){ this.insertTime = insertTime; } public Double getPe(){ return this.pe; } public void setPe(Double pe){ this.pe = pe; } public Stk getStk(){ return this.stk; } public void setStk(Stk stk){ this.stk = stk; } public String toString(){ return "code="+code+",forecastYear="+forecastYear+",forecastNetProfit="+forecastNetProfit+",insertTime="+insertTime+",pe="+pe+",stk="+stk; } }
package game; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; public class Predictor { Piece piece; Piece piece2; ArrayList<Piece> pieces = new ArrayList<Piece>(); int[][] prediction = new int[22][10]; int[][] staticb = new int[22][10]; //test public void updatePrediction(Piece piece, TetrisCanvas canvas, Board b) { int y = piece.getY(); int iter = 0; int repetitions = 0; while(!b.overlaps(piece, piece.getX(), piece.getY() + 1) & !(piece.getY() + piece.getLength() == 22)) { piece.setY(piece.getY() + 1); if(repetitions > 30) { break; } if(b.getBoard().equals(new int[22][10])) { break; } System.out.println("HI"); repetitions ++; } prediction = new int[22][10]; prediction = b.addPiece(piece, prediction); piece.setY(y); } public int[][] getPrediction(){ return this.prediction; } public Predictor() { int[][] data = { {1,1,0,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0}, }; addPiece(1, data, 5, 2, 2); int[][] data1 = { {1,0,0,0}, {1,0,0,0}, {1,0,0,0}, {1,0,0,0}, }; addPiece(2, data1, 6, 1, 4); int[][] data2 = { {0,1,1,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0}, }; addPiece(3, data2, 7, 3, 2); int[][] data3 = { {1,1,0,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0}, }; addPiece(4, data3, 8, 3, 2); int[][] data4 = { {1,0,0,0}, {1,0,0,0}, {1,1,0,0}, {0,0,0,0}, }; addPiece(5, data4, 9, 2, 3); int[][] data5 = { {0,1,0,0}, {0,1,0,0}, {1,1,0,0}, {0,0,0,0}, }; addPiece(6, data5, 10, 2, 3); int[][] data6 = { {1,1,1,0}, {0,1,0,0}, {0,0,0,0}, {0,0,0,0}, }; addPiece(7, data6, 11, 3, 2); piece = this.randomizePeice(System.currentTimeMillis()); piece2 = this.randomizePeice(new Random(System.currentTimeMillis()).nextInt((10000 - 5) + 1) + 5); } public void addPiece(int color, int[][] data, int ID, int width, int length) { pieces.add(new Piece(color, data, ID, width, length)); } public Piece nextPiece() { Piece retVal = piece.clone(); piece = piece2.clone(); piece2 = this.randomizePeice(System.currentTimeMillis()); return retVal; } public Piece randomizePeice(long l) { int i = new Random(l).nextInt((11 - 5) + 1) + 5; for(Piece piece: pieces) { if(piece.getID() == i) { piece.center(); return piece; } } return null; } public Piece getNextPiece(boolean first) { if(first) { piece.setLeft(); return piece; } return piece2; } public int[][] getNextPiece(int j, TetrisCanvas canvas) { Board b = new Board(canvas); b.reset(); piece.setLeft(); piece2.setLeft(); if(j == 0) { return b.addPiece(piece, new int[4][4]); } return b.addPiece(piece2, new int[4][4]); } }
/* * Nice Numbers for Graph Labels * by Paul Heckbert * from "Graphics Gems", Academic Press, 1990 */ /* * label.c: demonstrate nice graph labeling * * Paul Heckbert 2 Dec 88 */ /* main(ac, av) int ac; char **av; { double*locs, min, max; int i, NTICK; if (ac!=4) { fprintf(stderr, "Usage: label <min> <max> <nticks>\n"); exit(1); } min = atof(av[1]); max = atof(av[2]); NTICK = atoi(av[3]); locs = (double *)malloc(NTICK * sizeof(double)); NTICK = ticlocs(min, max,NTICK,locs); for (i = 0; i < NTICK; i++) fprintf(stdout, "%f\n",locs[i]); } */ /* * loose_label: demonstrate loose labeling of data range from min to max. * (tight method is similar) */ public class ticlocs { double[] locs; int numlocs; public ticlocs(double min, double max,int NTICK) { int i, nfrac; double d; /* tick mark spacing */ double graphmin, graphmax; /* graph range min and max */ double range, x; /* we expect min!=max */ range = nicenum(max-min, false); d = nicenum(range/(NTICK-1), true); System.out.println("nicenum ranges = " + range + " and " + d); graphmin = Math.floor(min/d)*d; graphmax = Math.ceil(max/d)*d; System.out.println("graphmin = " + graphmin + " graphmax = " + graphmax); nfrac = (int)Math.max(-Math.floor(log10(d)), 0d); /* # of fractional digits to show */ for (x=graphmin, i = 0; x<graphmax+.5d*d; x+=d, i++) { } locs = new double[i]; for (x=graphmin, i = 0; x<graphmax+.5d*d; x+=d, i++) { locs[i] = x; } numlocs = i; System.out.println("numlocs = " + numlocs); } public double log10(double Num) { return Math.log(Num)/Math.log(10); } /* * nicenum: find a "nice" number approximately equal to x. * Round the number if round=true, take ceiling if round=false */ public double nicenum(double x, boolean round) { int expv; /* exponent of x */ double f; /* fractional part of x */ double nf; /* nice, rounded fraction */ expv = (int)Math.floor(log10(x)); // I sure hope that's a log10()! f = x/Math.pow(10., expv); /* between 1 and 10 */ if (round) if (f<1.5d) nf = 1d; else if (f<3d) nf = 2d; else if (f<7d) nf = 5d; else nf = 10d; else if (f<=1d) nf = 1d; else if (f<=2d) nf = 2d; else if (f<=5d) nf = 5d; else nf = 10d; return nf*Math.pow(10d, expv); } /* if roundoff errors in pow cause problems, use this: */ public double alternate_pow(double a, int n) { double x; x = 1d; if (n>0) for (; n>0; n--) x *= a; else for (; n<0; n++) x /= a; return x; } }
/** * */ package com.oriaxx77.javaplay.threads.utilities.executors; import java.util.concurrent.Executor; /** * A very simple non-asynchronous {@link Executor} implementation. * The {@link #execute(Runnable)} method simply calls the passed * command's run() method. The {@link #main(String[])} method * demoes the usage of this class with executing an anonymous * 'Hello World' printer {@link Runnable}. Noteice that there is no new thread here, jut the main thread. * @author BagyuraI */ public class NonAsynchExecutor implements Executor { /** * It simply calls the run method of the provided command. * @see java.util.concurrent.Executor#execute(java.lang.Runnable) */ @Override public void execute(Runnable command) { command.run(); } /** * Demo the usage of this class with executing an anonymous * Hello World printer {@link Runnable} that prints our the <i>Hello World!</i> sentence. * @param args */ public static void main(String[] args) { Executor executor = new NonAsynchExecutor(); executor.execute( new Runnable() { @Override public void run() { System.out.println( "Hello World!" ); } }); } }
package seedu.project.model.task; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.project.logic.commands.CommandTestUtil.VALID_DEADLINE_CP2106; import static seedu.project.logic.commands.CommandTestUtil.VALID_DESCRIPTION_CP2106; import static seedu.project.logic.commands.CommandTestUtil.VALID_NAME_CP2106; import static seedu.project.logic.commands.CommandTestUtil.VALID_TAG_CP2106; import static seedu.project.testutil.TypicalTasks.CP2106_MILESTONE; import static seedu.project.testutil.TypicalTasks.CS2101_MILESTONE; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.project.logic.LogicManager; import seedu.project.testutil.TaskBuilder; public class TaskTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void asObservableList_modifyList_throwsUnsupportedOperationException() { Task task = new TaskBuilder().build(); thrown.expect(UnsupportedOperationException.class); task.getTags().remove(0); } @Test public void isSameTask() { // same object -> returns true assertTrue(CS2101_MILESTONE.isSameTask(CS2101_MILESTONE)); // null -> returns false assertFalse(CS2101_MILESTONE.isSameTask(null)); // different description and deadline -> returns false Task editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withDescription(VALID_DESCRIPTION_CP2106) .withDeadline(VALID_DEADLINE_CP2106).build(); assertFalse(CS2101_MILESTONE.isSameTask(editedCS2101Milestone)); // different name -> returns false editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withName(VALID_NAME_CP2106).build(); assertFalse(CS2101_MILESTONE.isSameTask(editedCS2101Milestone)); // same name, same description, different attributes -> returns true editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withDeadline(VALID_DEADLINE_CP2106) .withTags(VALID_TAG_CP2106).build(); assertTrue(CS2101_MILESTONE.isSameTask(editedCS2101Milestone)); // same name, same deadline, different attributes -> returns true editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withDescription(VALID_DESCRIPTION_CP2106) .withTags(VALID_TAG_CP2106).build(); assertTrue(CS2101_MILESTONE.isSameTask(editedCS2101Milestone)); // same name, same description, same deadline, different attributes -> returns true editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withTags(VALID_TAG_CP2106).build(); assertTrue(CS2101_MILESTONE.isSameTask(editedCS2101Milestone)); } @Test public void equals() { LogicManager.setState(true); System.out.println("hello"); // same values -> returns true System.out.println(CS2101_MILESTONE.getName().toString()); System.out.println(CS2101_MILESTONE.getDeadline().toString()); System.out.println(CS2101_MILESTONE.getTags().toString()); System.out.println(CS2101_MILESTONE.getDescription().toString()); Task cs2101MilestoneCopy = new TaskBuilder(CS2101_MILESTONE).build(); assertTrue(CS2101_MILESTONE.equals(cs2101MilestoneCopy)); // same object -> returns true assertTrue(CS2101_MILESTONE.equals(CS2101_MILESTONE)); // null -> returns false assertFalse(CS2101_MILESTONE.equals(null)); // different type -> returns false assertFalse(CS2101_MILESTONE.equals(5)); // different task -> returns false assertFalse(CS2101_MILESTONE.equals(CP2106_MILESTONE)); // different name -> returns false Task editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withName(VALID_NAME_CP2106).build(); assertFalse(CS2101_MILESTONE.equals(editedCS2101Milestone)); // different description -> returns false editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withDescription(VALID_DESCRIPTION_CP2106).build(); assertFalse(CS2101_MILESTONE.equals(editedCS2101Milestone)); // different deadline -> returns false editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withDeadline(VALID_DEADLINE_CP2106).build(); assertFalse(CS2101_MILESTONE.equals(editedCS2101Milestone)); // different tags -> returns false editedCS2101Milestone = new TaskBuilder(CS2101_MILESTONE).withTags(VALID_TAG_CP2106).build(); assertFalse(CS2101_MILESTONE.equals(editedCS2101Milestone)); } }
package com.github.dockerjava.core.command; import com.github.dockerjava.api.command.CreateExecCmd; import com.github.dockerjava.api.command.CreateExecResponse; public class CreateExecCmdImpl extends BaseExecCmdImpl<CreateExecCmd, CreateExecResponse> implements CreateExecCmd { public CreateExecCmdImpl(CreateExecCmd.Exec exec, String containerId) { super(exec); withContainerId(containerId); } }
package me.lordall.lordrp.command; import me.lordall.lordrp.mysql.PlayerMysql; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerMoveEvent; /** * Created by Lord_All on 30/05/2018 */ public class MoneyCommand implements CommandExecutor { private PlayerMysql playerInfo = new PlayerMysql(); @Override public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) { Player playerExecutor = (Player) commandSender; if (playerInfo.fetchPlayerPermissions(playerExecutor.getUniqueId().toString()) == 2) { if (args[2] != null) { Player player = Bukkit.getPlayer(args[1]); int coinPlayer = playerInfo.fetchPlayerCoin(player.getUniqueId().toString()); switch (args[0]) { case "set": int setMoney = Integer.parseInt(args[2]); playerInfo.updatePlayerMoney(player, setMoney); System.out.println("Set for " + player.getDisplayName() + " money : " + setMoney); break; case "add": int addMoney = Integer.parseInt(args[2]); addMoney += coinPlayer; playerInfo.updatePlayerMoney(player, addMoney); System.out.println("Add for " + player.getDisplayName() + " money : " + addMoney); break; case "remove": int removeMoney = coinPlayer - Integer.parseInt(args[2]); playerInfo.updatePlayerMoney(player, removeMoney); System.out.println("Remove for " + player.getDisplayName() + " money : " + removeMoney); break; case "clear": playerInfo.updatePlayerMoney(player, 0); System.out.println("Clear money for " + player.getDisplayName()); break; } } } else { playerExecutor.sendMessage("§4You don't have the permissions to execute this command"); } return false; } }
/* * 자바의 컬렉션프레임웍의 객체 중 데이터가 key-value의 쌍으로 되어 있는 형식을 전담하여 * 처리할 수 있는 객체를 Properties라 한다. * 이 세상의 여러 형태의 데이터 형식 중 오직 key-value로 된 쌍만을 이해한다!! * */ package study; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class PropTest { public PropTest() { //실행중인 자바코드에서 특정 디렉토리에 들어있는 문서파일을 먼저 접근해야 함 FileInputStream fis = null; Properties props=new Properties(); try { fis = new FileInputStream("C:/eclipse-workspace/javaee_workspace/MVCFramework/WebContent/WEB-INF/mapping/mapping.properties"); props.load(fis); //프로퍼티스 객체와 스트림 연결 //지금부터는 key값으로 검색이 가능하다 String value = props.getProperty("/movie.do"); System.out.println(value); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { if(fis!=null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new PropTest(); } }
package hw7.com.company.vehicles; import hw7.com.company.details.Engine; import hw7.com.company.professions.Driver; public class Lorry extends Car { private int capacity; public Lorry(String carBrand, String carCaseType, int weight, int capacity, Engine engine, Driver driver) { super(carBrand, carCaseType, weight, engine, driver); this.capacity = capacity; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } @Override public void printInfo() { System.out.println("Автомобиль марки: " + getCarBrand()); System.out.println("Тип кузова: " + getCarCaseType()); System.out.println("Вес: " + getWeight()); System.out.println("Грузоподъемность: " + getCapacity()); System.out.println("Двигатель: " + getEngine().toString()); System.out.println("Водитель: " + getDriver().toString()); } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.json; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.yahoo.cubed.util.Utils; import lombok.Data; import lombok.extern.slf4j.Slf4j; /** * New funnel group query JSON structure. */ @Slf4j @Data @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class NewFunnelGroupQuery extends FunnelGroupQuery { /** Funnel group Name. */ private String name; /** * Check if JSON is valid. * @return null if valid, error message if invalid */ public String isValid() { String nameErrorMessage = Utils.validateRegularTextJsonField(name, Utils.NAME_JSON_FIELD); if (nameErrorMessage != null) { return nameErrorMessage; } return super.isValid(); } }
package com.flyingh.moguard; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; import com.flyingh.moguard.app.MoGuardApp; public class AppPermissionsActivity extends Activity { private static final String TAG = "AppPermissionsActivity"; private TextView appNameTextView; private TextView packageNameTextView; private ScrollView scrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_permissions); appNameTextView = (TextView) findViewById(R.id.appNameTextView); packageNameTextView = (TextView) findViewById(R.id.packageNameTextView); scrollView = (ScrollView) findViewById(R.id.scrollView); showUI(); } private void showUI() { try { MoGuardApp application = (MoGuardApp) getApplication(); appNameTextView.setText(application.process.getApp().getLabel()); packageNameTextView.setText(application.process.getApp().getPackageName()); Class<?> cls = Class.forName("android.widget.AppSecurityPermissions"); Constructor<?> constructor = cls.getDeclaredConstructor(Context.class, String.class); constructor.setAccessible(true); Object newInstance = constructor.newInstance(this, application.process.getApp().getPackageName()); Method method = cls.getDeclaredMethod("getPermissionsView"); method.setAccessible(true); View view = (View) method.invoke(newInstance); scrollView.addView(view); application.process = null; } catch (Exception e) { Log.i(TAG, e.getMessage()); throw new RuntimeException(e); } } }
package lab5.abstracts; import lab5.util.Validador; import lab5.ids.ProdutoID; import java.util.Objects; /** * Representação do produto no sistema * * @author Charles Bezerra de Oliveira Júnior - 119110595 * */ public abstract class Produto implements Comparable<Produto> { /** * nome do produto */ protected String nome; /** * descrição do produto */ protected String descricao; /** * endereço composto do produto */ protected ProdutoID id; /** * Construtor do produto * @param nome atribui valor ao nome do produto * @param descricao atribui valor a descrição do produto */ protected Produto(String nome, String descricao){ Validador.prefixoError = "Erro no cadastro de produto"; this.nome = Validador.validaString("nome nao pode ser vazio ou nulo.", nome); this.descricao = Validador.validaString("descricao nao pode ser vazia ou nula.", descricao); this.id = new ProdutoID(nome, descricao); } /** * Retorna o nome do produto * @return String com o nome do produto */ public String getNome() { return this.nome; } /** * Retorna a descricao do produto * @return String com a descricao do produto */ public String getDescricao() { return this.descricao; } /** * Retorna o identificador do produto * @return ProdutoID */ public ProdutoID getID() { return this.id; } /** * Retorna o valor do preco do produto * @return double */ public double getPreco(){ return 0.0; } @Override public String toString(){ return this.nome + " - " + this.descricao; } @Override public int hashCode(){ return Objects.hash(this.id); } @Override public boolean equals(Object o){ if (o == this) return true; if (o == null) return false; if (o.getClass() != this.getClass()) return false; Produto p = (Produto) o; return this.hashCode() == p.hashCode(); } @Override public int compareTo(Produto p) { if (this.getNome().compareTo( p.getNome() ) == 1) //Se os nomes dos produtos forem iguais return this.toString().compareTo( p.toString() ); //Retorne a comparação de suas represetações textuais return this.getNome().compareTo( p.getNome() ); //Se não, retorne a comparação de seus nomes } }
package com.codecool.tripplanner; import android.app.Application; import com.codecool.tripplanner.roomdatabase.DestinationRepository; import com.codecool.tripplanner.roomdatabase.entity.Destination; public class AddDestinationPresenter<V extends AddDestinationView> implements BasePresenter<V> { private DestinationRepository repo; V view; public AddDestinationPresenter(Application app){ this.repo = new DestinationRepository(app); } public void insert(Destination destination){ repo.insert(destination); view.displayToast(); } @Override public void subscribe(V view) { this.view = view; } @Override public void unsubscribe() { view = null; } }
package ru.mirea.pr3; import java.lang.*; public class Book{ private String authorname; private String description; private int pagesnums; public Book(String c, String d,int p){ authorname = c; description = d; pagesnums=p; } public void setAuthorName(String authorname) { this.authorname = authorname; } public void setPagesnums(int pagesnums){ this.pagesnums = pagesnums; } public void setDescription(String description) { this.description = description; } public String getAuthorname(String authorname){ return authorname; } public String getDescription(String description) { return description; } public int getPagesnums(int pagesnums){ return pagesnums; } public String toString(){ return this.authorname + ", " + this.description + ", number of pages: " + this.pagesnums; } }
package com.example.login.model; public class UserInfo { private String userId; private String[] roles; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String[] getRoles() { return roles; } public void setRoles(String[] roles) { this.roles = roles; } }
package com.example.g0294.tutorial.datastorage; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; public class ContactDao { private SQLiteDatabase db; private DatabaseHandler dbHelper; public ContactDao(Context context) { dbHelper = new DatabaseHandler(context); } // 關閉資料庫 public void close() { db.close(); } // 新增聯絡人 public void addContact(Contact contact) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DatabaseHandler.KEY_NAME, contact.get_name()); values.put(DatabaseHandler.KEY_PH_NO, contact.get_phone_number()); db.insert(DatabaseHandler.TABLE_CONTACTS, null, values); // // db.execSQL("INSERT INTO contacts (name, phone_number) values (?,?)", // new Object[]{contact.get_name(), contact.get_phone_number()}); // close(); // 關閉連線 } // 取得單一聯絡人資訊 public Contact getContact(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Contact result = new Contact(); Cursor cursor = db.query(DatabaseHandler.TABLE_CONTACTS, // The table to query new String[]{DatabaseHandler.KEY_ID, DatabaseHandler.KEY_NAME, DatabaseHandler.KEY_PH_NO}, // The columns to return DatabaseHandler.KEY_ID + "=?", // The columns for the WHERE clause new String[]{String.valueOf(id)}, // The values for the WHERE clause null, null, null, null); if (cursor != null) { cursor.moveToFirst(); result._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id"))); result._name = cursor.getString(1); result._phone_number = cursor.getString(2); cursor.close(); return result; } return null; } // 取得所有聯絡人資料 public List<Contact> getAllContacts() { List<Contact> contactList = new ArrayList<>(); // Select All Query String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_CONTACTS; SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { while (cursor.moveToNext()) { Contact contact = new Contact(); contact.set_id(Integer.parseInt(cursor.getString(0))); contact.set_name(cursor.getString(1)); contact.set_phone_number(cursor.getString(2)); // Adding contact to list contactList.add(contact); } } cursor.close(); return contactList; } // 聯絡人數量 public int getContactsCount() { String countQuery = "SELECT * FROM " + DatabaseHandler.TABLE_CONTACTS; SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(countQuery, null); cursor.close(); return cursor.getCount(); } // 更新聯絡人 public int updateContact(Contact contact) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DatabaseHandler.KEY_NAME, contact.get_name()); values.put(DatabaseHandler.KEY_PH_NO, contact.get_phone_number()); return db.update(DatabaseHandler.TABLE_CONTACTS, values, DatabaseHandler.KEY_ID + " = ?", new String[]{String.valueOf(contact.get_id())}); } // 刪除聯絡人 public void deleteContact(Contact contact) { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete(DatabaseHandler.TABLE_CONTACTS, DatabaseHandler.KEY_ID + " = ?", new String[]{String.valueOf(contact.get_id())}); db.close(); } }
package com.example.test; import android.app.Application; import android.content.Context; import android.os.Bundle; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.nio.channels.CompletionHandler; import java.util.HashMap; import java.util.Map; import androidx.lifecycle.ViewModel; //I realise I've made this viewmodel messy. Usually, I'd have a class for the action (and call the action from the VM) and write proper pojos instead of having hardcoded objects. public class MainViewModel extends ViewModel { private static String schemaId; public String getSchemaId() { return schemaId; } public void setupApi(Context context, final CompletionHandler<String, Void> handler) { String setupURLExt = "merchant/schema"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Network.url + setupURLExt, createSchemaJSONObject(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { processJSONResponse(response); handler.completed(schemaId, null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { return requestHeaders(); } }; Network.getInstance(context).addToRequestQueue(jsonObjectRequest); } public void startTransaction(Context context, final CompletionHandler<Bundle, Void> handler) { String transactionURLExt = "merchant/payment/session"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Network.url + transactionURLExt, createPaymentSessionJSONObject(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { handler.completed(makeBundle(response), null); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { return requestHeaders(); } }; Network.getInstance(context).addToRequestQueue(jsonObjectRequest); } private Map<String, String> requestHeaders() { Map<String, String> header = new HashMap<String, String>(); header.put("content-type", "application/json"); header.put("x-api-key", Network.apiKey); header.put("x-merchant-id", Network.merchentId); return header; } private void processJSONResponse(JSONObject response) { try { JSONObject dataJSON = response.getJSONObject("data"); schemaId = dataJSON.getString("schemaId"); } catch (JSONException e) { e.printStackTrace(); } } private Bundle makeBundle(JSONObject response) { try { JSONObject dataJSON = response.getJSONObject("data"); JSONObject qrJSON = dataJSON.getJSONObject("qr"); Bundle bundle = new Bundle(); bundle.putString(TransactionFragment.TransactionKey.CONTENT.name(), qrJSON.getString("content")); bundle.putString(TransactionFragment.TransactionKey.IMAGE.name(), qrJSON.getString("image")); return bundle; } catch (JSONException e) { e.printStackTrace(); } return null; } private JSONObject createSchemaJSONObject() { try { JSONObject dataJSON = new JSONObject(); dataJSON.put("type", "POS-InStore"); dataJSON.put("description", "Schema to capture the point of sale information"); JSONObject storeIdJSON = new JSONObject(); storeIdJSON.put("type", "string"); JSONObject laneIdJSON = new JSONObject(); laneIdJSON.put("type", "string"); JSONObject rewardsIdJSON = new JSONObject(); rewardsIdJSON.put("type", "string"); JSONObject usePointsJSON = new JSONObject(); usePointsJSON.put("type", "boolean"); JSONObject propJSON = new JSONObject(); propJSON.put("storeId", storeIdJSON); propJSON.put("laneId", laneIdJSON); propJSON.put("rewardsId", rewardsIdJSON); propJSON.put("usePoints", usePointsJSON); JSONObject schemaJSON = new JSONObject(); schemaJSON.put("required", new JSONArray()); schemaJSON.put("type", "object"); schemaJSON.put("properties", propJSON); dataJSON.put("schema", schemaJSON); JSONObject metaObject = new JSONObject(); JSONObject paramObj = new JSONObject(); paramObj.put("data", dataJSON); paramObj.put("meta", metaObject); return paramObj; } catch (JSONException e) { e.printStackTrace(); } return null; } private JSONObject createPaymentSessionJSONObject() { try { JSONObject payloadJSON = new JSONObject(); payloadJSON.put("storeId", "12345"); payloadJSON.put("type", "string"); JSONObject additionalInfoJSON = new JSONObject(); additionalInfoJSON.put("schemaId", schemaId); additionalInfoJSON.put("payload", payloadJSON); JSONObject dataJSON = new JSONObject(); dataJSON.put("location", "Carrum Downs"); dataJSON.put("description", "Schema to capture the point of sale information"); dataJSON.put("additionalInfo", additionalInfoJSON); dataJSON.put("generateQR", true); dataJSON.put("timeToLiveQR", 60); dataJSON.put("timeToLivePaymentSession", 300); JSONObject metaObject = new JSONObject(); JSONObject paramObj = new JSONObject(); paramObj.put("data", dataJSON); paramObj.put("meta", metaObject); return paramObj; } catch (JSONException e) { e.printStackTrace(); } return null; } }
package com.handpay.obm.common.utils; import java.io.*; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Vector; import org.apache.commons.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.dubbo.common.utils.StringUtils; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; /** * Created by liliu on 2015/8/4. */ public class FileUtil { private static final Logger log=LoggerFactory.getLogger(FileUtil.class); private static final String defaultCharset="GBK"; public static void writeData(File f,List<String[]> data,boolean isAppend,String charset) throws Exception{ if(data==null || data.size()==0) return ; checkFile(f); BufferedOutputStream bw2=null; try { bw2=new BufferedOutputStream(new FileOutputStream(f,isAppend)); for(String l:lines(data)){ bw2.write(l.getBytes(Charset.forName(getFileCharset(charset,defaultCharset)))); bw2.write("\r\n".getBytes()); } bw2.flush(); }finally { try { if(bw2!=null) bw2.close(); } catch (IOException e) { e.printStackTrace(); } } } private static String getFileCharset(String charset,String defaultCharset){ if(StringUtils.isEmpty(charset)) return defaultCharset; return charset; } //写少量数据 public static void writeData(File f,String data,boolean isAppend,String charset) throws Exception{ if(StringUtils.isEmpty(data)) return ; checkFile(f); BufferedOutputStream bw2=null; try { bw2=new BufferedOutputStream(new FileOutputStream(f,isAppend)); bw2.write(data.getBytes(Charset.forName(getFileCharset(charset,defaultCharset)))); bw2.flush(); }finally { try { if(bw2!=null) bw2.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void appendData(File f,List<String[]> data,String charset) throws Exception{ if(f.exists()){ writeData(f, data,true,charset); }else{ throw new FileNotFoundException(f.getPath()+" does not exist!"); } } public static void writeWithTransfer(File f,String data,String charset) throws Exception{ writeWithTransferAppend(f,data,charset,false); } public static void writeWithTransferAppend(File f,String data,String charset,boolean isAppend) throws Exception{ if(StringUtils.isEmpty(data)) return ; if(isAppend){ if(f.exists()){ writeWithTransferAppend(f, data.getBytes(charset)); }else{ throw new FileNotFoundException(f.getPath()+" does not exist!"); } }else{ checkFile(f); writeWithTransferAppend(f, data.getBytes(charset)); } } public static void writeWithTransferAppend(File file, byte[] data) throws IOException { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel toFileChannel = raf.getChannel(); ByteArrayInputStream bais = null; System.out.println("write a data chunk: " + data.length + "byte"); bais = new ByteArrayInputStream(data); ReadableByteChannel fromByteChannel = Channels.newChannel(bais); long position=toFileChannel.size(); System.out.println(",position="+position); toFileChannel.transferFrom(fromByteChannel, position, data.length); toFileChannel.close(); fromByteChannel.close(); } public static void appendData(File f,String data,String charset) throws Exception{ if(f.exists()){ writeData(f, data,true,charset); }else{ throw new FileNotFoundException(f.getPath()+" does not exist!"); } } public static void writeData(File f,String data,String charset) throws Exception{ writeData(f, data,true,charset); } public static void deleteFile(String fileName) throws Exception{ File f=new File(fileName); if(f.exists()) f.delete(); else throw new FileNotFoundException(fileName+" does not exist!"); } public static void deleteFileIfExsits(String fileName){ File f=new File(fileName); if(f.exists()) f.delete(); } public static void createFileAndWriteData(File f,List<String[]> data,String charset) throws Exception{ createFile(f); writeData(f, data, false,charset); } private static void checkFile(File f){ File pf=new File(f.getParent()); if(!pf.exists()){ log.info("f path"+f.getParent()+" dose not exist"); pf.mkdirs(); log.info("f path"+f.getParent()+" has created"); } } private static void createFile(File f){ File pf=new File(f.getParent()); if(!pf.exists()) pf.mkdirs(); // try { // f.createNewFile(); // } catch (IOException e) { // e.printStackTrace(); // } } public static void createFileAndWriteData(File f,List<String[]> data,List<String[]> titles,String charset) throws Exception{ createFile(f); writeData(f, titles, false,charset); writeData(f, data, true,charset); } public static String[] lines(List<String[]> data){ String[] buf=new String[data.size()]; int j=0; for(String[] record:data){ StringBuilder sb=new StringBuilder(); for(int i=0;i<record.length;i++) { if(i>0) sb.append(","); sb.append(record[i]); } buf[j++]=sb.toString(); } return buf; } public static List<String[]> getTData(){ List<String[]> l=new ArrayList<String[]>(10); try { for (int i = 0; i < 10; i++) { String[] ld = new String[] { "序号","商户名称","商品名称","凭证号","2015/08/0614:09:13"}; l.add(ld); } } catch (Exception e) { e.printStackTrace(); } return l; } public static List<String[]> getTitle(){ List<String[]> l=new ArrayList<String[]>(10); for(int i=0;i<2;i++){ String[] ld=new String[]{"","",i+"-tilte","",""}; l.add(ld); } return l; } /** * 利用JSch包实现SFTP下载、上传文件 * @param ip 主机IP * @param user 主机登陆用户名 * @param psw 主机登陆密码 * @param port 主机ssh2登陆端口,如果取默认值,传-1 */ public static void sshSftp(String ip, String user, String psw ,int port,String uploadPath,String sourceFile,String fileName) throws Exception{ Session session = null; Channel channel = null; JSch jsch = new JSch(); if(port <=0){ //连接服务器,采用默认端口 session = jsch.getSession(user, ip); }else{ //采用指定的端口连接服务器 session = jsch.getSession(user, ip ,port); } //如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception("session is null"); } //设置登陆主机的密码 session.setPassword(psw);//设置密码 //设置第一次登陆的时候提示,可选值:(ask | yes | no) Properties conf=new Properties(); conf.put("StrictHostKeyChecking", "no"); session.setConfig(conf); //设置登陆超时时间 session.connect(30000); try { //创建sftp通信通道 channel = (Channel) session.openChannel("sftp"); channel.connect(1000); ChannelSftp sftp = (ChannelSftp) channel; //进入服务器指定的文件夹 sftp.cd(uploadPath); //列出服务器指定的文件列表 // Vector v = sftp.ls("*.txt"); // for(int i=0;i<v.size();i++){ // System.out.println(v.get(i)); // } // //以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换以下流就可以了 OutputStream outstream = sftp.put(fileName); InputStream instream = new FileInputStream(new File(sourceFile)); byte b[] = new byte[1024]; int n; while ((n = instream.read(b)) != -1) { outstream.write(b, 0, n); } outstream.flush(); outstream.close(); instream.close(); } catch (Exception e) { e.printStackTrace(); } finally { session.disconnect(); channel.disconnect(); } } public static void w(String target,String source) throws FileNotFoundException{ InputStream in =null; OutputStream out =new FileOutputStream(target); try { in = new FileInputStream(source); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf) )!= -1) { out.write(buf, 0, len); } out.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if (in != null) in.close(); if (out != null) { out.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } public static void main(String[] args){ for(int i=0;i<10;i++){ // try { // // w("d:/w"+i+".csv"); // } catch (FileNotFoundException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } } String ip="10.48.171.203"; String user="dev"; String psw="dev" ;int port=22; // try { // sshSftp( ip, user, psw , port,""); // } catch (Exception e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } // System.out.print(new Date().getTime()+" ,编码:"+Charset.defaultCharset()); // try { // FileUtil.createFileAndWriteData(new File("d:/csvdata/3t.csv"),getTData(),getTitle()); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } checkFile(new File("E:\\20151015abc\\brand-CardEdenBaseInterface\\src\\1.txt")); String a="商户名称:,腾讯new,账单时间:,2017-11-14 00:00:00~2017-11-15 00:00:00,,,,,,\r\n"+ "成功总金额:,88897,,,,,,,,\r\n"+ "成功笔数:,38,失败笔数:,28,,,,,,\r\n"; try { FileUtil.writeData(new File("E:\\20151015abc\\brand-CardEdenBaseInterface\\src\\abc.txt"), a, false,"GBK"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { RandomAccessFile raf = new RandomAccessFile("E:\\20151015abc\\brand-CardEdenBaseInterface\\src\\对账单格式-2.csv", "rw"); raf.seek(0); raf.write(a.getBytes()); raf.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // try { // FileUtil.deleteFile("E:\\20151015abc\\brand-CardEdenBaseInterface\\src\\1.txt"); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // try { // FileUtil.appendData(new File("d:/1t.csv"),getTData()); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } } }
package com.docker.storage.mongodb; import java.util.Collection; import com.docker.data.DataObject; import com.docker.storage.DBException; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCursor; import com.mongodb.client.model.CountOptions; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; public interface DAO { public DAO init() throws DBException; public void add(DataObject dObj) throws DBException; public void addAll(Collection<DataObject> dObjs) throws DBException; public DeleteResult delete(Bson match) throws DBException; public <T extends DataObject> T findOne(Bson query, Class<T> clazz) throws DBException; public Iterable<Document> aggregate(Bson... ops) throws DBException; FindIterable<Document> query(Bson query, String... keys) throws DBException; UpdateResult updateOne(Bson match, Bson update, boolean upsert) throws DBException; UpdateResult updateMany(Bson match, Bson update, boolean upsert) throws DBException; DataObject findOne(Bson query) throws DBException; Document findAndUpdate(Bson query, Bson projection, Bson sort, Bson update, boolean returnNew, boolean upsert) throws DBException; Document findAndDelete(Bson query) throws DBException; Document findAndReplace(Bson query, Document replacement, boolean returnNew, boolean upsert) throws DBException; <TResult> FindIterable<TResult> query(Bson query, Class<TResult> resultClass) throws DBException; FindIterable<Document> query(Bson query) throws DBException; <TResult> MongoCursor<TResult> distinct(String fieldName, Bson query, Class<TResult> resultClass) throws DBException; long count(Bson query); UpdateResult replace(DataObject dObj) throws DBException; long count(Bson query, CountOptions options); }
public class Batman { public static void main(String[] args) { System.out.println("I will catch you"); // adding more stuff - yes he will catch him // batmans car is cool // michael and george were the best batman characters } }
package TesteSite; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; /** * * Classe teste. * Pode-se melhorar muito a codificação e utilizar padrões de programação, por conhecer pouco sobre a ferramenta selenium com java * tentei desenvolver um código legível e que pudesse atender ao teste, há algumas coisas que não estão funcionando por exemplo na hora de navegar * para o menu "consulta pública", havia testado anteriormente com um sistema meu, e tinha funcionado, não descobri o porque de não navegar. * Não sei se dá pra ter um parametro para avaliação com este código, acredito que talvez a lógica pode ser avaliada e a tentativa mesmo tento poucos * dias para aprender. * * @author André Duarte <andre.silva141@fatec.sp.gov.br> * @since 17 de mai de 2017 20:31:42 * @version 1.0 */ public class TestandoAplicacao{ @Test public void testando() throws InterruptedException { System.setProperty( "webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe" ); WebDriver driver = new ChromeDriver(); driver.get( "https://projudi.tjpr.jus.br/projudi_consulta/" ); //driver.findElement( By.linkText( "Consulta Pública " ) ).click(); //CAPTURANDO O CONTEÚDO DO CAMPO WebElement valorCampo = driver.findElement( By.tagName( "data-sitekey" ) ); //DEIXAR SOMENTE OS NÚMEROS String valorNumerico = somenteNumeros( valorCampo.getText() ); //CONVERTO STRING EM NÚMERICO Integer valorNumericoConvertido = Integer.parseInt( valorNumerico ); //INVOCO O MÉTODO QUE FARÁ O CALCULO DE FIBONACCI, ME RETORNANDO UM VALOR Integer resultado = Fibonacci.calcularFibonacci( valorNumericoConvertido ); //VOLTAR O RESULTADO PARA STRING String resultadoNumerico = resultado.toString(); //SETANDO NO TEXTAREA A RESPOSTA JavascriptExecutor jse = (JavascriptExecutor) driver; WebElement campoTexto = driver.findElement( By.id( "g-recaptcha-response" ) ); if ( jse instanceof WebDriver ) { jse.executeScript( "arguments[0].setAttribute('style', 'visibility:hidden')", campoTexto ); campoTexto.sendKeys( resultadoNumerico ); } driver.close(); } /** * * Método responsável por manter apenas valores númericos da string e retornar estes valores. * * @param str * @return * * @author André Duarte <andre.silva141@fatec.sp.gov.br> * @since 17 de mai de 2017 20:47:46 * @version 1.0 */ public static String somenteNumeros( String str ) { if ( str != null ) { return str.replaceAll( "[^0123456789]", "" ); } else { return ""; } } }
/* * Copyright (c) 2016. Osred Brockhoist <osred.brockhoist@hotmail.com>. All Rights Reserved. */ package com.flyingosred.app.perpetualcalendar.database.lunar; public class Lunar { private int mYear; private int mMonth; private int mDay; private int mDaysInMonth; private boolean mIsLeapMonth; public Lunar(int year, int month, int day, int daysInMonth, boolean isLeapMonth) { mYear = year; mMonth = month; mDay = day; mDaysInMonth = daysInMonth; mIsLeapMonth = isLeapMonth; } public int getYear() { return mYear; } public int getMonth() { return mMonth; } public int getDay() { return mDay; } public int getDaysInMonth() { return mDaysInMonth; } public boolean isLeapMonth() { return mIsLeapMonth; } }
package com.txstats.common.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * @author Vinod Kandula */ @SuppressWarnings("serial") @ResponseStatus(value = HttpStatus.NO_CONTENT) public class StaleTransactionException extends Exception { }
package ke.co.edgar.alc4; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions; public class MainActivity extends AppCompatActivity { Button aboutBtn, profileBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(R.string.app_name); aboutBtn = findViewById(R.id.button_about); profileBtn = findViewById(R.id.button_my_profile); ImageView logo = findViewById(R.id.alc_logo); Glide.with(this).load(this.getResources() .getIdentifier("alc_logo", "drawable", this.getPackageName())) .transition(new DrawableTransitionOptions().crossFade()) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(logo); aboutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentAbout = new Intent(MainActivity.this, AboutALCActivity.class); startActivity(intentAbout); } }); profileBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intentProfile); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement switch (id) { case R.id.action_settings: Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intentProfile); break; } return super.onOptionsItemSelected(item); } }
package com.elkadakh.others; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class AssetLoader { //UI Buttons public static Texture largePlay, smallPlay, largeSound, largeSoundCanceled, smallSound, smallSoundCanceled, largeRate, smallRate, howTo; public static Texture lvl1Btn, lvl2Btn, lvl3Btn, lvl4Btn, lvl5Btn, lvl6Btn, lvl7Btn, lvl8Btn, lvl9Btn, lvl10Btn; public static Texture largeBackDark, largeBackLight, smallBackDark, smallBackLight, XsmallBackDark, XsmallBackLight; public static Texture dif1Dark80, dif1Light80, dif1Dark200, dif1Light200, dif1Dark300, dif1Light300; public static Texture dif2Dark80, dif2Light80, dif2Dark200, dif2Light200, dif2Dark300, dif2Light300; public static Texture dif3Dark80, dif3Light80, dif3Dark200, dif3Light200, dif3Dark300, dif3Light300; public static Texture dif4Dark80, dif4Light80, dif4Dark200, dif4Light200, dif4Dark300, dif4Light300; //Logos public static Texture logo800, logo1119, logo2000, logo4000; //Logo's 'U' letter public static Texture uLet1_800, uLet2_800, uLet3_800, uLet4_800; public static Animation uLet800Animation; public static Texture uLet1_1119, uLet2_1119, uLet3_1119, uLet4_1119; public static Animation uLet1119Animation; public static Texture uLet1_2000, uLet2_2000, uLet3_2000, uLet4_2000; public static Animation uLet2000Animation; public static Texture uLet1_4000, uLet2_4000, uLet3_4000, uLet4_4000; public static Animation uLet4000Animation; //Fonts public static BitmapFont font1; public static BitmapFont subText; public static BitmapFont subTextSmall; //Objects public static Texture canon; public static Texture canonBall; public static Texture canonBallWhite; //Level's 1 arrows public static Texture up; public static Texture upGreen; public static Texture left; public static Texture leftGreen; //Sounds public static Sound beep; public static Music crash; public static Music nextLevel; public static Music propellorSpin; //Helicopter public static Texture heli1Gray, heli2Gray, heli3Gray, heli4Gray; public static Texture heli1Green, heli2Green, heli3Green, heli4Green; public static Animation heliGrayAnimation, heliGreenAnimation; //Backgrounds public static Texture bgDarkLarge, bgLightLarge, bgTopDarkLarge, bgTopLightLarge; public static Texture bgDarkSmall, bgLightSmall, bgTopDarkSmall, bgTopLightSmall; //Levels' textures public static Texture lvl1Texture; //Fence texture public static Texture fenceSmall, fenceBig; //Target (Landing point) public static Texture target; public static Texture targetDif1; public static TextureRegion targetTR; public static Texture targetSmall; public static Texture targetSmallDif1; public static TextureRegion targetTRSmall; public static TextureRegion targetTRSmallDif1; public static TextureRegion targetTRDif1; //Teleport public static Texture teleport1,teleport2,teleport3,teleport4,teleport5,teleport6,teleport7,teleport8,teleport9,teleport10; public static Animation teleportAnimation; //Lightening 161 public static Texture light161_1,light161_2,light161_3,light161_4; public static Animation light161Animation; //Lightening 141 public static Texture light141_1,light141_2,light141_3,light141_4; public static Animation light141Animation; //Levels public static Texture level1; public static Texture level2; public static Texture level3; public static Texture level4; public static Texture level5; public static Texture level6; public static Texture level7; public static Texture level8a; public static Texture level8b; public static Texture level9; public static Texture level10; //Star public static Texture star, starBordered; public static void load() { //UI Buttons largePlay = new Texture(Gdx.files.internal("UI Buttons/play/largePlay.png")); largeRate = new Texture(Gdx.files.internal("UI Buttons/rate/largeRate.png")); smallRate = new Texture(Gdx.files.internal("UI Buttons/rate/smallRate.png")); howTo = new Texture(Gdx.files.internal("UI Buttons/howto/howto.png")); largeSound = new Texture(Gdx.files.internal("UI Buttons/sound/largeSound.png")); largeSoundCanceled = new Texture(Gdx.files.internal("UI Buttons/sound/largeSoundCanceled.png")); smallPlay = new Texture(Gdx.files.internal("UI Buttons/play/smallPlay.png")); smallSound = new Texture(Gdx.files.internal("UI Buttons/sound/smallSound.png")); smallSoundCanceled = new Texture(Gdx.files.internal("UI Buttons/sound/smallSoundCanceled.png")); lvl1Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl1Button.png")); lvl2Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl2Button.png")); lvl3Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl3Button.png")); lvl4Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl4Button.png")); lvl5Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl5Button.png")); lvl6Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl6Button.png")); lvl7Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl7Button.png")); lvl8Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl8Button.png")); lvl9Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl9Button.png")); lvl10Btn = new Texture(Gdx.files.internal("UI Buttons/levels/lvl10Button.png")); largeBackDark = new Texture(Gdx.files.internal("UI Buttons/back/largeBackDark.png")); largeBackLight = new Texture(Gdx.files.internal("UI Buttons/back/largeBackLight.png")); smallBackDark = new Texture(Gdx.files.internal("UI Buttons/back/smallBackDark.png")); smallBackLight = new Texture(Gdx.files.internal("UI Buttons/back/smallBackLight.png")); XsmallBackDark = new Texture(Gdx.files.internal("UI Buttons/back/XsmallBackDark.png")); XsmallBackLight = new Texture(Gdx.files.internal("UI Buttons/back/XsmallBackLight.png")); dif1Dark80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif1/dark80.png")); dif1Light80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif1/light80.png")); dif1Dark200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif1/dark200.png")); dif1Light200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif1/light200.png")); dif1Dark300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif1/dark300.png")); dif1Light300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif1/light300.png")); dif2Dark80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif2/dark80.png")); dif2Light80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif2/light80.png")); dif2Dark200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif2/dark200.png")); dif2Light200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif2/light200.png")); dif2Dark300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif2/dark300.png")); dif2Light300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif2/light300.png")); dif3Dark80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif3/dark80.png")); dif3Light80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif3/light80.png")); dif3Dark200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif3/dark200.png")); dif3Light200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif3/light200.png")); dif3Dark300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif3/dark300.png")); dif3Light300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif3/light300.png")); dif4Dark80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif4/dark80.png")); dif4Light80 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif4/light80.png")); dif4Dark200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif4/dark200.png")); dif4Light200 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif4/light200.png")); dif4Dark300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif4/dark300.png")); dif4Light300 = new Texture(Gdx.files.internal("UI Buttons/DiffLvls/dif4/light300.png")); //Logo logo800 = new Texture(Gdx.files.internal("Others/logo800/logo800.png")); logo1119 = new Texture(Gdx.files.internal("Others/logo1119/logo1119.png")); logo2000 = new Texture(Gdx.files.internal("Others/logo2000/logo2000.png")); logo4000 = new Texture(Gdx.files.internal("Others/logo4000/logo4000.png")); //Logos 'U' letter uLet1_800 = new Texture(Gdx.files.internal("Others/logo800/uLetterAnimation/u1.png")); uLet2_800 = new Texture(Gdx.files.internal("Others/logo800/uLetterAnimation/u2.png")); uLet3_800 = new Texture(Gdx.files.internal("Others/logo800/uLetterAnimation/u3.png")); uLet4_800 = new Texture(Gdx.files.internal("Others/logo800/uLetterAnimation/u4.png")); TextureRegion[] uLet800 = {new TextureRegion(uLet1_800, 5, 14, 124, 94), new TextureRegion(uLet2_800, 5, 14, 124, 94), new TextureRegion(uLet3_800, 5, 14, 124, 94), new TextureRegion(uLet4_800, 5, 14, 124, 94) }; uLet800Animation = new Animation(0.035f, uLet800); uLet800Animation.setPlayMode(Animation.PlayMode.LOOP); uLet1_1119 = new Texture(Gdx.files.internal("Others/logo1119/uLetterAnimation/u1.png")); uLet2_1119 = new Texture(Gdx.files.internal("Others/logo1119/uLetterAnimation/u2.png")); uLet3_1119 = new Texture(Gdx.files.internal("Others/logo1119/uLetterAnimation/u3.png")); uLet4_1119 = new Texture(Gdx.files.internal("Others/logo1119/uLetterAnimation/u4.png")); TextureRegion[] uLet1119 = {new TextureRegion(uLet1_1119, 3, 3, 245, 187), new TextureRegion(uLet2_1119, 3, 3, 245, 187), new TextureRegion(uLet3_1119, 3, 3, 245, 187), new TextureRegion(uLet4_1119, 3, 3, 245, 187) }; uLet1119Animation = new Animation(0.035f, uLet1119); uLet1119Animation.setPlayMode(Animation.PlayMode.LOOP); uLet1_2000 = new Texture(Gdx.files.internal("Others/logo2000/uLetterAnimation/u1.png")); uLet2_2000 = new Texture(Gdx.files.internal("Others/logo2000/uLetterAnimation/u2.png")); uLet3_2000 = new Texture(Gdx.files.internal("Others/logo2000/uLetterAnimation/u3.png")); uLet4_2000 = new Texture(Gdx.files.internal("Others/logo2000/uLetterAnimation/u4.png")); TextureRegion[] uLet2000 = {new TextureRegion(uLet1_2000, 15, 7, 324, 285), new TextureRegion(uLet2_2000, 15, 7, 324, 285), new TextureRegion(uLet3_2000, 15, 7, 324, 285), new TextureRegion(uLet4_2000, 15, 7, 324, 285) }; uLet2000Animation = new Animation(0.035f, uLet2000); uLet2000Animation.setPlayMode(Animation.PlayMode.LOOP); uLet1_4000 = new Texture(Gdx.files.internal("Others/logo4000/uLetterAnimation/u1.png")); uLet2_4000 = new Texture(Gdx.files.internal("Others/logo4000/uLetterAnimation/u2.png")); uLet3_4000 = new Texture(Gdx.files.internal("Others/logo4000/uLetterAnimation/u3.png")); uLet4_4000 = new Texture(Gdx.files.internal("Others/logo4000/uLetterAnimation/u4.png")); TextureRegion[] uLet4000 = {new TextureRegion(uLet1_4000, 0, 100, 690, 590), new TextureRegion(uLet2_4000, 0, 100, 690, 590), new TextureRegion(uLet3_4000, 0, 100, 690, 590), new TextureRegion(uLet4_4000, 0, 100, 690, 590) }; uLet4000Animation = new Animation(0.035f, uLet4000); uLet4000Animation.setPlayMode(Animation.PlayMode.LOOP); //Fonts font1 = new BitmapFont(Gdx.files.internal("Fonts/text.fnt")); subText = new BitmapFont(Gdx.files.internal("Fonts/subText.fnt")); subTextSmall = new BitmapFont(Gdx.files.internal("Fonts/subTextSmall.fnt")); //Objects canonBall = new Texture(Gdx.files.internal("Objects/canonBall.png")); canonBallWhite = new Texture(Gdx.files.internal("Objects/canonBallWhite.png")); //Level's 1 arrows up = new Texture(Gdx.files.internal("lvls1Arrows/up.png")); upGreen = new Texture(Gdx.files.internal("lvls1Arrows/upGreen.png")); left = new Texture(Gdx.files.internal("lvls1Arrows/left.png")); leftGreen = new Texture(Gdx.files.internal("lvls1Arrows/leftGreen.png")); //Sounds beep = Gdx.audio.newSound(Gdx.files.internal("SFX/beep.mp3")); crash = Gdx.audio.newMusic(Gdx.files.internal("SFX/crash.mp3")); crash.setVolume((float) 0.5); nextLevel = Gdx.audio.newMusic(Gdx.files.internal("SFX/nextLevel.wav")); propellorSpin = Gdx.audio.newMusic(Gdx.files.internal("SFX/propellorSpin.wav")); crash.setLooping(false); //Helicopter textures and animation heli1Gray = new Texture(Gdx.files.internal("Helicopter/gray/heli1Gray.png")); heli2Gray = new Texture(Gdx.files.internal("Helicopter/gray/heli2Gray.png")); heli3Gray = new Texture(Gdx.files.internal("Helicopter/gray/heli3Gray.png")); heli4Gray = new Texture(Gdx.files.internal("Helicopter/gray/heli4Gray.png")); heli1Green = new Texture(Gdx.files.internal("Helicopter/green/heli1Green.png")); heli2Green = new Texture(Gdx.files.internal("Helicopter/green/heli2Green.png")); heli3Green = new Texture(Gdx.files.internal("Helicopter/green/heli3Green.png")); heli4Green = new Texture(Gdx.files.internal("Helicopter/green/heli4Green.png")); TextureRegion[] heliGrayImages = {new TextureRegion(heli1Gray, 0, 0, 74, 34), new TextureRegion(heli2Gray, 0, 0, 74, 34), new TextureRegion(heli3Gray, 0, 0, 74, 34), new TextureRegion(heli4Gray, 0, 0, 74, 34) }; TextureRegion[] heliGreenImages = {new TextureRegion(heli1Green, 0, 0, 74, 34), new TextureRegion(heli2Green, 0, 0, 74, 34), new TextureRegion(heli3Green, 0, 0, 74, 34), new TextureRegion(heli4Green, 0, 0, 74, 34) }; heliGrayAnimation = new Animation(0.035f, heliGrayImages); heliGreenAnimation = new Animation(0.035f, heliGreenImages); heliGrayAnimation.setPlayMode(Animation.PlayMode.LOOP); heliGreenAnimation.setPlayMode(Animation.PlayMode.LOOP); //Backgrounds textures bgDarkLarge = new Texture(Gdx.files.internal("Backgrounds/Big screens/bgDarkLarge.png")); bgLightLarge = new Texture(Gdx.files.internal("Backgrounds/Big screens/bgLightLarge.png")); bgTopDarkLarge = new Texture(Gdx.files.internal("Backgrounds/Big screens/bgTopDarkLarge.png")); bgTopLightLarge = new Texture(Gdx.files.internal("Backgrounds/Big screens/bgTopLightLarge.png")); bgDarkSmall = new Texture(Gdx.files.internal("Backgrounds/Small screens/bgDarkSmall.png")); bgLightSmall = new Texture(Gdx.files.internal("Backgrounds/Small screens/bgLightSmall.png")); bgTopDarkSmall = new Texture(Gdx.files.internal("Backgrounds/Small screens/bgTopDarkSmall.png")); bgTopLightSmall = new Texture(Gdx.files.internal("Backgrounds/Small screens/bgTopLightSmall.png")); //Fence texture fenceSmall = new Texture(Gdx.files.internal("Levels/fenceSmall.png")); fenceBig = new Texture(Gdx.files.internal("Levels/fenceBig.png")); //Target (Landing point) target = new Texture(Gdx.files.internal("Others/target.png")); targetTR = new TextureRegion(target, 0, 0, 35, 35); //For rotation targetSmall = new Texture(Gdx.files.internal("Others/targetSmall.png")); targetTRSmall = new TextureRegion(targetSmall, 0, 0, 28, 28); //For rotation targetDif1 = new Texture(Gdx.files.internal("Others/targetDif1.png")); targetTRDif1 = new TextureRegion(targetDif1, 0, 0, 35, 35); //For rotation targetSmallDif1 = new Texture(Gdx.files.internal("Others/targetSmallDif1.png")); targetTRSmallDif1 = new TextureRegion(targetSmallDif1, 0, 0, 28, 28); //For rotation //Teleport (animated) teleport1 = new Texture(Gdx.files.internal("Others/teleport/frame_000.gif")); teleport2 = new Texture(Gdx.files.internal("Others/teleport/frame_001.gif")); teleport3 = new Texture(Gdx.files.internal("Others/teleport/frame_002.gif")); teleport4 = new Texture(Gdx.files.internal("Others/teleport/frame_003.gif")); teleport5 = new Texture(Gdx.files.internal("Others/teleport/frame_004.gif")); teleport6 = new Texture(Gdx.files.internal("Others/teleport/frame_005.gif")); teleport7 = new Texture(Gdx.files.internal("Others/teleport/frame_006.gif")); teleport8 = new Texture(Gdx.files.internal("Others/teleport/frame_007.gif")); teleport9 = new Texture(Gdx.files.internal("Others/teleport/frame_008.gif")); teleport10 = new Texture(Gdx.files.internal("Others/teleport/frame_008.gif")); TextureRegion[] teleportImages = { new TextureRegion(teleport1, 5, 4, 195, 195), new TextureRegion(teleport3, 5, 4, 195, 195), new TextureRegion(teleport4, 5, 4, 195, 195), new TextureRegion(teleport5, 5, 4, 195, 195), new TextureRegion(teleport6, 5, 4, 195, 195), new TextureRegion(teleport7, 5, 4, 195, 195), new TextureRegion(teleport8, 5, 4, 195, 195), new TextureRegion(teleport9, 5, 4, 195, 195), new TextureRegion(teleport10, 5, 4, 195, 195), }; teleportAnimation = new Animation(0.03f, teleportImages); teleportAnimation.setPlayMode(Animation.PlayMode.LOOP); //light161 (animated) light161_1 = new Texture(Gdx.files.internal("Objects/161h/1.png")); light161_2 = new Texture(Gdx.files.internal("Objects/161h/2.png")); light161_3 = new Texture(Gdx.files.internal("Objects/161h/3.png")); light161_4 = new Texture(Gdx.files.internal("Objects/161h/4.png")); TextureRegion[] light161Images = { new TextureRegion(light161_1, 0, 0, 5, 161), new TextureRegion(light161_2, 0, 0, 5, 161), new TextureRegion(light161_3, 0, 0, 5, 161), new TextureRegion(light161_4, 0, 0, 5, 161), }; light161Animation = new Animation(0.05f, light161Images); light161Animation.setPlayMode(Animation.PlayMode.LOOP); //light141 (animated) light141_1 = new Texture(Gdx.files.internal("Objects/141h/1.png")); light141_2 = new Texture(Gdx.files.internal("Objects/141h/2.png")); light141_3 = new Texture(Gdx.files.internal("Objects/141h/3.png")); light141_4 = new Texture(Gdx.files.internal("Objects/141h/4.png")); TextureRegion[] light141Images = { new TextureRegion(light161_1, 0, 0, 5, 141), new TextureRegion(light161_2, 0, 0, 5, 141), new TextureRegion(light161_3, 0, 0, 5, 141), new TextureRegion(light161_4, 0, 0, 5, 141), }; light141Animation = new Animation(0.05f, light141Images); light141Animation.setPlayMode(Animation.PlayMode.LOOP); //Levels level1 = new Texture(Gdx.files.internal("Levels/level1.png")); level2 = new Texture(Gdx.files.internal("Levels/level2.png")); level3 = new Texture(Gdx.files.internal("Levels/level3.png")); level4 = new Texture(Gdx.files.internal("Levels/level4.png")); level5 = new Texture(Gdx.files.internal("Levels/level5.png")); level6 = new Texture(Gdx.files.internal("Levels/level6.png")); level7 = new Texture(Gdx.files.internal("Levels/level7.png")); level8a = new Texture(Gdx.files.internal("Levels/level8a.png")); level8b = new Texture(Gdx.files.internal("Levels/level8b.png")); level9 = new Texture(Gdx.files.internal("Levels/level9.png")); level10 = new Texture(Gdx.files.internal("Levels/level10.png")); //star star = new Texture(Gdx.files.internal("Others/starForLvls.png")); starBordered = new Texture(Gdx.files.internal("Others/starForLvlsBordered.png")); } public static void dispose() { //Must dispose of the texture when game is finished largePlay.dispose(); smallPlay.dispose(); largeSound.dispose(); largeSoundCanceled.dispose(); smallSound.dispose(); smallSoundCanceled.dispose(); largeRate.dispose(); smallRate.dispose(); lvl1Btn.dispose(); lvl2Btn.dispose(); lvl3Btn.dispose(); lvl4Btn.dispose(); lvl5Btn.dispose(); lvl6Btn.dispose(); lvl7Btn.dispose(); lvl8Btn.dispose(); lvl9Btn.dispose(); largeBackDark.dispose(); largeBackLight.dispose(); smallBackDark.dispose(); smallBackLight.dispose(); XsmallBackDark.dispose(); XsmallBackLight.dispose(); logo800.dispose(); logo1119.dispose(); logo2000.dispose(); uLet1_800.dispose(); uLet2_800.dispose(); uLet3_800.dispose(); uLet4_800.dispose(); uLet1_1119.dispose(); uLet2_1119.dispose(); uLet3_1119.dispose(); uLet4_1119.dispose(); uLet1_2000.dispose(); uLet2_2000.dispose(); uLet3_2000.dispose(); uLet4_2000.dispose(); uLet1_4000.dispose(); uLet2_4000.dispose(); uLet3_4000.dispose(); uLet4_4000.dispose(); font1.dispose(); subText.dispose(); subTextSmall.dispose(); canon.dispose(); canonBall.dispose(); up.dispose(); upGreen.dispose(); left.dispose(); leftGreen.dispose(); beep.dispose(); crash.dispose(); nextLevel.dispose(); propellorSpin.dispose(); heli1Gray.dispose(); heli2Gray.dispose(); heli3Gray.dispose(); heli4Gray.dispose(); heli1Green.dispose(); heli2Green.dispose(); heli3Green.dispose(); heli4Green.dispose(); bgLightLarge.dispose(); bgTopLightLarge.dispose(); bgLightSmall.dispose(); bgTopLightSmall.dispose(); lvl1Texture.dispose(); fenceSmall.dispose(); fenceBig.dispose(); target.dispose(); targetSmall.dispose(); teleport1.dispose(); teleport2.dispose(); teleport3.dispose(); teleport4.dispose(); teleport5.dispose(); teleport6.dispose(); teleport7.dispose(); teleport8.dispose(); teleport9.dispose(); teleport10.dispose(); light161_1.dispose(); light161_2.dispose(); light161_3.dispose(); light161_4.dispose(); light141_1.dispose(); light141_2.dispose(); light141_3.dispose(); light141_4.dispose(); level1.dispose(); level2.dispose(); level3.dispose(); level4.dispose(); level5.dispose(); level6.dispose(); level7.dispose(); level8a.dispose(); level8b.dispose(); level9.dispose(); } }
package net.gupt.ebuy.service; import net.gupt.ebuy.dao.RegistDao; import net.gupt.ebuy.dao.RegistDaoImpl; import net.gupt.ebuy.pojo.Customer; /** * 用户注册模块业务接口实现类 * @author glf * */ public class RegistServiceImpl implements RegistService{ private RegistDao registDaoImpl = new RegistDaoImpl(); public boolean submitReg(Customer customer) { boolean flag = registDaoImpl.submitReg(customer); return flag; } public Customer validName(String name) { Customer customer = registDaoImpl.findByName(name); return customer; } }
package com.lesports.albatross.adapter.compertition; import android.content.Context; import android.view.View; import android.widget.TextView; import com.lesports.albatross.R; import com.lesports.albatross.adapter.BaseListAdapter; /** * 直播流,使用gridview * Created by zhouchenbin on 16/6/27. */ @Deprecated public class LiveStreamAdapter<LiveStream> extends BaseListAdapter { private LiveStreamAdapter(Context context) { super(context); } ViewHolder viewHolder; @Override protected View getItemView(View view, int position) { if (view == null) { viewHolder = new ViewHolder(); view = inflater.inflate(R.layout.live_stream_item, null); viewHolder.textView = (TextView) view.findViewById(R.id.live_streams_name); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } // final LiveStream liveStream = (LiveStream) mValues.get(position); //// viewHolder.textView.setText(liveStream); // if (position == 0) { // viewHolder.textView.setBackgroundDrawable(getResources().getDrawable(R.drawable.comp_detail_record_pre)); // // } return view; } private class ViewHolder { private TextView textView; } }
package com.logzc.webzic.orm.jdbc; import com.logzc.webzic.orm.db.DbConnection; import com.logzc.webzic.orm.db.DbResults; import com.logzc.webzic.orm.support.ConnectionSource; import com.logzc.webzic.orm.util.OrmUtils; import java.io.IOException; import java.sql.*; /** * Created by lishuang on 2016/8/23. */ public class JdbcDbConnection implements DbConnection { private Connection connection; private ConnectionSource connectionSource; public JdbcDbConnection(Connection connection,ConnectionSource connectionSource) { this.connection = connection; this.connectionSource=connectionSource; } @Override public int insert(String statement, Object... args) throws SQLException { return execute(statement,args); } @Override public int delete(String statement, Object... args) throws SQLException { return execute(statement,args); } @Override public int update(String statement, Object... args) throws SQLException { return execute(statement,args); } public int execute(String statement, Object... args) throws SQLException{ try(PreparedStatement stmt = this.connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { setStatementArgs(stmt, args); //print the sql. printSql(stmt,statement,args); return stmt.executeUpdate(); } } @Override public DbResults query(String statement, Object... args) throws SQLException { PreparedStatement stmt = this.connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); setStatementArgs(stmt, args); printSql(stmt,statement,args); ResultSet resultSet = stmt.executeQuery(); return new DbResults(stmt, resultSet); } private void printSql(PreparedStatement stmt,String statement,Object[] args){ //print the sql. System.out.println(stmt); System.out.println(statement); System.out.print("Args:"); for (Object obj:args){ System.out.print(" "+obj); } System.out.println(); } private void setStatementArgs(PreparedStatement stmt, Object... args) throws SQLException { if (args == null) { return; } for (int i = 0; i < args.length; i++) { Object arg = args[i]; Object sqlArg=connectionSource.getDialect().getSqlObject(arg); int sqlType=connectionSource.getDialect().getSqlType(arg); if (arg == null) { stmt.setNull(i + 1, Types.NULL); } else { stmt.setObject(i + 1, sqlArg, sqlType); } } } @Override public void close() throws IOException { try { if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { throw new IOException("could not close SQL connection."); } } }
/* * Lesson 29 Coding Activity 1 * A student wants an algorithm to find the hardest spelling * word in a list of vocabulary. They define hardest by the longest word. * Write the code to find the longest word stored in an array of Strings called list. * If several words have the same length it should print the first word * in list with the longest length. * For example, if the following list were declared: * * String list [] = {"high", "every", "nearing", "checking", "food ", * "stand", "value", "best", "energy", "add", "grand", "notation", * "abducted", "food ", "stand"}; * * It would print: * checking */ class Lesson_29_Activity_One { /* * Fill this list with values that will be useful for you to test. A good idea * may be to copy/paste the list in the example above. Do not make any changes * to this list in your main method. You can print values from list, but do not * add or remove values to this variable. */ public static String[] list = { "high", "every", "nearing", "checking", "food ", "stand", "value", "best", "energy", "add", "grand", "notation", "abducted", "food ", "stand" }; public static void main(String[] args) { String word = ""; for (String listWord : list) { word = listWord.length() > word.length() ? listWord : word; } System.out.println(word); } }
package java2plant; import java.io.File; import java2plant.control.Controller; import java2plant.control.ToCtrl; import java2plant.model.ClassList; /** * * @author arthur */ public class Java2Plant { // TODO: clean up private static File fInputDir; private static File fOutputDir; /** * @param args * the command line arguments */ public static void main(String[] args) { if (args.length < 2) { return; } fInputDir = new File(args[0]); fOutputDir = new File(args[1]); ToCtrl ctrl = Controller.getInstance(); ctrl.setInputFile(fInputDir); ctrl.setOutputFile(fOutputDir); ctrl.parseJava(); ctrl.writePlant(ClassList.getInstance()); } }
package com.example.photoshare; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { Button signInButton, goToSignUpButton; TextView signInEmail, signInPassword; FirebaseAuth mFirebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mFirebaseAuth = FirebaseAuth.getInstance(); signInButton = findViewById(R.id.signInButton); goToSignUpButton = findViewById(R.id.goToSignUpButton); signInEmail = findViewById(R.id.signInEmail); signInPassword = findViewById(R.id.signInPassword); goToSignUpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SignUpActivity.class); startActivity(intent); } }); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = signInEmail.getText().toString(); String password = signInPassword.getText().toString(); if(email.isEmpty() || password.isEmpty()) { signInEmail.setError("Please enter all fields!"); signInEmail.requestFocus(); return; } if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { signInEmail.setError("Please enter a valid email!"); signInEmail.requestFocus(); return; } mFirebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()) { Intent intent = new Intent(MainActivity.this, Home.class); startActivity(intent); finish(); } else { Toast.makeText(MainActivity.this, "Error signing in", Toast.LENGTH_LONG).show(); } } }); } }); } }
import org.apache.axis.AxisFault; import javax.xml.rpc.ServiceException; import java.net.MalformedURLException; public interface UserCheckService { boolean CheckIfRealPerson(User user) throws AxisFault, MalformedURLException, ServiceException; }
/** * * @author Iago Nogueira <iagonogueira227@gmail.com> */ public class No { private No next; private int item; public No ( int item ) { this.item = item; } public No ( int item, No next ) { this.item = item; this.next = next; } public No getNext() { return next; } public void setNext(No next) { this.next = next; } public int getItem() { return item; } public void setItem(int item) { this.item = item; } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.bvt.sql.oracle.createTable; import com.alibaba.druid.sql.OracleTest; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleSchemaStatVisitor; import java.util.List; public class OracleCreateTableTest96 extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE TABLE \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\" \n" + " ( \"IAU_ID\" NUMBER, \n" + " \"IAU_AUTHENTICATIONMETHOD\" VARCHAR2(255), \n" + " PRIMARY KEY (\"IAU_ID\")\n" + " USING INDEX (CREATE INDEX \"CAOBOHAHA_IAU\".\"DYN_IAU_USERSESSION_INDEX\" ON \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\" (\"IAU_ID\") \n" + " PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS \n" + " TABLESPACE \"CAOBOHAHA_IAU\" ) ENABLE\n" + " ) SEGMENT CREATION DEFERRED \n" + " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" + " NOCOMPRESS LOGGING\n" + " TABLESPACE \"CAOBOHAHA_IAU\" "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals("CREATE TABLE \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\" (\n" + "\t\"IAU_ID\" NUMBER,\n" + "\t\"IAU_AUTHENTICATIONMETHOD\" VARCHAR2(255),\n" + "\tPRIMARY KEY (\"IAU_ID\")\n" + "\t\tUSING INDEX (CREATE INDEX \"CAOBOHAHA_IAU\".\"DYN_IAU_USERSESSION_INDEX\" ON \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\"(\"IAU_ID\")\n" + "\t\tCOMPUTE STATISTICS\n" + "\t\tPCTFREE 10\n" + "\t\tINITRANS 2\n" + "\t\tMAXTRANS 255\n" + "\t\tTABLESPACE \"CAOBOHAHA_IAU\")\n" + "\t\tENABLE\n" + ")\n" + "PCTFREE 10\n" + "PCTUSED 40\n" + "INITRANS 1\n" + "MAXTRANS 255\n" + "NOCOMPRESS\n" + "LOGGING\n" + "TABLESPACE \"CAOBOHAHA_IAU\"", stmt.toString()); } }
/** * <copyright> * </copyright> * * */ package ssl.resource.ssl.grammar; public class SslContainment extends ssl.resource.ssl.grammar.SslTerminal { public SslContainment(org.eclipse.emf.ecore.EStructuralFeature feature, ssl.resource.ssl.grammar.SslCardinality cardinality, int mandatoryOccurencesAfter) { super(feature, cardinality, mandatoryOccurencesAfter); } public String toString() { return getFeature().getName(); } }
package com.ws; import java.util.Scanner; /** * @author shuo.wang * @date 19-9-27 */ public class ProcessDemo { public static void main(String[] args) throws Exception{ Thread.sleep(20000); ProcessBuilder pb = new ProcessBuilder("java", "-cp /home/shuowang/IdeaProject/study-demo/jdk-demo/src/main/java","com.ws.ProcessDemo2"); Process process = pb.start(); Scanner scanner = new Scanner(process.getInputStream()); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } Thread.sleep(20000); scanner.close(); } }
package org.usfirst.frc.team548.robot; import com.ctre.CANTalon; import com.ctre.CANTalon.FeedbackDevice; import com.ctre.CANTalon.TalonControlMode; public class Shooter { private static Shooter instance; public static Shooter getInstance() { if(instance == null) instance = new Shooter(); return instance; } private static CANTalon talonLeft, talonRight, elvevator; private Shooter() { talonLeft = new CANTalon(Constants.SHOOT_TALONID_TALONLEFT); //Encoder talonRight = new CANTalon(Constants.SHOOT_TALONID_TALONRIGHT); talonLeft.setFeedbackDevice(FeedbackDevice.CtreMagEncoder_Relative); talonLeft.setPID(Constants.SHOOT_PID_P, Constants.SHOOT_PID_I, Constants.SHOOT_PID_D, Constants.SHOOT_PID_F, Constants.SHOOT_PID_IZONE, 0, 0); talonRight.changeControlMode(TalonControlMode.Follower); //talonRight.reverseSensor(true); talonRight.set(talonLeft.getDeviceID()); elvevator = new CANTalon(Constants.SHOOT_TALONID_TALONELEVATOR); //talonRight.enableBrakeMode(false); //talonLeft.enableBrakeMode(false); } public static void setShooterPower(double p) { talonLeft.changeControlMode(TalonControlMode.PercentVbus); talonLeft.set(p); //talonRight.set(p); } public static void setElevator(double p) { elvevator.set(p); } public static void setShooterSpeed(double speed) { talonLeft.changeControlMode(TalonControlMode.Speed); talonLeft.set(speed); } public static void stop() { setShooterPower(0); } public static double getSpeed() { return talonLeft.getSpeed(); } public static void injectAfterSpeed(double speed) { setShooterSpeed(speed); if(getSpeed() > speed-45) setElevator(.4); } public static void addF(double a){ talonLeft.setF(Constants.SHOOT_PID_F+a); } }
package bychkov.sergey.audiobookplayer; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import net.rdrei.android.dirchooser.DirectoryChooserActivity; import net.rdrei.android.dirchooser.DirectoryChooserConfig; import java.io.File; import java.util.List; public class MainActivity extends AppCompatActivity implements AppReceiver.Receiver { private static final String LOG_TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_DIRECTORY = 0; Button bPlay; Button bStop; Button bFolderChooser; ListView filesListView; TextView tFolderName; TextView tFileName; FileListAdapter adapter; private File folder; private File selectedFile; private AppReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mReceiver = new AppReceiver(new Handler()); mReceiver.setReceiver(this); // setContentView(R.layout.activity_main); bPlay = (Button) findViewById(R.id.bPlay); bStop = (Button) findViewById(R.id.bStop); bFolderChooser = (Button) findViewById(R.id.bOpenFolder); tFolderName = (TextView) findViewById(R.id.folderName); tFileName = (TextView) findViewById(R.id.fileName); filesListView = (ListView) findViewById(R.id.fileList); // bFolderChooser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bFolderChooserClick(); } }); bPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { play(); } }); bStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stop(); } }); adapter = new FileListAdapter(this); filesListView.setAdapter(adapter); filesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectedFile = (File) adapter.getItem(position); } }); filesListView.setSelector(R.color.bright_blue); filesListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } /** * Dispatch onResume() to fragments. Note that for better inter-operation * with older versions of the platform, at the point of this call the * fragments attached to the activity are <em>not</em> resumed. This means * that in some cases the previous state may still be saved, not allowing * fragment transactions that modify the state. To correctly interact * with fragments in their proper state, you should instead override * {@link #onResumeFragments()}. */ @Override protected void onResume() { super.onResume(); // setReceiver(this); } /** * Dispatch onPause() to fragments. */ @Override protected void onPause() { super.onPause(); //setReceiver(null); } private void stop() { ControllerService.startActionStop(this); } private void play() { String folderName = folder != null ? folder.getAbsolutePath() : null; String fileName = selectedFile != null ? selectedFile.getAbsolutePath() : null; ControllerService.startActionPlay(this, folderName, fileName); } private void bFolderChooserClick() { final Intent chooserIntent = new Intent(this, DirectoryChooserActivity.class); final DirectoryChooserConfig config = DirectoryChooserConfig.builder() .newDirectoryName("DirChooserSample") .allowReadOnlyDirectory(true) .initialDirectory("/sdcard") .allowNewDirectoryNameModification(true) .build(); chooserIntent.putExtra(DirectoryChooserActivity.EXTRA_CONFIG, config); // REQUEST_DIRECTORY is a constant integer to identify the request, e.g. 0 startActivityForResult(chooserIntent, REQUEST_DIRECTORY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_DIRECTORY) { if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) { handleFolderSelected(data .getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR)); } else { // Nothing selected } } } private void handleFolderSelected(String stringExtra) { tFolderName.setText(stringExtra); folder = new File(stringExtra); ControllerService.startActionSetFolder(this,stringExtra); ControllerService.startActionGetFileList(this,mReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onReceiveResult(int resultCode, Bundle resultData) { switch (resultCode) { case ControllerService.STATUS_ERROR: String errMessage = resultData.getString(ControllerService.ERROR); Log.e(LOG_TAG, errMessage); Toast.makeText(this, errMessage, Toast.LENGTH_LONG).show(); break; case ControllerService.STATUS_OK: Log.d(LOG_TAG, resultData.getString(ControllerService.ACTION)); break; case ControllerService.RESULT_FILE_LIST: Log.d(LOG_TAG, "FileList received"); adapter.setData((List<File>) resultData.getSerializable(ControllerService.FILE_LIST)); break; case ControllerService.RESULT_CURRENT_FILE: Log.d(LOG_TAG, "Current file "); } } }
package pl.edu.pw.mini.taio.omino.app.utils; public class ColorConverter { public static javafx.scene.paint.Color awtToFx(java.awt.Color color) { return javafx.scene.paint.Color.rgb(color.getRed(), color.getGreen(), color.getBlue()); } public static java.awt.Color fxToAwt(javafx.scene.paint.Color color) { return new java.awt.Color((float)color.getRed(), (float)color.getGreen(), (float)color.getBlue()); } }
package com.union.express.web.employee.jpa.dao; import com.union.express.web.employee.model.Employee; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import java.util.List; /** * @author linaz * @created 2016.08.08 13:54 */ public interface IEmployeeRepository extends PagingAndSortingRepository<Employee, String> { Employee findByEmployeeName(@Param("employeeName") String userName); Employee findByPhone(@Param(("phone"))int phone); List<Employee> findByEmployeeNameAndPassword(@Param("employeeName") String userName, @Param("password") String password); }
/* Given an initial array nums = [4,5,8,2] and an integer k, each time I call add(int val) method, it should return the current kth largest number including this newly added integer val. For example: Input = [4,5,8,2], k = 3 k.add(3) // return 4 because 4 is the 3rd largest in [4,5,8,2,3] k.add(5) // return 5 because 5 is the 3rd largest in [4,5,8,2,3,5] */ class KthLargest { private Queue<Integer> queue = new PriorityQueue<>(); private final int LIMIT; public KthLargest(int k, int[] nums) { LIMIT = k; for(int number : nums){ add(number); } } public int add(int val) { queue.offer(val); if(queue.size() > LIMIT){ queue.poll(); } return queue.peek(); } } /** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */
package com.regnant.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class GetDBConnection { public static Connection getDBConnection() { Connection connection=null; try { Class.forName("com.mysql.jdbc.Driver"); connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","Admin@123"); } catch (ClassNotFoundException e) { System.out.println("where is your MySQL JDBC Driver"); e.printStackTrace(); return null; }catch(SQLException e) { System.out.println("Connection Failed check output console"); e.printStackTrace(); return null; } return connection; } }
package com.sailaminoak.saiii; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.fragment.app.FragmentTransaction; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.io.ByteArrayOutputStream; import java.text.SimpleDateFormat; import java.util.Calendar; import cc.cloudist.acplibrary.ACProgressConstant; import cc.cloudist.acplibrary.ACProgressFlower; import android.provider.Settings.Secure; public class Read extends AppCompatActivity { LinearLayout linearLayout; SharedPreferences sharedPreferences; boolean deleteTablesAfter=true; SQLHelper sqlHelper; String realFilename=""; boolean first=true; int h=90; int helperForTime=88; String deviceName="Unknown Device "; String byWho="Unknown Author"; String dateToDisplay="Unknown Date"; @Override protected void onCreate(Bundle savedInstanceState) { ActionBar actionBar=getSupportActionBar(); actionBar.hide(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_read); linearLayout=findViewById(R.id.linearLayout); final String newString; if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras == null) { newString = null; } else { newString = extras.getString("t"); } } else { newString = (String) savedInstanceState.getSerializable("t"); } sharedPreferences =getSharedPreferences("Saii",MODE_PRIVATE); //Toast.makeText(this,newString,Toast.LENGTH_LONG).show(); final ACProgressFlower dialog = new ACProgressFlower.Builder(Read.this) .direction(ACProgressConstant.DIRECT_CLOCKWISE) .themeColor(Color.GREEN) .text("Connecting To Server...") .fadeColor(Color.DKGRAY).build(); dialog.show(); try { long currentTime = Calendar.getInstance().getTimeInMillis(); sqlHelper=new SQLHelper(Read.this,"db.sqlite",null,2); realFilename="Tables"+currentTime; try{ boolean a=sqlHelper.queryData("CREATE TABLE " + realFilename + "( name TEXT ,image BLOB, ids INTEGER )"); }catch (Exception e){ Toast.makeText(Read.this,e+" error ",Toast.LENGTH_SHORT).show(); } byte[] b612 = new byte[0]; String android_id = Secure.getString(Read.this.getContentResolver(), Secure.ANDROID_ID); Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a"); String formattedDate = df.format(c.getTime()); sqlHelper.insertData("asdfjkl;yokelaminoak,,,"+"???"+",,,"+"???"+",,,"+"???",b612,9999,realFilename); DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child(newString); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (snapshot.exists()) { for (DataSnapshot dataSnapshot : snapshot.getChildren()) { TextView textView = new TextView(Read.this); final String a = dataSnapshot.child("text").getValue().toString(); if (a.length() == 0) continue; try{ if(a.contains("asdfjkl;yokelaminoak")){ String[] importantData=a.split(",,,"); byWho=importantData[1]; dateToDisplay=importantData[2]; deviceName=importantData[3]; }}catch (Exception e){ Toast.makeText(Read.this,"Can't reveive full write information",Toast.LENGTH_SHORT).show(); } if(a.length()==0)continue; if(a.contentEquals(" "))continue; if (a.contains("asdfjkl;yokelaminoak")) continue; if(a.contentEquals("image gonna be")){ ImageView imageView=new ImageView(Read.this); imageView.setImageResource(R.drawable.rose); LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(30,15,30,15); imageView.setLayoutParams(layoutParams); imageView.setAdjustViewBounds(true); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); linearLayout.addView(imageView); final int idForImage=helperForTime; ++helperForTime; boolean v=sqlHelper.insertData("",imageToByte(imageView),idForImage,realFilename); } else{ byte[] b = new byte[0]; if(sqlHelper.insertData(a,b,h,realFilename)){ }else{ Toast.makeText(Read.this,"Error occur when inserting EDIT TEXT",Toast.LENGTH_LONG).show(); } h++; textView.setText(a); textView.setTextSize(18); textView.setTextColor(getResources().getColor(R.color.black)); linearLayout.addView(textView); } } } else { TextView textView = new TextView(Read.this); textView.setText(" No Such File Exists......"); textView.setTextColor(Color.RED); textView.setTextSize(30); textView.getResources().getDrawable(R.color.tran); linearLayout.addView(textView); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); }catch (Exception e){ TextView textView = new TextView(Read.this); textView.setText("Cannot connect to server. Try Again!"); textView.setTextColor(Color.RED); textView.setTextSize(30); textView.getResources().getDrawable(R.color.tran); linearLayout.addView(textView); } Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { dialog.dismiss(); } }, 500); BottomNavigationView bottomNavigationView=findViewById(R.id.navigation_view); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_add: Toast.makeText(Read.this,"Stored in Database",Toast.LENGTH_SHORT).show(); deleteTablesAfter=false; break; case R.id.navigation_image: SharedPreferences.Editor editor=sharedPreferences.edit(); String temp=sharedPreferences.getString("ids",","); Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a"); String formattedDate = df.format(c.getTime()); temp= newString+" "+formattedDate+","+temp; editor.putString("ids",temp); editor.apply(); Toast.makeText(Read.this, "Remembered...Assume:3 ", Toast.LENGTH_SHORT).show(); break; case R.id.navigation_done: if(byWho.contentEquals("asdfjkl;yokelaminoak")) byWho="Unknown (May Detected Later)"; AlertDialog.Builder builder=new AlertDialog.Builder(Read.this); builder.setTitle("Writer Information"); builder.setMessage("Device ID : "+byWho+"\n"+"Date : "+dateToDisplay+"\n"+"Device Name : "+deviceName); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.show(); break; } return true; } }); } @Override public void onBackPressed() { super.onBackPressed(); if(deleteTablesAfter){ try{ sqlHelper.queryData("drop table "+realFilename); }catch (Exception e){ Toast.makeText(Read.this,"dropping table error",Toast.LENGTH_SHORT).show(); } }else{ SharedPreferences.Editor editor=sharedPreferences.edit(); String a=sharedPreferences.getString("ggg",","); if(a.contains(realFilename)){ }else{ String collle=realFilename+","+sharedPreferences.getString("ggg",","); editor.putString("ggg",collle); editor.apply(); } } finish(); Intent intent=new Intent(Read.this,MainActivity.class); startActivity(intent); } public byte[] imageToByte(ImageView image){ Bitmap bitmap= ((BitmapDrawable)image.getDrawable()).getBitmap(); ByteArrayOutputStream stream=new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream); return stream.toByteArray(); } }
/** * @Author: Asher Huang * @Date: 2019-10-06 * @Description: PACKAGE_NAME * @Version:1.0 */ public class ThreadTest { public static void main(String[] args) { System.out.println("main线程1在运行"); MyThread myThread = new MyThread(); //启动线程,启动的方法是调用start()方法,而不是去调用run()方法 // 线程只能启动1次,如果再次执行myThread.start()将会抛出运行时异常 myThread.start(); // myThread.start(); System.out.println("main线程2在运行"); } } class MyThread extends Thread{ public void run(){ System.out.println(getId()+" "+ getName()+"当前线程正在运行"); } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * 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 org.neuro4j.studio.core.views.dialogs; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.resources.IResourceProxyVisitor; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.ListenerList; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ResourceWorkingSetFilter; import org.eclipse.ui.WorkbenchException; import org.eclipse.ui.XMLMemento; import org.eclipse.ui.actions.WorkingSetFilterActionGroup; import org.eclipse.ui.dialogs.SearchPattern; import org.eclipse.ui.ide.ResourceUtil; import org.eclipse.ui.internal.WorkbenchMessages; import org.eclipse.ui.internal.WorkbenchPlugin; import org.eclipse.ui.internal.ide.IDEWorkbenchMessages; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.ide.IIDEHelpContextIds; import org.eclipse.ui.internal.ide.model.ResourceFactory; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.ui.statushandlers.StatusManager; import org.neuro4j.studio.core.util.ClassloaderHelper; import org.neuro4j.studio.core.util.ListEntry; import org.neuro4j.studio.core.util.FlowFromJarsLoader; public class FlowResourcesSelectionDialog extends FilteredItemsSelectionDialog { private static final String DIALOG_SETTINGS = "org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog"; //$NON-NLS-1$ private static final String WORKINGS_SET_SETTINGS = "WorkingSet"; //$NON-NLS-1$ private static final String SHOW_DERIVED = "ShowDerived"; //$NON-NLS-1$ private ShowDerivedResourcesAction showDerivedResourcesAction; private ResourceItemLabelProvider resourceItemLabelProvider; private ResourceItemDetailsLabelProvider resourceItemDetailsLabelProvider; private WorkingSetFilterActionGroup workingSetFilterActionGroup; private CustomWorkingSetFilter workingSetFilter = new CustomWorkingSetFilter(); private String title; ISelectionService iSelectionService = null; /** * The base outer-container which will be used to search for resources. This * is the root of the tree that spans the search space. Often, this is the * workspace root. */ private IContainer container; /** * The container to use as starting point for relative search, or <code>null</code> if none. * * @since 3.6 */ private IContainer searchContainer; private int typeMask; private boolean isDerived; private String fileNamePattern; private String pathPattern; /** * Creates a new instance of the class * * @param shell * the parent shell * @param multi * the multi selection flag * @param container * the container to select resources from, e.g. the workspace * root * @param typesMask * a mask specifying which resource types should be shown in the * dialog. The mask should contain one or more of the resource * type bit masks defined in {@link IResource#getType()} */ public FlowResourcesSelectionDialog(Shell shell, boolean multi, IContainer container, int typesMask) { super(shell, multi); contentProvider = new FlowContentProvider(); setSelectionHistory(new ResourceSelectionHistory()); setTitle(IDEWorkbenchMessages.OpenResourceDialog_title); /* * Allow location of paths relative to a searchContainer, which is * initialized from the active editor or the selected element. */ IWorkbenchWindow ww = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); if (ww != null) { IWorkbenchPage activePage = ww.getActivePage(); if (activePage != null) { IResource resource = null; IEditorPart activeEditor = activePage.getActiveEditor(); if (activeEditor != null && activeEditor == activePage.getActivePart()) { IEditorInput editorInput = activeEditor.getEditorInput(); resource = ResourceUtil.getResource(editorInput); } else { iSelectionService = ww.getSelectionService(); ISelection selection = iSelectionService.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; if (structuredSelection.size() == 1) { resource = ResourceUtil .getResource(structuredSelection .getFirstElement()); } } } if (resource != null) { if (!(resource instanceof IContainer)) { resource = resource.getParent(); } searchContainer = (IContainer) resource; } } } this.container = ClassloaderHelper.getActiveJavaProject().getProject(); this.typeMask = typesMask; resourceItemLabelProvider = new ResourceItemLabelProvider(); resourceItemDetailsLabelProvider = new ResourceItemDetailsLabelProvider(); setListLabelProvider(resourceItemLabelProvider); setDetailsLabelProvider(resourceItemDetailsLabelProvider); } public class FlowContentProvider extends ContentProvider { protected Object[] getSortedItems() { List<ListEntry> flows = FlowFromJarsLoader.getInstance().getFlows(ClassloaderHelper.getActiveProjectName()); if (lastSortedItems.size() != items.size() + flows.size()) { synchronized (lastSortedItems) { List<String> list = new ArrayList<String>(flows.size()); for (ListEntry entry: flows) { Object[] children = (Object[]) entry.getChildren(null); for (Object child : children) { ListEntry c = (ListEntry)child; list.add(entry.getMessage() + "-" + c.getMessage()); } } lastSortedItems.clear(); lastSortedItems.addAll(items); lastSortedItems.addAll(list); Collections.sort(lastSortedItems, getHistoryComparator()); } } return lastSortedItems.toArray(); } protected Object[] getFilteredItems(Object parent, IProgressMonitor monitor) { int ticks = 100; if (monitor == null) { monitor = new NullProgressMonitor(); } monitor .beginTask( WorkbenchMessages.FilteredItemsSelectionDialog_cacheRefreshJob_getFilteredElements, ticks); if (filters != null) { ticks /= (filters.size() + 2); } else { ticks /= 2; } // get already sorted array Object[] filteredElements = getSortedItems(); // monitor.worked(ticks); // // // filter the elements using provided ViewerFilters // if (this.contentProvider.filters != null && filteredElements != null) { // for (Iterator iter = this.contentProvider.filters.iterator(); iter.hasNext();) { // ViewerFilter f = (ViewerFilter) iter.next(); // filteredElements = f.filter(list, parent, filteredElements); // monitor.worked(ticks); // } // } if (filteredElements == null || monitor.isCanceled()) { monitor.done(); return new Object[0]; } ArrayList preparedElements = new ArrayList(filteredElements.length); // preparedElements.addAll(this.itemsFromJars); boolean hasHistory = false; if (filteredElements.length > 0) { if (isHistoryElement(filteredElements[0])) { hasHistory = true; } } int reportEvery = filteredElements.length / ticks; // add separator for (int i = 0; i < filteredElements.length; i++) { Object item = filteredElements[i]; if (hasHistory && !isHistoryElement(item)) { preparedElements.add(itemsListSeparator); hasHistory = false; } preparedElements.add(item); if (reportEvery != 0 && ((i + 1) % reportEvery == 0)) { monitor.worked(1); } } monitor.done(); return preparedElements.toArray(); } } // public void addFromJars(List<String> list) { // this.itemsFromJars.addAll(list); // } public void setResourceFilter(String filter) { this.fileNamePattern = filter; } public void setPathFilter(String filter) { this.pathPattern = filter; } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.SelectionStatusDialog#configureShell(org.eclipse * .swt.widgets.Shell) */ protected void configureShell(Shell shell) { super.configureShell(shell); PlatformUI.getWorkbench().getHelpSystem() .setHelp(shell, IIDEHelpContextIds.OPEN_RESOURCE_DIALOG); } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.SelectionDialog#setTitle(java.lang.String) */ public void setTitle(String title) { super.setTitle(title); this.title = title; } /** * Adds or replaces subtitle of the dialog * * @param text * the new subtitle */ private void setSubtitle(String text) { if (text == null || text.length() == 0) { getShell().setText(title); } else { getShell().setText(title + " - " + text); //$NON-NLS-1$ } } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getDialogSettings() */ protected IDialogSettings getDialogSettings() { IDialogSettings settings = IDEWorkbenchPlugin.getDefault() .getDialogSettings().getSection(DIALOG_SETTINGS); if (settings == null) { settings = IDEWorkbenchPlugin.getDefault().getDialogSettings() .addNewSection(DIALOG_SETTINGS); } return settings; } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#storeDialog(org.eclipse * .jface.dialogs.IDialogSettings) */ protected void storeDialog(IDialogSettings settings) { super.storeDialog(settings); settings.put(SHOW_DERIVED, showDerivedResourcesAction.isChecked()); XMLMemento memento = XMLMemento.createWriteRoot("workingSet"); //$NON-NLS-1$ workingSetFilterActionGroup.saveState(memento); workingSetFilterActionGroup.dispose(); StringWriter writer = new StringWriter(); try { memento.save(writer); settings.put(WORKINGS_SET_SETTINGS, writer.getBuffer().toString()); } catch (IOException e) { StatusManager.getManager().handle( new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, IStatus.ERROR, "", e)); //$NON-NLS-1$ // don't do anything. Simply don't store the settings } } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#restoreDialog(org * .eclipse.jface.dialogs.IDialogSettings) */ protected void restoreDialog(IDialogSettings settings) { super.restoreDialog(settings); boolean showDerived = settings.getBoolean(SHOW_DERIVED); showDerivedResourcesAction.setChecked(showDerived); this.isDerived = showDerived; String setting = settings.get(WORKINGS_SET_SETTINGS); if (setting != null) { try { IMemento memento = XMLMemento.createReadRoot(new StringReader( setting)); workingSetFilterActionGroup.restoreState(memento); } catch (WorkbenchException e) { StatusManager.getManager().handle( new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, IStatus.ERROR, "", e)); //$NON-NLS-1$ // don't do anything. Simply don't restore the settings } } addListFilter(workingSetFilter); applyFilter(); } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillViewMenu(org. * eclipse.jface.action.IMenuManager) */ protected void fillViewMenu(IMenuManager menuManager) { super.fillViewMenu(menuManager); showDerivedResourcesAction = new ShowDerivedResourcesAction(); menuManager.add(showDerivedResourcesAction); workingSetFilterActionGroup = new WorkingSetFilterActionGroup( getShell(), new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property = event.getProperty(); if (WorkingSetFilterActionGroup.CHANGE_WORKING_SET .equals(property)) { IWorkingSet workingSet = (IWorkingSet) event .getNewValue(); if (workingSet != null && !(workingSet.isAggregateWorkingSet() && workingSet .isEmpty())) { workingSetFilter.setWorkingSet(workingSet); setSubtitle(workingSet.getLabel()); } else { IWorkbenchWindow window = PlatformUI .getWorkbench() .getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window .getActivePage(); workingSet = page.getAggregateWorkingSet(); if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) { workingSet = null; } } workingSetFilter.setWorkingSet(workingSet); setSubtitle(null); } scheduleRefresh(); } } }); menuManager.add(new Separator()); workingSetFilterActionGroup.fillContextMenu(menuManager); } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createExtendedContentArea * (org.eclipse.swt.widgets.Composite) */ protected Control createExtendedContentArea(Composite parent) { return null; } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.SelectionDialog#getResult() */ public Object[] getResult() { Object[] result = super.getResult(); if (result == null) return null; List resultToReturn = new ArrayList(result.length); for (int i = 0; i < result.length; i++) { if (result[i] instanceof String) { resultToReturn.add((result[i])); } } return resultToReturn.toArray(); } /* * (non-Javadoc) * * @see org.eclipse.jface.window.Window#open() */ public int open() { if (getInitialPattern() == null) { IWorkbenchWindow window = PlatformUI.getWorkbench() .getActiveWorkbenchWindow(); if (window != null) { ISelection selection = window.getSelectionService() .getSelection(); if (selection instanceof ITextSelection) { String text = ((ITextSelection) selection).getText(); if (text != null) { text = text.trim(); if (text.length() > 0) { IWorkspace workspace = ResourcesPlugin .getWorkspace(); IStatus result = workspace.validateName(text, IResource.FILE); if (result.isOK()) { setInitialPattern(text); } } } } } } return super.open(); } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getElementName(java * .lang.Object) */ public String getElementName(Object item) { String resource = (String) item; return resource; } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#validateItem(java * .lang.Object) */ protected IStatus validateItem(Object item) { return new Status(IStatus.OK, WorkbenchPlugin.PI_WORKBENCH, 0, "", null); //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#createFilter() */ protected ItemsFilter createFilter() { return new ResourceFilter(container, searchContainer, isDerived, typeMask); } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#applyFilter() */ protected void applyFilter() { super.applyFilter(); } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#getItemsComparator() */ protected Comparator getItemsComparator() { return new Comparator() { public int compare(Object o1, Object o2) { String c1 = (String) o1; String c2 = (String) o2; int comparability = c1.compareTo(c2); // Collator collator = Collator.getInstance(); // String resource1 = (String) o1; // IResource resource2 = (IResource) o2; // String s1 = resource1.getName(); // String s2 = resource2.getName(); // // // Compare names without extension first // int s1Dot = s1.lastIndexOf('.'); // int s2Dot = s2.lastIndexOf('.'); // String n1 = s1Dot == -1 ? s1 : s1.substring(0, s1Dot); // String n2 = s2Dot == -1 ? s2 : s2.substring(0, s2Dot); // int comparability = collator.compare(n1, n2); // if (comparability != 0) // return comparability; // // // Compare full names // if (s1Dot != -1 || s2Dot != -1) { // comparability = collator.compare(s1, s2); // if (comparability != 0) // return comparability; // } // // // Search for resource relative paths // if (searchContainer != null) { // IContainer c1 = resource1.getParent(); // IContainer c2 = resource2.getParent(); // // // Return paths 'closer' to the searchContainer first // comparability = pathDistance(c1) - pathDistance(c2); // if (comparability != 0) // return comparability; // } // // // Finally compare full path segments // IPath p1 = resource1.getFullPath(); // IPath p2 = resource2.getFullPath(); // // Don't compare file names again, so subtract 1 // int c1 = p1.segmentCount() - 1; // int c2 = p2.segmentCount() - 1; // for (int i = 0; i < c1 && i < c2; i++) { // comparability = collator.compare(p1.segment(i), // p2.segment(i)); // if (comparability != 0) // return comparability; // } // comparability = c1 - c2; return comparability; } /* * (non-Javadoc) * * @see java.util.Comparator#compare(java.lang.Object, * java.lang.Object) */ // public int compare(Object o1, Object o2) { // Collator collator = Collator.getInstance(); // IResource resource1 = (IResource) o1; // IResource resource2 = (IResource) o2; // String s1 = resource1.getName(); // String s2 = resource2.getName(); // // // Compare names without extension first // int s1Dot = s1.lastIndexOf('.'); // int s2Dot = s2.lastIndexOf('.'); // String n1 = s1Dot == -1 ? s1 : s1.substring(0, s1Dot); // String n2 = s2Dot == -1 ? s2 : s2.substring(0, s2Dot); // int comparability = collator.compare(n1, n2); // if (comparability != 0) // return comparability; // // // Compare full names // if (s1Dot != -1 || s2Dot != -1) { // comparability = collator.compare(s1, s2); // if (comparability != 0) // return comparability; // } // // // Search for resource relative paths // if (searchContainer != null) { // IContainer c1 = resource1.getParent(); // IContainer c2 = resource2.getParent(); // // // Return paths 'closer' to the searchContainer first // comparability = pathDistance(c1) - pathDistance(c2); // if (comparability != 0) // return comparability; // } // // // Finally compare full path segments // IPath p1 = resource1.getFullPath(); // IPath p2 = resource2.getFullPath(); // // Don't compare file names again, so subtract 1 // int c1 = p1.segmentCount() - 1; // int c2 = p2.segmentCount() - 1; // for (int i = 0; i < c1 && i < c2; i++) { // comparability = collator.compare(p1.segment(i), // p2.segment(i)); // if (comparability != 0) // return comparability; // } // comparability = c1 - c2; // // return comparability; // } }; } /** * Return the "distance" of the item from the root of the relative search * container. Distances can be compared (smaller numbers are better). <br> * - Closest distance is if the item is the same folder as the search * container.<br> * - Next are folders inside the search container.<br> * - After all those, distance increases with decreasing matching prefix * folder count.<br> * * @param item * parent of the resource being examined * @return the "distance" of the passed in IResource from the search * container * @since 3.6 */ private int pathDistance(IContainer item) { // Container search path: e.g. /a/b/c IPath containerPath = searchContainer.getFullPath(); // itemPath: distance: // /a/b/c ==> 0 // /a/b/c/d/e ==> 2 // /a/b ==> Integer.MAX_VALUE/4 + 1 // /a/x/e/f ==> Integer.MAX_VALUE/4 + 2 // /g/h ==> Integer.MAX_VALUE/2 IPath itemPath = item.getFullPath(); if (itemPath.equals(containerPath)) return 0; int matching = containerPath.matchingFirstSegments(itemPath); if (matching == 0) return Integer.MAX_VALUE / 2; int containerSegmentCount = containerPath.segmentCount(); if (matching == containerSegmentCount) { // inside searchContainer: return itemPath.segmentCount() - matching; } // outside searchContainer: return Integer.MAX_VALUE / 4 + containerSegmentCount - matching; } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog#fillContentProvider * (org * .eclipse.ui.dialogs.FilteredItemsSelectionDialog.AbstractContentProvider, * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter, * org.eclipse.core.runtime.IProgressMonitor) */ protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { if (itemsFilter instanceof ResourceFilter) container.accept(new ResourceProxyVisitor(contentProvider, (ResourceFilter) itemsFilter, progressMonitor), IResource.DEPTH_INFINITE); if (progressMonitor != null) progressMonitor.done(); } /** * Sets the derived flag on the ResourceFilter instance */ private class ShowDerivedResourcesAction extends Action { /** * Creates a new instance of the action. */ public ShowDerivedResourcesAction() { super( IDEWorkbenchMessages.FilteredResourcesSelectionDialog_showDerivedResourcesAction, IAction.AS_CHECK_BOX); } public void run() { FlowResourcesSelectionDialog.this.isDerived = isChecked(); applyFilter(); } } /** * A label provider for ResourceDecorator objects. It creates labels with a * resource full path for duplicates. It uses the Platform UI label * decorator for providing extra resource info. */ private class ResourceItemLabelProvider extends LabelProvider implements ILabelProviderListener, IStyledLabelProvider { // Need to keep our own list of listeners private ListenerList listeners = new ListenerList(); WorkbenchLabelProvider provider = new WorkbenchLabelProvider(); /** * Creates a new instance of the class */ public ResourceItemLabelProvider() { super(); provider.addListener(this); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { if (!(element instanceof IResource)) { return super.getImage(element); } IResource res = (IResource) element; return provider.getImage(res); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (!(element instanceof IResource)) { return super.getText(element); } IResource res = (IResource) element; String str = res.getName(); // extra info for duplicates if (isDuplicateElement(element)) str = str + " - " + res.getParent().getFullPath().makeRelative().toString(); //$NON-NLS-1$ return str; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider. * IStyledLabelProvider#getStyledText(java.lang.Object) */ public StyledString getStyledText(Object element) { if (!(element instanceof IResource)) { return new StyledString(super.getText(element)); } IResource res = (IResource) element; StyledString str = new StyledString(res.getName()); // extra info for duplicates if (isDuplicateElement(element)) { str.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$ str.append(res.getParent().getFullPath().makeRelative() .toString(), StyledString.QUALIFIER_STYLER); } // Debugging: // int pathDistance = pathDistance(res.getParent()); // if (pathDistance != Integer.MAX_VALUE / 2) { // if (pathDistance > Integer.MAX_VALUE / 4) // str.append(" (" + (pathDistance - Integer.MAX_VALUE / 4) + // " folders up from current selection)", // StyledString.QUALIFIER_STYLER); // else // str.append(" (" + pathDistance + // " folders down from current selection)", // StyledString.QUALIFIER_STYLER); // } return str; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.LabelProvider#dispose() */ public void dispose() { provider.removeListener(this); provider.dispose(); super.dispose(); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.IBaseLabelProvider#addListener(org.eclipse * .jface.viewers.ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { listeners.add(listener); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.LabelProvider#removeListener(org.eclipse * .jface.viewers.ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { listeners.remove(listener); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ILabelProviderListener#labelProviderChanged * (org.eclipse.jface.viewers.LabelProviderChangedEvent) */ public void labelProviderChanged(LabelProviderChangedEvent event) { Object[] l = listeners.getListeners(); for (int i = 0; i < listeners.size(); i++) { ((ILabelProviderListener) l[i]).labelProviderChanged(event); } } } /** * A label provider for details of ResourceItem objects. */ private class ResourceItemDetailsLabelProvider extends ResourceItemLabelProvider { /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { if (!(element instanceof IResource)) { return super.getImage(element); } IResource parent = ((IResource) element).getParent(); return provider.getImage(parent); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.LabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (!(element instanceof IResource)) { return super.getText(element); } IResource parent = ((IResource) element).getParent(); if (parent.getType() == IResource.ROOT) { // Get readable name for workspace root ("Workspace"), without // duplicating language-specific string here. return null; } return parent.getFullPath().makeRelative().toString(); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ILabelProviderListener#labelProviderChanged * (org.eclipse.jface.viewers.LabelProviderChangedEvent) */ public void labelProviderChanged(LabelProviderChangedEvent event) { Object[] l = super.listeners.getListeners(); for (int i = 0; i < super.listeners.size(); i++) { ((ILabelProviderListener) l[i]).labelProviderChanged(event); } } } /** * Viewer filter which filters resources due to current working set */ private class CustomWorkingSetFilter extends ViewerFilter { private ResourceWorkingSetFilter resourceWorkingSetFilter = new ResourceWorkingSetFilter(); /** * Sets the active working set. * * @param workingSet * the working set the filter should work with */ public void setWorkingSet(IWorkingSet workingSet) { resourceWorkingSetFilter.setWorkingSet(workingSet); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers * .Viewer, java.lang.Object, java.lang.Object) */ public boolean select(Viewer viewer, Object parentElement, Object element) { return resourceWorkingSetFilter.select(viewer, parentElement, element); } } /** * ResourceProxyVisitor to visit resource tree and get matched resources. * During visit resources it updates progress monitor and adds matched * resources to ContentProvider instance. */ private class ResourceProxyVisitor implements IResourceProxyVisitor { private AbstractContentProvider proxyContentProvider; private ResourceFilter resourceFilter; private IProgressMonitor progressMonitor; private List projects; /** * Creates new ResourceProxyVisitor instance. * * @param contentProvider * @param resourceFilter * @param progressMonitor * @throws CoreException */ public ResourceProxyVisitor(AbstractContentProvider contentProvider, ResourceFilter resourceFilter, IProgressMonitor progressMonitor) throws CoreException { super(); this.proxyContentProvider = contentProvider; this.resourceFilter = resourceFilter; this.progressMonitor = progressMonitor; // IResource[] resources = container.members(); this.projects = new ArrayList(Arrays.asList(ClassloaderHelper.getActiveJavaProject().getProject())); if (progressMonitor != null) progressMonitor .beginTask( WorkbenchMessages.FilteredItemsSelectionDialog_searchJob_taskName, projects.size()); } /* * (non-Javadoc) * * @see * org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse * .core.resources.IResourceProxy) */ public boolean visit(IResourceProxy proxy) { if (progressMonitor.isCanceled()) return false; IResource resource = proxy.requestResource(); if (this.projects.remove((resource.getProject())) || this.projects.remove((resource))) { progressMonitor.worked(1); } proxyContentProvider.add(resource, resourceFilter); if (resource.getType() == IResource.FOLDER && resource.isDerived() && !resourceFilter.isShowDerived()) { return false; } if (resource.getType() == IResource.FILE) { return false; } return true; } } /** * Filters resources using pattern and showDerived flag. It overrides * ItemsFilter. */ protected class ResourceFilter extends ItemsFilter { private boolean showDerived = false; private IContainer filterContainer; /** * Container path pattern. Is <code>null</code> when only a file name * pattern is used. * * @since 3.6 */ private SearchPattern containerPattern; /** * Container path pattern, relative to the current searchContainer. Is <code>null</code> if there's no search * container. * * @since 3.6 */ private SearchPattern relativeContainerPattern; /** * Camel case pattern for the name part of the file name (without * extension). Is <code>null</code> if there's no extension. * * @since 3.6 */ SearchPattern namePattern; /** * Camel case pattern for the file extension. Is <code>null</code> if * there's no extension. * * @since 3.6 */ SearchPattern extensionPattern; private int filterTypeMask; /** * Creates new ResourceFilter instance * * @param container * @param showDerived * flag which determine showing derived elements * @param typeMask */ public ResourceFilter(IContainer container, boolean showDerived, int typeMask) { super(); this.filterContainer = container; this.showDerived = showDerived; this.filterTypeMask = typeMask; } /** * Creates new ResourceFilter instance * * @param container * @param searchContainer * IContainer to use for performing relative search * @param showDerived * flag which determine showing derived elements * @param typeMask * @since 3.6 */ private ResourceFilter(IContainer container, IContainer searchContainer, boolean showDerived, int typeMask) { this(container, showDerived, typeMask); String stringPattern = pathPattern + getPattern() + "." + fileNamePattern; String filenamePattern; int sep = stringPattern.lastIndexOf(IPath.SEPARATOR); if (sep != -1) { filenamePattern = stringPattern.substring(sep + 1, stringPattern.length()); if ("*".equals(filenamePattern)) //$NON-NLS-1$ filenamePattern = "**"; //$NON-NLS-1$ if (sep > 0) { if (filenamePattern.length() == 0) // relative patterns // don't need a file // name filenamePattern = "**"; //$NON-NLS-1$ String containerPattern = stringPattern.substring(0, sep); if (searchContainer != null) { relativeContainerPattern = new SearchPattern( SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_PATTERN_MATCH); relativeContainerPattern.setPattern(searchContainer .getFullPath().append(containerPattern) .toString()); } if (!containerPattern.startsWith("" + IPath.SEPARATOR)) //$NON-NLS-1$ containerPattern = IPath.SEPARATOR + containerPattern; this.containerPattern = new SearchPattern( SearchPattern.RULE_EXACT_MATCH | SearchPattern.RULE_PREFIX_MATCH | SearchPattern.RULE_PATTERN_MATCH); this.containerPattern.setPattern(containerPattern); } patternMatcher.setPattern(filenamePattern); } else { filenamePattern = stringPattern; } int lastPatternDot = filenamePattern.lastIndexOf('.'); if (lastPatternDot != -1) { char last = filenamePattern .charAt(filenamePattern.length() - 1); if (last != ' ' && last != '<' && getMatchRule() != SearchPattern.RULE_EXACT_MATCH) { namePattern = new SearchPattern(); namePattern.setPattern(filenamePattern.substring(0, lastPatternDot)); extensionPattern = new SearchPattern(); // extensionPattern.setPattern(filenamePattern // .substring(lastPatternDot + 1)); extensionPattern.setPattern(fileNamePattern); } } // namePattern = new SearchPattern(); // namePattern.setPattern("*"); // extensionPattern = new SearchPattern(); // extensionPattern.setPattern(".n4j"); } /** * Creates new ResourceFilter instance */ public ResourceFilter() { this(container, searchContainer, isDerived, typeMask); } /** * @param item * Must be instance of IResource, otherwise <code>false</code> will be returned. * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#isConsistentItem(java.lang.Object) */ public boolean isConsistentItem(Object item) { if (!(item instanceof IResource)) { return false; } IResource resource = (IResource) item; if (this.filterContainer.findMember(resource.getFullPath()) != null) return true; return false; } /** * @param item * Must be instance of IResource, otherwise <code>false</code> will be returned. * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter#matchItem(java.lang.Object) */ public boolean matchItem(Object item) { if (!(item instanceof IResource)) { return false; } IResource resource = (IResource) item; if ((!this.showDerived && resource.isDerived()) || ((this.filterTypeMask & resource.getType()) == 0)) return false; String name = resource.getName(); if (nameMatches(name)) { if (containerPattern != null) { // match full container path: String containerPath = resource.getParent().getFullPath() .toString(); if (containerPattern.matches(containerPath)) return true; // match path relative to current selection: if (relativeContainerPattern != null) return relativeContainerPattern.matches(containerPath); return false; } return true; } return false; } private boolean nameMatches(String name) { if (namePattern != null) { // fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212565 int lastDot = name.lastIndexOf('.'); if (lastDot != -1 && namePattern.matches(name.substring(0, lastDot)) && extensionPattern .matches(name.substring(lastDot + 1))) { return true; } } return matches(name); } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter# * isSubFilter * (org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) */ public boolean isSubFilter(ItemsFilter filter) { if (!super.isSubFilter(filter)) return false; if (filter instanceof ResourceFilter) { ResourceFilter resourceFilter = (ResourceFilter) filter; if (this.showDerived == resourceFilter.showDerived) { if (containerPattern == null) { return resourceFilter.containerPattern == null; } else if (resourceFilter.containerPattern == null) { return false; } else { return containerPattern .equals(resourceFilter.containerPattern); } } } return false; } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter# * equalsFilter * (org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) */ public boolean equalsFilter(ItemsFilter iFilter) { if (!super.equalsFilter(iFilter)) return false; if (iFilter instanceof ResourceFilter) { ResourceFilter resourceFilter = (ResourceFilter) iFilter; if (this.showDerived == resourceFilter.showDerived) { if (containerPattern == null) { return resourceFilter.containerPattern == null; } else if (resourceFilter.containerPattern == null) { return false; } else { return containerPattern .equals(resourceFilter.containerPattern); } } } return false; } /** * Check show derived flag for a filter * * @return true if filter allow derived resources false if not */ public boolean isShowDerived() { return showDerived; } } /** * <code>ResourceSelectionHistory</code> provides behavior specific to * resources - storing and restoring <code>IResource</code>s state to/from * XML (memento). */ private class ResourceSelectionHistory extends SelectionHistory { /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory * #restoreItemFromMemento(org.eclipse.ui.IMemento) */ protected Object restoreItemFromMemento(IMemento element) { ResourceFactory resourceFactory = new ResourceFactory(); IResource resource = (IResource) resourceFactory .createElement(element); return resource; } /* * (non-Javadoc) * * @see * org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.SelectionHistory * #storeItemToMemento(java.lang.Object, org.eclipse.ui.IMemento) */ protected void storeItemToMemento(Object item, IMemento element) { // String resource = (String) item; // ResourceFactory resourceFactory = new ResourceFactory(resource); // resourceFactory.saveState(element); } } }
package com.winksoft.idcardcer.net.mfs.app; import java.nio.charset.Charset; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import java.nio.charset.CharsetDecoder; import android.util.Log; //CumulativeProtocolDecoder public class MFDecoder extends CumulativeProtocolDecoder { private Charset charset = Charset.forName("GB2312"); @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { Log.i(this.getClass().toString(), "解码:" + in.toString()); if (in.remaining()< 4) return false; in.mark(); @SuppressWarnings("unused") byte tag = in.get(); //1 tag @SuppressWarnings("unused") short flag = in.get(); //2 flag @SuppressWarnings("unused") short appLen = in.getShort(); //3 appLen if (in.remaining()<appLen+1){ in.reset(); return false; } MFSessionPacket msg = new MFSessionPacket(); short srcLen = in.getShort(); //4 srcLen if ((srcLen+2+1 > in.remaining()) || (srcLen < 6)){ return false; } msg.command = in.getShort(); //5 Command msg.returnCode = in.getShort(); //6 short fieldNum = in.getShort(); //7 CharsetDecoder cd = charset.newDecoder(); for (int i=0;i<fieldNum;i++){ if (in.remaining() < 4+1){ return false; } short fieldID = in.getShort(); short fieldLen = in.getShort(); if (in.remaining()<fieldLen+1){ return false; } MFPacketField field; if (fieldLen!=0) { byte[] m= new byte[fieldLen]; in.get(m); field = new MFPacketField(fieldID, m); }else field = new MFPacketField(fieldID, new byte[0]); msg.fieldList.add(field); } msg.checkSum = in.getShort(); msg.ETX = in.get(); out.write(msg); if (in.remaining()>0) return true; else return false; } }
package modele; import geocache.UserEntity; import utils.JpaDao; public class UserDao extends JpaDao<UserEntity> implements DAOInterface{ private static UserDao instance; public UserDao() { super(UserEntity.class); } public static UserDao getInstance(){ if(instance == null) { instance = new UserDao(); } return instance; } }
package com.other; public class AtoI { public int atoi(String s) { if(s== null) return 0; int length = s.length(); if(length <1) return 0; double result = 0; char flag = '+'; int i=0; if(s.charAt(0) == '-') { flag = '-'; i++; }else if(s.charAt(0)=='+') { i++; } while(length > i && s.charAt(i) >='0' && s.charAt(i) <='9') { result = result*10+(s.charAt(i) -'0'); i++; } if(flag =='-') { result = result *-1; } if(result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if(result < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int)result; } public static void main(String[] args) { AtoI ai =new AtoI(); System.out.println(ai.atoi("-123")); } }
package fundamentos.tarefas; import java.util.Scanner; public class Tarefa3 { public static void main(String[] args) { /* * Criar um programa que leia o peso e * a altura do usuário e imprima no * console o IMC. */ Scanner entrada = new Scanner(System.in); System.out.println("Informe seu Peso: "); double peso = entrada.nextDouble(); System.out.println("Informe sua altura: "); double altura = entrada.nextDouble(); double calculo = peso/(altura*altura); System.out.println("seu IMC é de: " + calculo); entrada.close(); } }
package org.squonk.execution.steps; /** * Created by timbo on 19/01/17. */ public interface StatusUpdatable { void updateStatus(String status); }
package com.limegroup.gnutella.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import org.limewire.util.OSUtils; import org.limewire.util.VersionUtils; import com.limegroup.gnutella.util.FrostWireUtils; /** * Contains the <tt>JDialog</tt> instance that shows "about" information for the * application. */ // 2345678|012345678|012345678|012345678|012345678|012345678|012345678|012345678| final class AboutWindow { /** * Constant handle to the <tt>JDialog</tt> that contains about information. */ private final JDialog DIALOG; /** * Constant for the scolling pane of credits. */ private final ScrollingTextPane SCROLLING_PANE; private final JLabel EULA_LABEL; private final JLabel PRIVACY_POLICY_LABEL; /** * Constructs the elements of the about window. */ AboutWindow() { DIALOG = new JDialog(GUIMediator.getAppFrame()); if (!OSUtils.isMacOSX()) DIALOG.setModal(true); DIALOG.setSize(new Dimension(600, 400)); DIALOG.setResizable(false); DIALOG.setTitle(I18n.tr("About FrostWire")); DIALOG.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); DIALOG.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent we) { SCROLLING_PANE.stopScroll(); } public void windowClosing(WindowEvent we) { SCROLLING_PANE.stopScroll(); } }); // set up scrolling pane SCROLLING_PANE = createScrollingPane(); SCROLLING_PANE.addHyperlinkListener(GUIUtils.getHyperlinkListener()); // set up limewire version label JLabel client = new JLabel(I18n.tr("FrostWire") + " " + FrostWireUtils.getFrostWireVersion() + " (build " + FrostWireUtils.getBuildNumber() + ")"); client.setHorizontalAlignment(SwingConstants.CENTER); // set up java version label JLabel java = new JLabel("Java " + VersionUtils.getJavaVersion()); java.setHorizontalAlignment(SwingConstants.CENTER); // set up frostwire.com label JLabel url = new URLLabel("http://www.frostwire.com"); url.setHorizontalAlignment(SwingConstants.CENTER); EULA_LABEL = new URLLabel("http://www.frostwire.com/eula",I18n.tr("End User License Agreement")); PRIVACY_POLICY_LABEL = new URLLabel("http://www.frostwire.com/privacy","Privacy Policy"); // set up close button JButton button = new JButton(I18n.tr("Close")); DIALOG.getRootPane().setDefaultButton(button); button.setToolTipText(I18n.tr("Close This Window")); button.addActionListener(GUIUtils.getDisposeAction()); // layout window JComponent pane = (JComponent) DIALOG.getContentPane(); GUIUtils.addHideAction(pane); pane.setLayout(new GridBagLayout()); pane.setBorder(BorderFactory.createEmptyBorder(GUIConstants.SEPARATOR, GUIConstants.SEPARATOR, GUIConstants.SEPARATOR, GUIConstants.SEPARATOR)); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1; gbc.insets = new Insets(0, 0, 0, 0); gbc.gridwidth = 2; gbc.gridy = 0; LogoPanel logo = new LogoPanel(); pane.add(logo, gbc); gbc.gridy = 1; pane.add(Box.createVerticalStrut(GUIConstants.SEPARATOR), gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridy = 2; pane.add(client, gbc); gbc.gridy = 3; pane.add(java, gbc); gbc.gridy = 4; pane.add(url, gbc); gbc.gridy = 5; pane.add(Box.createVerticalStrut(GUIConstants.SEPARATOR), gbc); gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.gridy = 6; pane.add(SCROLLING_PANE, gbc); gbc.gridy = 7; gbc.weighty = 0; gbc.fill = GridBagConstraints.NONE; pane.add(Box.createVerticalStrut(GUIConstants.SEPARATOR), gbc); JPanel legalLinksPanel = new JPanel(); legalLinksPanel.setPreferredSize(new Dimension(300,27)); legalLinksPanel.setMinimumSize(new Dimension(300,27)); legalLinksPanel.add(EULA_LABEL,BorderLayout.LINE_START); legalLinksPanel.add(PRIVACY_POLICY_LABEL,BorderLayout.LINE_END); gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.WEST; gbc.gridwidth = 1; gbc.gridy = 8; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.WEST; pane.add(legalLinksPanel, gbc); gbc = new GridBagConstraints(); gbc.gridy = 8; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.anchor = GridBagConstraints.EAST; pane.add(button, gbc); } private void appendListOfNames(String commaSepNames, StringBuilder sb) { for (String name : commaSepNames.split(",")) sb.append("<li>"+name+"</li>"); } private ScrollingTextPane createScrollingPane() { StringBuilder sb = new StringBuilder(); sb.append("<html>"); Color color = new JLabel().getForeground(); int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); String hex = toHex(r) + toHex(g) + toHex(b); sb.append("<body text='#" + hex + "'>"); // introduction sb.append(I18n.tr("<h1>FrostWire Logo Designer</h1>")); sb.append("<ul><li>Luis Ramirez (Venezuela - <a href='http://www.elblogo.com'>ElBlogo.com</a>)</li></ul>"); sb.append(I18n.tr("<h1>FrostWire Graphics Designers/Photographers</h1>")); sb.append("<ul>"); sb.append("<li>Kirill Grouchnikov - Substance library <a href='http://www.pushing-pixels.org/'>Pushing-Pixels.org</a></li>"); sb.append("<li>Arianys Wilson - Splash 4.18 (New York - <a href='http://nanynany.com/blog/?from=frostwire'>NanyNany.com</a>)</li>"); sb.append("<li>Scott Kellum - Splash 4.17 (New York - <a href='http://www.scottkellum.net'>ScottKellum.net</a>)</li>"); sb.append("<li>Shelby Allen - Splash 4.13 (New Zealand - <a href='http://www.stitzu.com'>Stitzu.com</a>)</li>"); sb.append("<li>Cecko Hanssen - <a href='http://www.flickr.com/photos/cecko/95013472/'>Frozen Brothers</a> CC Photograph for 4.17 Splash (Tilburg, Netherlands)</li>"); sb.append("<li>Marcelina Knitter - <a href='https://twitter.com/#!/marcelinkaaa'>@Marcelinkaaa</a></li>"); sb.append("</ul>"); sb.append(I18n.tr("<h1>Thanks to Former FrostWire Developers</h1>")); sb.append("<li>Gregorio Roper (Germany)</li>"); sb.append("<li>Fernando Toussaint '<strong>FTA</strong>' - <a href='http://www.cybercultura.net'>Web</a></li>"); sb.append("<br><br>"); sb.append(I18n.tr("<h1>Thanks to the FrostWire Chat Community!</h1>")); sb.append(I18n.tr("Thanks to everybody that has helped us everyday in the forums and chatrooms, " + "you not only help new users but you also warn the FrostWire team of any problem that " + "occur on our networks. Thank you all, without you this wouldn't be possible!")); sb.append(I18n.tr("<br><br>In Special we give thanks to the Chatroom Operators and Forum Moderators")); sb.append("<ul>"); sb.append(I18n.tr("<h1>FrostWire Chat Operators</h1>")); String chat_operators = "Aubrey,Casper,COOTMASTER,Emily,Gummo,Hobo,Humanoid,iDan,lexie,OfficerSparker,Scott1x,THX1138,WolfWalker,Wyrdjax,Daemon,Trinity"; appendListOfNames(chat_operators, sb); sb.append("</ul>"); sb.append(I18n.tr("<h1>FrostWire Forum Moderators</h1>")); String forum_moderators="Aaron.Walkhouse,Calliope,cootmaster,Efrain,et voil&agrave;,nonprofessional,Only A Hobo,spuggy,stief,The_Fox"; sb.append("<ul>"); appendListOfNames(forum_moderators,sb); sb.append("</ul>"); sb.append("<h1>Many Former Chat Operators</h1>"); String former_operators="AlleyCat,Coelacanth,Gollum,Jewels,Jordan,Kaapeli,Malachi,Maya,Sabladowah,Sweet_Songbird,UB4T,jwb,luna_moon,nonproffessional,sug,the-jack,yummy-brummy"; sb.append("<ul>"); appendListOfNames(former_operators, sb); sb.append("</ul>"); sb.append(I18n.tr("And also to the Support Volunteer Helpers:")); sb.append("<ul>"); appendListOfNames("dutchboy,Lelu,udsteve",sb); sb.append("</ul>"); // azureus/vuze devs. sb.append("<h1>Thanks to the Azureus Core Developers</h1>"); String az_devs = "Olivier Chalouhi (gudy),Alon Rohter (nolar),Paul Gardner (parg),ArronM (TuxPaper),Paul Duran (fatal_2),Jonathan Ledlie(ledlie),Allan Crooks (amc1),Xyrio (muxumx),Michael Parker (shadowmatter),Aaron Grunthal (the8472)"; sb.append("<ul>"); appendListOfNames(az_devs, sb); sb.append("</ul>"); // developers sb.append(I18n.tr("<h1>Thanks to the LimeWire Developer Team</h1>")); sb.append("<ul>\n" + " <li>Greg Bildson</li>\n" + " <li>Sam Berlin</li>\n" + " <li>Zlatin Balevsky</li>\n" + " <li>Felix Berger</li>\n" + " <li>Mike Everett</li>\n" + " <li>Kevin Faaborg</li>\n" + " <li>Jay Jeyaratnam</li>\n" + " <li>Curtis Jones</li>\n" + " <li>Tim Julien</li>\n" + " <li>Akshay Kumar</li>\n" + " <li>Jeff Palm</li>\n" + " <li>Mike Sorvillo</li>\n" + " <li>Dan Sullivan</li>\n" + "</ul>"); // community VIPs sb.append(I18n.tr("Several colleagues in the Gnutella community merit special thanks. These include:")); sb.append("<ul>\n" + " <li>Vincent Falco -- Free Peers, Inc.</li>\n" + " <li>Gordon Mohr -- Bitzi, Inc.</li>\n" + " <li>John Marshall -- Gnucleus</li>\n" + " <li>Jason Thomas -- Swapper</li>\n" + " <li>Brander Lien -- ToadNode</li>\n" + " <li>Angelo Sotira -- www.gnutella.com</li>\n" + " <li>Marc Molinaro -- www.gnutelliums.com</li>\n" + " <li>Simon Bellwood -- www.gnutella.co.uk</li>\n" + " <li>Serguei Osokine</li>\n" + " <li>Justin Chapweske</li>\n" + " <li>Mike Green</li>\n" + " <li>Raphael Manfredi</li>\n" + " <li>Tor Klingberg</li>\n" + " <li>Mickael Prinkey</li>\n" + " <li>Sean Ediger</li>\n" + " <li>Kath Whittle</li>\n" + "</ul>"); sb.append(I18n.tr("<h1>Thanks to the PJIRC Staff</h1>")); sb.append("<ul>"); sb.append("<li>Plouf</li>"); sb.append("<li>Jiquera</li>"); sb.append("<li>Ezequiel</li>"); sb.append("<li>Superchatbar.nl</li>"); sb.append("<li>Thema</li>"); sb.append("</ul>"); sb.append(I18n.tr("<h1>Thanks to the Automatix Team</h1>")); sb.append("<p>For helping distribute Frostwire to opensource communities in a very simple manner."); sb.append("<ul>"); sb.append("<li>Arnieboy</li>"); sb.append("<li>JimmyJazz</li>"); sb.append("<li>Mstlyevil</li>"); sb.append("<li>WildTangent</li>"); sb.append("</ul>"); sb.append(I18n.tr("<h1>Thanks to Ubuntu/Kubuntu Teams</h1>")); sb.append(I18n.tr("<p>For making the world a better place with such an excellent distro, you'll be the ones to make a difference on the desktop.</p>")); sb.append(I18n.tr("<h1>Thanks to the NSIS Project</h1>")); sb.append(I18n.tr("<p>Thanks for such an awesome installer builder system and documentation.</p>")); sb.append(I18n.tr("<h1>Thanks to our families</h1>")); sb.append(I18n.tr("For being patient during our many sleepless nights")); // bt notice sb.append("<small>"); sb.append("<br><br>"); sb.append(I18n.tr("BitTorrent, the BitTorrent Logo, and Torrent are trademarks of BitTorrent, Inc.")); sb.append("</small>"); sb.append("</body></html>"); return new ScrollingTextPane(sb.toString()); } /** * Returns the int as a hex string. */ private String toHex(int i) { String hex = Integer.toHexString(i).toUpperCase(); if (hex.length() == 1) return "0" + hex; else return hex; } /** * Displays the "About" dialog window to the user. */ void showDialog() { GUIUtils.centerOnScreen(DIALOG); DIALOG.setVisible(true); } }
package com.zzp.seckill.entity; /** * @Description 用户信息 * @Author Garyzeng * @since 2021.01.19 **/ public class User { }
/* * 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 entity; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import javax.persistence.EntityManager; import utils.PuSelector; /** * * @author jamalahmed */ public class UuidFacade { public List<Uuidd> getRandomUuid() { List<Uuidd> uuid = new ArrayList(); for (int i = 0; i < 25; i++) { Uuidd u = new Uuidd(); u.setUuid(UUID.randomUUID().toString()); uuid.add(u); } return uuid; } public List<Uuidd> getRandomUuidWithTimeAndCount(int count) { List<String> strings = new ArrayList(); List<Uuidd> uuid2 = new ArrayList(); for (int i = 0; i < 1; i++) { Uuidd u2 = new Uuidd(); for (int b = 0; b < count; b++) { String u = (UUID.randomUUID().toString()); strings.add(u); } u2.setCreated("Created " + new SimpleDateFormat("dd.MM.yyyy-HH.mm.ss").format(new Date())); u2.setUuids(strings); uuid2.add(u2); } return uuid2; } public List<Uuidd> getRandomUuidWithTime() { List<Uuidd> uuid = new ArrayList(); for (int i = 0; i < 25; i++) { Uuidd u = new Uuidd(); u.setUuid(UUID.randomUUID().toString() + " Created: " + new SimpleDateFormat("dd.MM.yyyy-HH.mm.ss").format(new Date())); uuid.add(u); } return uuid; } public static void main(String[] args) { } }
package com.bigbang.myfavoriteplaces.database; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import com.bigbang.myfavoriteplaces.model.Location; import java.util.List; import io.reactivex.Flowable; @Dao public interface DAO { @Insert void addLocation(Location location); @Query("SELECT * FROM Location") Flowable<List<Location>> getFaveLocs(); @Query("DELETE FROM Location WHERE id = :locationId") void deleteLocation(int locationId); }
package Proyecto; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextArea; import java.awt.Color; import java.awt.SystemColor; import java.awt.Font; import java.awt.Toolkit; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.JTextPane; import javax.swing.JEditorPane; import javax.swing.JToggleButton; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import javax.swing.ImageIcon; public class Acerca_de extends JFrame { private JPanel contentPane; private JLabel lblCreadores; private JLabel lblSanyder; private JLabel lblDanielaValverde; private JLabel lblKevinLlauriLlauri; private JLabel lblFlorLecaAltamirano; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Acerca_de frame = new Acerca_de(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Acerca_de() { setIconImage(Toolkit.getDefaultToolkit().getImage(Acerca_de.class.getResource("/imagenes/Fondo2.jpg"))); setResizable(false); setTitle("Acerca de Ruta 21"); setFont(new Font("Times New Roman", Font.PLAIN, 15)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 335, 307); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JButton btnAtras = new JButton("Aceptar\t"); btnAtras.setBounds(115, 240, 89, 23); btnAtras.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Inicio atras = new Inicio(); atras.setVisible(true); dispose(); } }); contentPane.setLayout(null); contentPane.add(btnAtras); lblCreadores = new JLabel("Creadores:"); lblCreadores.setForeground(Color.WHITE); lblCreadores.setHorizontalAlignment(SwingConstants.CENTER); lblCreadores.setBounds(118, 11, 82, 23); lblCreadores.setFont(new Font("Times New Roman", Font.PLAIN, 17)); contentPane.add(lblCreadores); lblSanyder = new JLabel("Snayder Rosario Miranda"); lblSanyder.setForeground(Color.WHITE); lblSanyder.setHorizontalAlignment(SwingConstants.CENTER); lblSanyder.setBounds(59, 69, 201, 23); lblSanyder.setFont(new Font("Times New Roman", Font.PLAIN, 17)); contentPane.add(lblSanyder); lblDanielaValverde = new JLabel("David Vargas Dominguez"); lblDanielaValverde.setForeground(Color.WHITE); lblDanielaValverde.setHorizontalAlignment(SwingConstants.CENTER); lblDanielaValverde.setBounds(59, 91, 201, 23); lblDanielaValverde.setFont(new Font("Times New Roman", Font.PLAIN, 17)); contentPane.add(lblDanielaValverde); lblKevinLlauriLlauri = new JLabel("Ivan Moncada Rodriguez"); lblKevinLlauriLlauri.setForeground(Color.WHITE); lblKevinLlauriLlauri.setHorizontalAlignment(SwingConstants.CENTER); lblKevinLlauriLlauri.setBounds(59, 115, 201, 23); lblKevinLlauriLlauri.setFont(new Font("Times New Roman", Font.PLAIN, 17)); contentPane.add(lblKevinLlauriLlauri); lblFlorLecaAltamirano = new JLabel("Flor Lecca Altamirano"); lblFlorLecaAltamirano.setForeground(Color.WHITE); lblFlorLecaAltamirano.setHorizontalAlignment(SwingConstants.CENTER); lblFlorLecaAltamirano.setBounds(59, 138, 201, 23); lblFlorLecaAltamirano.setFont(new Font("Times New Roman", Font.PLAIN, 17)); contentPane.add(lblFlorLecaAltamirano); JLabel lblVersin = new JLabel("Versi\u00F3n: 3.0.240"); lblVersin.setForeground(Color.WHITE); lblVersin.setHorizontalAlignment(SwingConstants.CENTER); lblVersin.setFont(new Font("Times New Roman", Font.PLAIN, 17)); lblVersin.setBounds(97, 172, 124, 23); contentPane.add(lblVersin); JLabel lblContactoIcibertecedupe = new JLabel("Contacto: i201815535@cibertec.edu.pe"); lblContactoIcibertecedupe.setForeground(Color.WHITE); lblContactoIcibertecedupe.setHorizontalAlignment(SwingConstants.CENTER); lblContactoIcibertecedupe.setFont(new Font("Times New Roman", Font.PLAIN, 17)); lblContactoIcibertecedupe.setBounds(14, 206, 291, 23); contentPane.add(lblContactoIcibertecedupe); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(Acerca_de.class.getResource("/imagenes/Fondo2.jpg"))); lblNewLabel.setBounds(0, 0, 329, 278); contentPane.add(lblNewLabel); setLocationRelativeTo(null); } }
package com.xi.studyDemo; /** * Created by Administrator on 2016/3/8. */ class Person { public Person(){ System.out.println("this is a Person"); } protected int getPrice() { return 30; } }
package model; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import exceptions.LoseException; import processing.core.PApplet; public class Logic { private MainCharacter mc; private ArrayList<Car> cars; private ArrayList<Player> players; private ArrayList<Car> lane1; private ArrayList<Car> lane2; private ArrayList<Car> lane3; private ArrayList<Car> lane4; private ArrayList<Car> lane5; private ArrayList<Car> lane6; private DurationComparator dc; private PApplet app; private static Logic onlyInstance; private Logic(PApplet app) { cars= new ArrayList<>(); players=new ArrayList<>(); lane1= new ArrayList<>(); lane2= new ArrayList<>(); lane3= new ArrayList<>(); lane4= new ArrayList<>(); lane5= new ArrayList<>(); lane6= new ArrayList<>(); dc=new DurationComparator(); this.app=app; } public static Logic getInstance(PApplet app) { if(onlyInstance == null) { onlyInstance = new Logic(app); } return onlyInstance; } public void initializeElements(String[] input) { for (int i = 0; i < input.length; i++) { String[] atributes=input[i].split(","); String objectType= atributes[0].trim(); int dirVel= Integer.parseInt(atributes[1].trim()); int posX= Integer.parseInt(atributes[2].trim()); int posY= Integer.parseInt(atributes[3].trim()); if(objectType.equals("carro")) { int dir=0; if(dirVel<0) { dir=-1; }else { dir=1; } int vel= Math.abs(dirVel); addSingleCar(posX, posY, dir, vel); } if(objectType.equals("personaje")) { addMainCharacter(posX,posY); } } } private void addSingleCar(int posX, int posY, int dir, int vel) { Car c= new Car(posX,posY,dir,vel,app); switch(posY) { case 50: lane1.add(c); cars.add(c); break; case 150: lane2.add(c); cars.add(c); break; case 250: lane3.add(c); cars.add(c); break; case 350: lane4.add(c); cars.add(c); break; case 450: lane5.add(c); cars.add(c); break; case 550: lane6.add(c); cars.add(c); break; } } private void addMainCharacter(int posX, int posY) { mc= new MainCharacter(posX, posY, 0, 50, app); } //Generate Cars public void carGenerator() { int max=5; while(cars.size()<30) { int randomLane= (int) app.random(1,7); int randomX=(int) app.random(1,700); int vel= (int) app.random(1,5); switch(randomLane) { case 1: if(lane1.size()<max) { addSingleCar(randomX, 50, -1, vel); } break; case 2: if(lane2.size()<max) { addSingleCar(randomX, 150, 1, vel); } break; case 3: if(lane3.size()<max) { addSingleCar(randomX, 250, -1, vel); } break; case 4: if(lane4.size()<max) { addSingleCar(randomX, 350, -1, vel); } break; case 5: if(lane5.size()<max) { addSingleCar(randomX, 450, 1, vel); } break; case 6: if(lane6.size()<max) { addSingleCar(randomX, 550, -1, vel); } break; } } } public void drawElements() { for(int i=0;i<cars.size(); i++) { cars.get(i).draw(); Thread t1= new Thread(cars.get(i)); t1.start(); } mc.draw(); } public void moveCharacter(char key) { mc.move(key); } public void checkLose() throws LoseException{ switch(mc.getPosY()) { case 50: for (int i=0; i<lane1.size(); i++) { int x1=mc.getPosX(); int y1=mc.getPosY(); int x2=lane1.get(i).getPosX()+lane1.get(i).getWidth()/2; int y2=lane1.get(i).getPosY()+lane1.get(i).getHeight()/2; if (PApplet.dist(x1,y1 ,x2 , y2)<mc.getWidth()/2+lane1.get(i).getWidth()/2) { throw new LoseException(); } } break; case 150: for (int i=0; i<lane2.size(); i++) { int x1=mc.getPosX(); int y1=mc.getPosY(); int x2=lane2.get(i).getPosX()+lane2.get(i).getWidth()/2; int y2=lane2.get(i).getPosY()+lane2.get(i).getHeight()/2; if (PApplet.dist(x1,y1 ,x2 , y2)<mc.getWidth()/2+lane2.get(i).getWidth()/2) { throw new LoseException(); } } break; case 250: for (int i=0; i<lane3.size(); i++) { int x1=mc.getPosX(); int y1=mc.getPosY(); int x2=lane3.get(i).getPosX()+lane3.get(i).getWidth()/2; int y2=lane3.get(i).getPosY()+lane3.get(i).getHeight()/2; if (PApplet.dist(x1,y1 ,x2 , y2)<mc.getWidth()/2+lane3.get(i).getWidth()/2) { throw new LoseException(); } } break; case 350: for (int i=0; i<lane4.size(); i++) { int x1=mc.getPosX(); int y1=mc.getPosY(); int x2=lane4.get(i).getPosX()+lane4.get(i).getWidth()/2; int y2=lane4.get(i).getPosY()+lane4.get(i).getHeight()/2; if (PApplet.dist(x1,y1 ,x2 , y2)<mc.getWidth()/2+lane4.get(i).getWidth()/2) { throw new LoseException(); } } break; case 450: for (int i=0; i<lane5.size(); i++) { int x1=mc.getPosX(); int y1=mc.getPosY(); int x2=lane5.get(i).getPosX()+lane5.get(i).getWidth()/2; int y2=lane5.get(i).getPosY()+lane5.get(i).getHeight()/2; if (PApplet.dist(x1,y1 ,x2 , y2)<mc.getWidth()/2+lane5.get(i).getWidth()/2) { throw new LoseException(); } } break; case 550: for (int i=0; i<lane6.size(); i++) { int x1=mc.getPosX(); int y1=mc.getPosY(); int x2=lane6.get(i).getPosX()+lane6.get(i).getWidth()/2; int y2=lane6.get(i).getPosY()+lane6.get(i).getHeight()/2; if (PApplet.dist(x1,y1 ,x2 , y2)<mc.getWidth()/2+lane6.get(i).getWidth()/2) { throw new LoseException(); } } break; } } public boolean checkWin() { if(mc.getPosY()>=600) { return true; }else { return false; } } public void addPlayer(LocalDateTime dateTime, int gameTime) { Player p= new Player(dateTime,gameTime, app); players.add(p); } public void drawPlayers() { for (int i = 0; i < players.size(); i++) { players.get(i).draw(75+(i*25)); } } public void sortScores(int sort) { switch (sort) { case 1: Collections.sort(players); break; case 2: Collections.sort(players,dc); break; } } public void reset() { mc.setPosX(400); mc.setPosY(0); } }
/* * 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.http.converter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.Collection; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourceRegion; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.MediaTypeFactory; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.MimeTypeUtils; import org.springframework.util.StreamUtils; /** * Implementation of {@link HttpMessageConverter} that can write a single * {@link ResourceRegion} or Collections of {@link ResourceRegion ResourceRegions}. * * @author Brian Clozel * @author Juergen Hoeller * @author Sam Brannen * @since 4.3 */ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> { public ResourceRegionHttpMessageConverter() { super(MediaType.ALL); } @Override @SuppressWarnings("unchecked") protected MediaType getDefaultContentType(Object object) { Resource resource = null; if (object instanceof ResourceRegion resourceRegion) { resource = resourceRegion.getResource(); } else { Collection<ResourceRegion> regions = (Collection<ResourceRegion>) object; if (!regions.isEmpty()) { resource = regions.iterator().next().getResource(); } } return MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM); } @Override public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) { return false; } @Override public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable MediaType mediaType) { return false; } @Override public Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { throw new UnsupportedOperationException(); } @Override protected ResourceRegion readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { throw new UnsupportedOperationException(); } @Override public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) { return canWrite(clazz, null, mediaType); } @Override public boolean canWrite(@Nullable Type type, @Nullable Class<?> clazz, @Nullable MediaType mediaType) { if (!(type instanceof ParameterizedType parameterizedType)) { return (type instanceof Class<?> c && ResourceRegion.class.isAssignableFrom(c)); } if (!(parameterizedType.getRawType() instanceof Class<?> rawType)) { return false; } if (!(Collection.class.isAssignableFrom(rawType))) { return false; } if (parameterizedType.getActualTypeArguments().length != 1) { return false; } Type typeArgument = parameterizedType.getActualTypeArguments()[0]; if (!(typeArgument instanceof Class<?> typeArgumentClass)) { return false; } return ResourceRegion.class.isAssignableFrom(typeArgumentClass); } @Override @SuppressWarnings("unchecked") protected void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (object instanceof ResourceRegion resourceRegion) { writeResourceRegion(resourceRegion, outputMessage); } else { Collection<ResourceRegion> regions = (Collection<ResourceRegion>) object; if (regions.size() == 1) { writeResourceRegion(regions.iterator().next(), outputMessage); } else { writeResourceRegionCollection(regions, outputMessage); } } } protected void writeResourceRegion(ResourceRegion region, HttpOutputMessage outputMessage) throws IOException { Assert.notNull(region, "ResourceRegion must not be null"); HttpHeaders responseHeaders = outputMessage.getHeaders(); long start = region.getPosition(); long end = start + region.getCount() - 1; long resourceLength = region.getResource().contentLength(); end = Math.min(end, resourceLength - 1); long rangeLength = end - start + 1; responseHeaders.add("Content-Range", "bytes " + start + '-' + end + '/' + resourceLength); responseHeaders.setContentLength(rangeLength); InputStream in = region.getResource().getInputStream(); // We cannot use try-with-resources here for the InputStream, since we have // custom handling of the close() method in a finally-block. try { StreamUtils.copyRange(in, outputMessage.getBody(), start, end); } finally { try { in.close(); } catch (IOException ex) { // ignore } } } private void writeResourceRegionCollection(Collection<ResourceRegion> resourceRegions, HttpOutputMessage outputMessage) throws IOException { Assert.notNull(resourceRegions, "Collection of ResourceRegion should not be null"); HttpHeaders responseHeaders = outputMessage.getHeaders(); MediaType contentType = responseHeaders.getContentType(); String boundaryString = MimeTypeUtils.generateMultipartBoundaryString(); responseHeaders.set(HttpHeaders.CONTENT_TYPE, "multipart/byteranges; boundary=" + boundaryString); OutputStream out = outputMessage.getBody(); Resource resource = null; InputStream in = null; long inputStreamPosition = 0; try { for (ResourceRegion region : resourceRegions) { long start = region.getPosition() - inputStreamPosition; if (start < 0 || resource != region.getResource()) { if (in != null) { in.close(); } resource = region.getResource(); in = resource.getInputStream(); inputStreamPosition = 0; start = region.getPosition(); } long end = start + region.getCount() - 1; // Writing MIME header. println(out); print(out, "--" + boundaryString); println(out); if (contentType != null) { print(out, "Content-Type: " + contentType); println(out); } long resourceLength = region.getResource().contentLength(); end = Math.min(end, resourceLength - inputStreamPosition - 1); print(out, "Content-Range: bytes " + region.getPosition() + '-' + (region.getPosition() + region.getCount() - 1) + '/' + resourceLength); println(out); println(out); // Printing content StreamUtils.copyRange(in, out, start, end); inputStreamPosition += (end + 1); } } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore } } println(out); print(out, "--" + boundaryString + "--"); } private static void println(OutputStream os) throws IOException { os.write('\r'); os.write('\n'); } private static void print(OutputStream os, String buf) throws IOException { os.write(buf.getBytes(StandardCharsets.US_ASCII)); } }
package com.metoo.foundation.domain; /** * * <p> * Title: LogType.java * </p> * * <p> * Description:日志类型枚举类型,系统未过多使用,可不比关注,特殊又需要的可以使用该类 * </p> * * <p> * Copyright: Copyright (c) 2014 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-4-25 * * @version koala_b2b2c v2.0 2015版 */ public enum LogType { SAVE, REMOVE, LIST, VIEW, LOGIN, LOGOUT, RESTORE, IMPORT, SEND, UPDATEPWS, ROLE }
/** * This class is generated by jOOQ */ package schema.tables.records; import java.sql.Timestamp; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record7; import org.jooq.Row7; import org.jooq.impl.UpdatableRecordImpl; import schema.tables.StudentManualenrollmentaudit; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class StudentManualenrollmentauditRecord extends UpdatableRecordImpl<StudentManualenrollmentauditRecord> implements Record7<Integer, String, Timestamp, String, String, Integer, Integer> { private static final long serialVersionUID = -1432331087; /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.id</code>. */ public void setId(Integer value) { set(0, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.enrolled_email</code>. */ public void setEnrolledEmail(String value) { set(1, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.enrolled_email</code>. */ public String getEnrolledEmail() { return (String) get(1); } /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.time_stamp</code>. */ public void setTimeStamp(Timestamp value) { set(2, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.time_stamp</code>. */ public Timestamp getTimeStamp() { return (Timestamp) get(2); } /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.state_transition</code>. */ public void setStateTransition(String value) { set(3, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.state_transition</code>. */ public String getStateTransition() { return (String) get(3); } /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.reason</code>. */ public void setReason(String value) { set(4, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.reason</code>. */ public String getReason() { return (String) get(4); } /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.enrolled_by_id</code>. */ public void setEnrolledById(Integer value) { set(5, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.enrolled_by_id</code>. */ public Integer getEnrolledById() { return (Integer) get(5); } /** * Setter for <code>bitnami_edx.student_manualenrollmentaudit.enrollment_id</code>. */ public void setEnrollmentId(Integer value) { set(6, value); } /** * Getter for <code>bitnami_edx.student_manualenrollmentaudit.enrollment_id</code>. */ public Integer getEnrollmentId() { return (Integer) get(6); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record7 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row7<Integer, String, Timestamp, String, String, Integer, Integer> fieldsRow() { return (Row7) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row7<Integer, String, Timestamp, String, String, Integer, Integer> valuesRow() { return (Row7) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.ENROLLED_EMAIL; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field3() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.TIME_STAMP; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.STATE_TRANSITION; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.REASON; } /** * {@inheritDoc} */ @Override public Field<Integer> field6() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.ENROLLED_BY_ID; } /** * {@inheritDoc} */ @Override public Field<Integer> field7() { return StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT.ENROLLMENT_ID; } /** * {@inheritDoc} */ @Override public Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public String value2() { return getEnrolledEmail(); } /** * {@inheritDoc} */ @Override public Timestamp value3() { return getTimeStamp(); } /** * {@inheritDoc} */ @Override public String value4() { return getStateTransition(); } /** * {@inheritDoc} */ @Override public String value5() { return getReason(); } /** * {@inheritDoc} */ @Override public Integer value6() { return getEnrolledById(); } /** * {@inheritDoc} */ @Override public Integer value7() { return getEnrollmentId(); } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value1(Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value2(String value) { setEnrolledEmail(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value3(Timestamp value) { setTimeStamp(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value4(String value) { setStateTransition(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value5(String value) { setReason(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value6(Integer value) { setEnrolledById(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord value7(Integer value) { setEnrollmentId(value); return this; } /** * {@inheritDoc} */ @Override public StudentManualenrollmentauditRecord values(Integer value1, String value2, Timestamp value3, String value4, String value5, Integer value6, Integer value7) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached StudentManualenrollmentauditRecord */ public StudentManualenrollmentauditRecord() { super(StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT); } /** * Create a detached, initialised StudentManualenrollmentauditRecord */ public StudentManualenrollmentauditRecord(Integer id, String enrolledEmail, Timestamp timeStamp, String stateTransition, String reason, Integer enrolledById, Integer enrollmentId) { super(StudentManualenrollmentaudit.STUDENT_MANUALENROLLMENTAUDIT); set(0, id); set(1, enrolledEmail); set(2, timeStamp); set(3, stateTransition); set(4, reason); set(5, enrolledById); set(6, enrollmentId); } }
package net.lantrack.framework.sysbase.entity; import java.io.Serializable; import java.util.Date; /** * 登录信息 * @date 2019年1月17日 */ public class LoginInfo implements Serializable { /** * 登录名 */ private String loginName; /** * 账户是否被禁用(0否1是) */ private String ifForbidden="0"; /** * 是否锁定(0否1是) */ private String ifLock="0"; /** * 开始锁定时间 */ private Date lockStartTime; /** * 账户应解锁时间 */ private Date lockEndTime; /** * 登录失败次数 */ private Integer errCount = 0; /** * 最后一次登录成功时间 */ private Date lastSucTime; /** * 最后一次登录成功地址 */ private String lastSucAddress; /** * 最后一次登录成功ip */ private String lastSucIp; /** * 最后一次登录成功设备(app,pc) */ private String lastDevice; /** * 发送验证码时间 */ private Date sendmsgTime; /** * 验证码有效期结束时间 */ private Date endmsgTime; /** * 短信验证码 */ private String msgCode; /** * 扫描二维码登录状态(0未登录1已登录) */ private String stand1; /** * 扫描二维码成功后返回确认认证信息 */ private String stand2; private String stand3; private String stand4; private String stand5; private String stand6; private static final long serialVersionUID = 1L; public LoginInfo(String loginName, String ifForbidden, String ifLock, Date lockStartTime, Date lockEndTime, Integer errCount, Date lastSucTime, String lastSucAddress, String lastSucIp, String lastDevice, Date sendmsgTime, Date endmsgTime, String msgCode, String stand1, String stand2, String stand3, String stand4, String stand5, String stand6) { this.loginName = loginName; this.ifForbidden = ifForbidden; this.ifLock = ifLock; this.lockStartTime = lockStartTime; this.lockEndTime = lockEndTime; this.errCount = errCount; this.lastSucTime = lastSucTime; this.lastSucAddress = lastSucAddress; this.lastSucIp = lastSucIp; this.lastDevice = lastDevice; this.sendmsgTime = sendmsgTime; this.endmsgTime = endmsgTime; this.msgCode = msgCode; this.stand1 = stand1; this.stand2 = stand2; this.stand3 = stand3; this.stand4 = stand4; this.stand5 = stand5; this.stand6 = stand6; } public LoginInfo() { super(); } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName == null ? null : loginName.trim(); } public String getIfForbidden() { return ifForbidden; } public void setIfForbidden(String ifForbidden) { this.ifForbidden = ifForbidden == null ? null : ifForbidden.trim(); } public String getIfLock() { return ifLock; } public void setIfLock(String ifLock) { this.ifLock = ifLock == null ? null : ifLock.trim(); } public Date getLockStartTime() { return lockStartTime; } public void setLockStartTime(Date lockStartTime) { this.lockStartTime = lockStartTime; } public Date getLockEndTime() { return lockEndTime; } public void setLockEndTime(Date lockEndTime) { this.lockEndTime = lockEndTime; } public Integer getErrCount() { return errCount; } public void errCount(Integer errCount) { this.errCount = errCount; } public Date getLastSucTime() { return lastSucTime; } public void setLastSucTime(Date lastSucTime) { this.lastSucTime = lastSucTime; } public String getLastSucAddress() { return lastSucAddress; } public void setLastSucAddress(String lastSucAddress) { this.lastSucAddress = lastSucAddress == null ? null : lastSucAddress.trim(); } public String getLastSucIp() { return lastSucIp; } public void setLastSucIp(String lastSucIp) { this.lastSucIp = lastSucIp == null ? null : lastSucIp.trim(); } public String getLastDevice() { return lastDevice; } public void setLastDevice(String lastDevice) { this.lastDevice = lastDevice == null ? null : lastDevice.trim(); } public Date getSendmsgTime() { return sendmsgTime; } public void setSendmsgTime(Date sendmsgTime) { this.sendmsgTime = sendmsgTime; } public Date getEndmsgTime() { return endmsgTime; } public void setEndmsgTime(Date endmsgTime) { this.endmsgTime = endmsgTime; } public String getMsgCode() { return msgCode; } public void setMsgCode(String msgCode) { this.msgCode = msgCode == null ? null : msgCode.trim(); } public String getStand1() { return stand1; } public void setStand1(String stand1) { this.stand1 = stand1 == null ? null : stand1.trim(); } public String getStand2() { return stand2; } public void setStand2(String stand2) { this.stand2 = stand2 == null ? null : stand2.trim(); } public String getStand3() { return stand3; } public void setStand3(String stand3) { this.stand3 = stand3 == null ? null : stand3.trim(); } public String getStand4() { return stand4; } public void setStand4(String stand4) { this.stand4 = stand4 == null ? null : stand4.trim(); } public String getStand5() { return stand5; } public void setStand5(String stand5) { this.stand5 = stand5 == null ? null : stand5.trim(); } public String getStand6() { return stand6; } public void setStand6(String stand6) { this.stand6 = stand6 == null ? null : stand6.trim(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", loginName=").append(loginName); sb.append(", ifForbidden=").append(ifForbidden); sb.append(", ifLock=").append(ifLock); sb.append(", lockStartTime=").append(lockStartTime); sb.append(", lockEndTime=").append(lockEndTime); sb.append(", errCount=").append(errCount); sb.append(", lastSucTime=").append(lastSucTime); sb.append(", lastSucAddress=").append(lastSucAddress); sb.append(", lastSucIp=").append(lastSucIp); sb.append(", lastDevice=").append(lastDevice); sb.append(", sendmsgTime=").append(sendmsgTime); sb.append(", endmsgTime=").append(endmsgTime); sb.append(", msgCode=").append(msgCode); sb.append(", stand1=").append(stand1); sb.append(", stand2=").append(stand2); sb.append(", stand3=").append(stand3); sb.append(", stand4=").append(stand4); sb.append(", stand5=").append(stand5); sb.append(", stand6=").append(stand6); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package com.entse.testcases; import com.entse.base.Page; import com.entse.pages.actions.SignInPage; import com.entse.utilities.Utilities; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.Hashtable; public class SignInTest { @Test(dataProviderClass = Utilities.class, dataProvider = "dp") public void signInTest(Hashtable<String, String> data) { if(data.get("runmode").equalsIgnoreCase("N")){ throw new SkipException("Skipping the test cause the RunMode is set to NO"); } Page.initConfiguration(); SignInPage signInPage = Page.topNav.gotoSignIn(); signInPage.doLogin(data.get("username"), data.get("password")); } @AfterMethod public void tearDown(){ if(Page.driver != null) { Page.quitBrowser(); } } }
package collection; import org.junit.Before; import org.junit.Test; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Iterator; import java.util.Properties; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; public class PropertiesTest { private final String PATH_PROPERTIES = "output/properties.properties"; private final String PATH_PROPERTIES_XML = "output/properties.xml"; @Before public void cleanUp(){ try { Files.deleteIfExists(Paths.get(PATH_PROPERTIES)); Files.deleteIfExists(Paths.get(PATH_PROPERTIES_XML)); } catch (IOException e) { e.printStackTrace(); } } @Test public void createProperties(){ Properties profile = generateProfileProperties(); assertThat(profile.size(), equalTo(3)); } @Test public void findSizeWithIterator(){ Properties profile = generateProfileProperties(); Iterator<Object> it = profile.keySet().iterator(); int size = 0; while(it.hasNext()){ it.next(); size++; } assertThat(profile.size(), equalTo(size)); } @Test public void shouldGetDefaultValue(){ Properties profile = generateProfileProperties(); String actualAge = profile.getProperty("age", "unknown"); assertThat(actualAge, equalTo("unknown")); } @Test public void shouldStorePropertiesInFile(){ createPropertiesFile(); propertiesFileContainsPropertyValue("name", "John Doe"); propertiesFileContainsPropertyValue("phone", "5141234567"); propertiesFileContainsPropertyValue("gender", "male"); } @Test public void readPropertiesFromFile(){ createPropertiesFile(); Properties profile = new Properties(); try { profile.load(new FileReader(PATH_PROPERTIES)); } catch (IOException e) { e.printStackTrace(); } assertThat(profile.getProperty("name"), equalTo("John Doe")); assertThat(profile.getProperty("phone"), equalTo("5141234567")); assertThat(profile.getProperty("gender"), equalTo("male")); } @Test public void shouldStorePropertiesInXmlFile(){ createPropertiesXmlFile(); propertiesFileContainsPropertyValueXml("name", "John Doe"); propertiesFileContainsPropertyValueXml("phone", "5141234567"); propertiesFileContainsPropertyValueXml("gender", "male"); } @Test public void readPropertiesFromXmlFile(){ createPropertiesXmlFile(); Properties profile = new Properties(); try { profile.loadFromXML(new FileInputStream(PATH_PROPERTIES_XML)); } catch (IOException e) { e.printStackTrace(); } assertThat(profile.getProperty("name"), equalTo("John Doe")); assertThat(profile.getProperty("phone"), equalTo("5141234567")); assertThat(profile.getProperty("gender"), equalTo("male")); } private void createPropertiesFile() { Properties profile = generateProfileProperties(); try { FileWriter output = new FileWriter(PATH_PROPERTIES); profile.store(output, "comments"); }catch (Exception e){ e.printStackTrace(); } } private void createPropertiesXmlFile() { Properties profile = generateProfileProperties(); try { FileOutputStream output = new FileOutputStream(PATH_PROPERTIES_XML); profile.storeToXML(output, "comments"); }catch (Exception e){ e.printStackTrace(); } } private void propertiesFileContainsPropertyValue(String property, String value){ try { String fileContent = new String(Files.readAllBytes(Paths.get(PATH_PROPERTIES))); assertThat(fileContent, containsString(property + "=" + value)); } catch (IOException e) { e.printStackTrace(); } } private void propertiesFileContainsPropertyValueXml(String property, String value){ String entry = String.format("<entry key=\"%s\">%s</entry>", property, value); try { String fileContent = new String(Files.readAllBytes(Paths.get(PATH_PROPERTIES_XML))); assertThat(fileContent, containsString(entry)); } catch (IOException e) { e.printStackTrace(); } } private Properties generateProfileProperties() { Properties profile = new Properties(); profile.setProperty("name", "John Doe"); profile.setProperty("phone", "5141234567"); profile.setProperty("gender", "male"); return profile; } }
package com.example.blog; import java.util.ArrayList; import javax.servlet.annotation.WebServlet; import com.example.blog.Broadcaster.BroadcastListener; import com.example.blog.model.Post; import com.example.blog.model.User; import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.navigator.Navigator; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.ui.UI; @SuppressWarnings("serial") @Theme("blog") @Push public class BlogUI extends UI implements BroadcastListener { private static final ArrayList<User> users = new ArrayList<>(); private Navigator navigator; // views private PostsView posts; @WebServlet(value = "/*", asyncSupported = true) @VaadinServletConfiguration(productionMode = false, ui = BlogUI.class) public static class Servlet extends VaadinServlet { } @Override protected void init(VaadinRequest request) { Broadcaster.register(this); navigator = new Navigator(this, this); navigator.addView(RegisterView.REGISTER_VIEW, new RegisterView(this)); posts = new PostsView(users, navigator); navigator.addView(LoginView.LOGIN_VIEW, new LoginView(this)); navigator.addView(PostsView.POSTS_VIEW, posts); navigator.addView(AddPostView.ADD_POST_VIEW, new AddPostView(this)); navigator.navigateTo(PostsView.POSTS_VIEW); } @Override public void registerUser(User user) { users.add(user); System.out.println("ADDED USER " + users.size()); } public ArrayList<User> getUsers() { return users; } @Override public void addPost(Post post, User owner) { access(new Runnable() { @Override public void run() { if (getSession().getCurrent().getAttribute("userName") == null) { posts.addPost(post, owner); return; } if (getSession().getCurrent().getAttribute("userName") != null && !((String) (getSession().getCurrent().getAttribute("userName"))).equals(owner.getName()) ) { posts.addPost(post, owner); } } }); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package network; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * * @author dimitriv */ public class Reservation implements Comparable<Reservation> { Node sender; Set<Node> blocked = new HashSet<>(); Slot slot; @Override public String toString () { String result = "Sender: " + sender+" blocked: "; result += Arrays.toString(blocked.toArray()); return result; } @Override public int compareTo(Reservation o) { return Integer.valueOf(this.blocked.size()).compareTo(o.blocked.size()); } }
package com.citibank.ods.entity.pl.valueobject; import java.util.Date; /** * @author m.nakamura * * Representação da tabela de histórico de contrato. */ public class To3ProductAccountHistEntityVO extends BaseTo3ProductAccountEntityVO { // Data de referência do registro no histórico private Date m_prodAcctRefDate = null; /** * Seta a data de referência do registro no histórico * * @param prodAcctRefDate_ - A data de referência do registro no histórico */ public void setProdAcctRefDate( Date prodAcctRefDate_ ) { m_prodAcctRefDate = prodAcctRefDate_; } /** * Recupera a data de referência do registro no histórico * * @return Date - Retorna a data de referência do registro no histórico */ public Date getProdAcctRefDate() { return m_prodAcctRefDate; } }
package com.healthmarketscience.jackcess.scsu; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /* * This sample software accompanies Unicode Technical Report #6 and * distributed as is by Unicode, Inc., subject to the following: * * Copyright 1996-1997 Unicode, Inc.. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * without fee is hereby granted provided that this copyright notice * appears in all copies. * * UNICODE, INC. MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * UNICODE, INC., SHALL NOT BE LIABLE FOR ANY ERRORS OR OMISSIONS, AND * SHALL NOT BE LIABLE FOR ANY DAMAGES, INCLUDING CONSEQUENTIAL AND * INCIDENTAL DAMAGES, SUFFERED BY YOU AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. * * @author Asmus Freytag * * @version 001 Dec 25 1996 * @version 002 Jun 25 1997 * @version 003 Jul 25 1997 * @version 004 Aug 25 1997 * * Unicode and the Unicode logo are trademarks of Unicode, Inc., * and are registered in some jurisdictions. **/ /** * A number of helpful output routines for debugging. Output can be * centrally enabled or disabled by calling Debug.set(true/false); * All methods are statics; */ public class Debug { private static final Log LOG = LogFactory.getLog(Debug.class); // debugging helper public static void out(char [] chars) { out(chars, 0); } public static void out(char [] chars, int iStart) { if (!LOG.isDebugEnabled()) return; StringBuilder msg = new StringBuilder(); for (int i = iStart; i < chars.length; i++) { if (chars[i] >= 0 && chars[i] <= 26) { msg.append("^"+(char)(chars[i]+0x40)); } else if (chars[i] <= 255) { msg.append(chars[i]); } else { msg.append("\\u"+Integer.toString(chars[i],16)); } } LOG.debug(msg.toString()); } public static void out(byte [] bytes) { out(bytes, 0); } public static void out(byte [] bytes, int iStart) { if (!LOG.isDebugEnabled()) return; StringBuilder msg = new StringBuilder(); for (int i = iStart; i < bytes.length; i++) { msg.append(bytes[i]+","); } LOG.debug(msg.toString()); } public static void out(String str) { if (!LOG.isDebugEnabled()) return; LOG.debug(str); } public static void out(String msg, int iData) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg + iData); } public static void out(String msg, char ch) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg + "[U+"+Integer.toString(ch,16)+"]" + ch); } public static void out(String msg, byte bData) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg + bData); } public static void out(String msg, String str) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg + str); } public static void out(String msg, char [] data) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg); out(data); } public static void out(String msg, byte [] data) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg); out(data); } public static void out(String msg, char [] data, int iStart) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg +"("+iStart+"): "); out(data, iStart); } public static void out(String msg, byte [] data, int iStart) { if (!LOG.isDebugEnabled()) return; LOG.debug(msg+"("+iStart+"): "); out(data, iStart); } }
package com.example.tecomca.mylogin_seccion05.Activities; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.tecomca.mylogin_seccion05.Model.User; import com.example.tecomca.mylogin_seccion05.R; import com.example.tecomca.mylogin_seccion05.Sql.DatabaseHelper; //import com.google.android.gms.tasks.OnCompleteListener; //import com.google.android.gms.tasks.Task; //import com.google.firebase.auth.AuthResult; //import com.google.firebase.auth.FirebaseAuth; import org.w3c.dom.Text; public class RegisterActivity extends AppCompatActivity implements View.OnClickListener { private EditText mEmailField, mPassField, mNameField; private Button mRegisterBtn; private Button mBackBtn; private int tipo; private DatabaseHelper databaseHelper; private User user; // private FirebaseAuth mAuth; // // private FirebaseAuth.AuthStateListener mAuthListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); initViews(); initListeners(); initObjects(); } // protected void onStart(){ // super.onStart(); // // mAuth.addAuthStateListener(mAuthListener); // } // // private void startSingUp(){ // String email = mEmailField.getText().toString(); // String password = mPassField.getText().toString(); // // if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) { // Toast.makeText(RegisterActivity.this, "Campos estan vacios", Toast.LENGTH_SHORT).show(); // } else { // mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { // @Override // public void onComplete(@NonNull Task<AuthResult> task) { // if (!task.isSuccessful()) { // Toast.makeText(RegisterActivity.this, "Problemas al registrar", Toast.LENGTH_SHORT).show(); // } // } // }); // } // } private void initViews(){ mEmailField = (EditText) findViewById(R.id.editTextEmail); mPassField = (EditText) findViewById(R.id.editTextPass); mNameField = (EditText) findViewById(R.id.editTextName); mRegisterBtn = (Button) findViewById(R.id.btnRegister); mBackBtn = (Button) findViewById(R.id.btnBack); } private void initListeners(){ mRegisterBtn.setOnClickListener(this); mBackBtn.setOnClickListener(this); } private void initObjects(){ databaseHelper = new DatabaseHelper(RegisterActivity.this); user = new User(); } @Override public void onClick(View v){ switch (v.getId()){ case R.id.btnRegister: //Toast.makeText(RegisterActivity.this, "Algun dia funcionara XD", Toast.LENGTH_SHORT).show(); postDataToSQLite(); break; case R.id.btnBack: // los onclick de los listener como estan arriba Intent intentRegister = new Intent(RegisterActivity.this,MainActivity.class); startActivity(intentRegister); break; } } private boolean login(String email, String password) { if (!isValidEmail(email)){ Toast.makeText(this, "Email is not valid, please try again", Toast.LENGTH_LONG).show(); return false; } else if (!isValidPassword(password)){ Toast.makeText(this, "Password is not valid, 4 characters or more, please try again", Toast.LENGTH_LONG).show(); return false; } else { return true; } } private boolean isValidEmail(String email) { return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches(); } private boolean isValidPassword (String password) { return password.length() >= 4; } private void postDataToSQLite(){ String email = mEmailField.getText().toString().trim(); String password = mPassField.getText().toString().trim(); String name = mNameField.getText().toString().trim(); tipo = 2; if (login(email, password)) { // goToMain(); if (!databaseHelper.checkUser(email)){ user.setName(name); user.setEmail(email); user.setPassword(password); user.setType(tipo); databaseHelper.addUser(user); Toast.makeText(this, "El registro de usuario satisfactorio", Toast.LENGTH_LONG).show(); emptyInputEditText(); }else{ Toast.makeText(this, "El email ya existe", Toast.LENGTH_LONG).show(); } } } private void emptyInputEditText(){ mEmailField.setText(null); mPassField.setText(null); mNameField.setText(null); } }
package com.test.base; import java.util.List; /** * Given a binary tree and a sum, find all root-to-leaf paths * where each path's sum equals the given sum. * * 有一个二叉树和目标值,有从 root-leaf的路径,满足,节点值的和等于目标值;全部找到 * * @author YLine * * 2018年11月27日 下午7:36:54 */ public interface Solution { public List<List<Integer>> pathSum(TreeNode root, int sum); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package PO; /** * * @author QueroDelivery */ public class estabelecimento { private int cod_estab; private String nom_estab; public int getCod_estab() { return cod_estab; } public void setCod_estab(int cod_estab) { this.cod_estab = cod_estab; } public String getNom_estab() { return nom_estab; } public void setNom_estab(String nom_estab) { this.nom_estab = nom_estab; } @Override public String toString() { return "estabelecimento{" + "cod_estab=" + cod_estab + ", nom_estab=" + nom_estab + '}'; } }
package pro.likada.rest.wrapper.autograph; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by abuca on 24.03.17. */ public class RPointWrapper { @JsonProperty("Lat") private Double latitude; @JsonProperty("Lng") private Double longitude; public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } }
package org.shujito.cartonbox.controller.task; import java.io.InputStream; import org.shujito.cartonbox.model.parser.GelbooruTagsParser; import org.shujito.cartonbox.model.parser.XmlParser; public class GelbooruTagsDownloader extends XmlDownloader { public GelbooruTagsDownloader(String url) { super(url); } @Override public XmlParser<?> parse(InputStream is) throws Exception { return new GelbooruTagsParser(is); } @Override public XmlParser<?> parseError(InputStream is) throws Exception { return null; } }
/* * Copyright 2002-2016 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.testfixture.servlet; import java.io.IOException; import java.io.OutputStream; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.WriteListener; import org.springframework.util.Assert; /** * Delegating implementation of {@link jakarta.servlet.ServletOutputStream}. * * <p>Used by {@link MockHttpServletResponse}; typically not directly * used for testing application controllers. * * @author Juergen Hoeller * @since 1.0.2 * @see MockHttpServletResponse */ public class DelegatingServletOutputStream extends ServletOutputStream { private final OutputStream targetStream; /** * Create a DelegatingServletOutputStream for the given target stream. * @param targetStream the target stream (never {@code null}) */ public DelegatingServletOutputStream(OutputStream targetStream) { Assert.notNull(targetStream, "Target OutputStream must not be null"); this.targetStream = targetStream; } /** * Return the underlying target stream (never {@code null}). */ public final OutputStream getTargetStream() { return this.targetStream; } @Override public void write(int b) throws IOException { this.targetStream.write(b); } @Override public void flush() throws IOException { super.flush(); this.targetStream.flush(); } @Override public void close() throws IOException { super.close(); this.targetStream.close(); } @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener writeListener) { throw new UnsupportedOperationException(); } }
package Bean; import java.util.LinkedList; import java.util.Queue; import java.util.Vector; /** * @author dmrfcoder * @date 2019-04-15 */ public class Memory { private double memorySize; private final Vector<Message> messageVector; private volatile double curSize; public double getMemoryPercentage() { if (memorySize - curSize < 0.5) { return 100; } return (curSize / memorySize) * 100; } public int getMemoryCurCount() { return messageVector.size(); } public Message getMessage() { if (messageVector.size() == 0) { return null; } else { Message message = messageVector.lastElement(); return message; } } public Vector<Message> getMessageVector() { return messageVector; } public boolean removeMessageFromMemory(Message message) { synchronized (messageVector) { if (messageVector.contains(message)) { messageVector.remove(message); curSize -= message.getContent().length(); return true; } } return false; } /** * @param memorySize :默认传入的单位为M,需要将其转化为字节。 */ public Memory(double memorySize) { this.memorySize = memorySize * 1024 * 1024; this.messageVector = new Vector<>(); this.curSize = 0; } public boolean addContentToMemory(Message message) { if (curSize < memorySize) { messageVector.add(message); curSize += message.getContent().length(); return true; } else { return false; } } }