text
stringlengths
10
2.72M
/* Count the number of prime numbers less than a non-negative number, n. */ public int countPrimes(int n) { boolean[] isPrime = new boolean[n]; for (int i=2;i<n;i++){ isPrime[i]=true; } //mark off prime's multiples because they are not prime numbers for (int i=2;i*i<n;i++){ if (!isPrime[i]) continue; for (int j=i*i;j<n;j+=i){ isPrime[j]=false; } } //count prime number in total int count=0; for (int i=2;i<n;i++){ if (isPrime[i]) count++; } return count; } /*public int countPrimes(int n) { int count=0 for (int i=1;i<n;i++){ if (isPrime(i))count++; } return count; } public boolean isPrime(int number){ if (number==0 || number==1) return false; for (int i=2;i*i<=number;i++){ if (number%i==0) return false; } return true; }*/
package com.jeffdisher.thinktank.crypto; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * Helpers related to cryptographic signing and verification. * Further reading for broader context or understanding (much of this class was created by looking at these sources): * -Java signatures and verification: http://tutorials.jenkov.com/java-cryptography/signature.html * -Standard crypto algorithm names: https://docs.oracle.com/javase/9/docs/specs/security/standard-names.html * -deserializing keys: https://exceptionshub.com/how-to-recover-a-rsa-public-key-from-a-byte-array.html */ public class CryptoHelpers { private static final String KEY_ALGORITHM = "EC"; private static final String SIGNATURE_ALGORITHM = "SHA512withECDSA"; private static final SecureRandom RANDOM = new SecureRandom(); private static final KeyFactory KEY_FACTORY; static { try { KEY_FACTORY = KeyFactory.getInstance(KEY_ALGORITHM); } catch (NoSuchAlgorithmException e) { // This is a static config error. throw new AssertionError(e); } } /** * @return A randomly generated key pair in the default EC curve. */ public static KeyPair generateRandomKeyPair() { // We just use the default EC spec with 112-bit keys (just since we want them small). KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); } catch (NoSuchAlgorithmException e) { // This is a static config error. throw _noSuchAlgorithm(KEY_ALGORITHM, e); } keyPairGenerator.initialize(112, RANDOM); return keyPairGenerator.generateKeyPair(); } /** * @param key The public key to serialize. * @return The key, serialized using X509 encoding. */ public static byte[] serializePublic(PublicKey key) { if (null == key) { throw new NullPointerException(); } return key.getEncoded(); } /** * @param bytes An EC public key encoded as X509. * @return The public key (null if there was an error decoding). */ public static PublicKey deserializePublic(byte[] bytes) { if (null == bytes) { throw new NullPointerException(); } PublicKey key; try { key = KEY_FACTORY.generatePublic(new X509EncodedKeySpec(bytes)); } catch (InvalidKeySpecException e) { // This is an error in the key. key = null; } return key; } /** * @param key The private key to serialize. * @return The key, serialized using PKCS8 encoding. */ public static byte[] serializePrivate(PrivateKey key) { if (null == key) { throw new NullPointerException(); } return key.getEncoded(); } /** * @param bytes An EC private key encoded as PKCS8. * @return The private key (null if there was an error decoding). */ public static PrivateKey deserializePrivate(byte[] bytes) { if (null == bytes) { throw new NullPointerException(); } PrivateKey key; try { key = KEY_FACTORY.generatePrivate(new PKCS8EncodedKeySpec(bytes)); } catch (InvalidKeySpecException e) { // This is an error in the key. key = null; } return key; } /** * Generates a cryptographic signature of the given message signed with the given private key. * * @param key An EC private key. * @param message The message to sign. * @return The cryptographic signature, in ASN.1 DER encoding. */ public static byte[] sign(PrivateKey key, byte[] message) { if ((null == key) || (null == message)) { throw new NullPointerException(); } Signature signature; try { signature = Signature.getInstance(SIGNATURE_ALGORITHM); } catch (NoSuchAlgorithmException e) { // This is a static config error. throw _noSuchAlgorithm(SIGNATURE_ALGORITHM, e); } byte[] serialized; try { signature.initSign(key, RANDOM); signature.update(message); serialized = signature.sign(); } catch (InvalidKeyException e) { // This is an error in the key. serialized = null; } catch (SignatureException e) { // This can't happen since we are initializing the signature right here. throw new AssertionError("Unexpected exception", e); } return serialized; } /** * Verifies that the signature provided was generated from the given message by the private key associated with the * given public key. * * @param key An EC public key. * @param message The message presumably signed. * @param signature The signature derived from the message (encoded as ASN.1 DER). * @return True if the signature was generated from this message using the private key associated with the given * public key. */ public static boolean verify(PublicKey key, byte[] message, byte[] signature) { if ((null == key) || (null == message) || (null == signature)) { throw new NullPointerException(); } Signature verify; try { verify = Signature.getInstance(SIGNATURE_ALGORITHM); } catch (NoSuchAlgorithmException e) { // This is a static config error. throw _noSuchAlgorithm(SIGNATURE_ALGORITHM, e); } boolean verified; try { verify.initVerify(key); verify.update(message); verified = verify.verify(signature); } catch (InvalidKeyException e) { // This is an error in the key. verified = false; } catch (SignatureException e) { // This is how a failure appears if the signature was just corrupted. verified = false; } return verified; } private static RuntimeException _noSuchAlgorithm(String name, NoSuchAlgorithmException e) { throw new AssertionError("Missing required crypto algorith: " + name, e); } }
package com.example.kuno.intentmultiex; import android.app.Activity; import android.os.Bundle; /** * Created by kuno on 2017-01-31. */ public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); } }
package practica10.ejemplo4_Listener; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; //implementamos un interface de testNg public class InvokedMethodListener implements IInvokedMethodListener{ @Override public void beforeInvocation(IInvokedMethod method, ITestResult testResult) { //dice cuanto test se ha ejecutado System.out.println("Antes de invocar" + method.getTestMethod().getMethodName()); } @Override public void afterInvocation(IInvokedMethod method, ITestResult testResult) { System.out.println("Después de invocar" + method.getTestMethod().getMethodName()); } }
package com.spreadtrum.android.eng; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; public class engfetch { private int mSocketID = -1; private int mType = 0; private static native void disable_modemdebugpm(int i); private static native void enable_modemdebugpm(int i); private static native int eng_getdebugnowakelock(int i); private static native void engf_close(int i); private static native int engf_getphasecheck(byte[] bArr, int i); private static native int engf_open(int i); private static native int engf_read(int i, byte[] bArr, int i2); private static native int engf_write(int i, byte[] bArr, int i2); static { System.loadLibrary("engmodeljni"); } public void writeCmd(String cmd) { int sockid = engopen(); ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream(); DataOutputStream outputBufferStream = new DataOutputStream(outputBuffer); String str = "CMD:" + cmd; try { outputBufferStream.writeBytes(str); engwrite(sockid, outputBuffer.toByteArray(), outputBuffer.toByteArray().length); Log.d("engfetch", "write cmd '" + str + "'"); engclose(sockid); } catch (IOException e) { Log.e("engfetch", "writebytes error"); } } public int engopen() { return engopen(0); } public int engopen(int type) { if (this.mSocketID >= 0) { engclose(this.mSocketID); } int result = engf_open(type); if (result < 0) { return 0; } this.mType = type; this.mSocketID = result; return result; } public void engclose(int fd) { engf_close(this.mSocketID); this.mSocketID = -1; } private boolean engreopen() { boolean z; int result = engf_open(this.mType); if (result >= 0) { this.mSocketID = result; } String str = "engfetch"; StringBuilder append = new StringBuilder().append("engreopen: "); if (result >= 0) { z = true; } else { z = false; } Log.e(str, append.append(z).toString()); if (result >= 0) { return true; } return false; } public int engwrite(int fd, byte[] data, int dataSize) { if (this.mSocketID < 0 && !engreopen()) { return 0; } int result; int iCount = 0; while (true) { result = engf_write(this.mSocketID, data, dataSize); if (result < 0 && iCount < 1 && engreopen()) { iCount++; } } return result; } public int engread(int fd, byte[] data, int size) { if (this.mSocketID < 0 && !engreopen()) { return 0; } int result; int iCount = 0; while (true) { result = engf_read(this.mSocketID, data, size); if (result < 0 && iCount < 1 && engreopen()) { iCount++; } } return result; } public int enggetphasecheck(byte[] data, int size) { return engf_getphasecheck(data, size); } public void enablemodemdebugpm(int size) { enable_modemdebugpm(size); } public void disablemodemdebugpm(int size) { disable_modemdebugpm(size); } public int enggetdebugnowakelock(int size) { return eng_getdebugnowakelock(size); } }
package com.sun.xml.bind.v2.model.impl; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; /** * @author Kohsuke Kawaguchi */ final class RuntimeEnumConstantImpl extends EnumConstantImpl<Type,Class,Field,Method> { public RuntimeEnumConstantImpl( RuntimeEnumLeafInfoImpl owner, String name, String lexical, EnumConstantImpl<Type,Class,Field,Method> next) { super(owner, name, lexical, next); } }
public enum FurnitureEnum { DOOR, SWINDOW, DWINDOW, FOURPTABLE, SIXPTABLE, EIGHTPTABLE, CHAIR, BIGCHAIR, SMALLBENCH, BIGBENCH ,LOWILUM, MEDILUM, STRONGILUM; public int getWidth(FurnitureEnum furEnum) { switch (furEnum) { case FOURPTABLE: return 34; case SIXPTABLE: return 56; case EIGHTPTABLE: return 75; case CHAIR: return 18; case SMALLBENCH: return 99; case BIGBENCH: return 198; case LOWILUM: return 18; case MEDILUM: return 18; case STRONGILUM: return 18; } return 100000; } public int getHeight(FurnitureEnum furEnum) { switch (furEnum) { case FOURPTABLE: return 34; case SIXPTABLE: return 34; case EIGHTPTABLE: return 41; case CHAIR: return 22; case SMALLBENCH: return 32; case BIGBENCH: return 32; case LOWILUM: return 18; case MEDILUM: return 18; case STRONGILUM: return 18; } return 100000; } public int getNumberOfFurniture(FurnitureEnum furEnum) { int counter = 0; for (FurnitureEnum f : FurnitureEnum.values()) { if (f.name().equals(furEnum.name())) return counter; counter++; } return counter; } }
package cs261_project.controller; import java.net.URLEncoder; import java.util.Map; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.eclipse.jetty.util.UrlEncoded; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import cs261_project.*; import cs261_project.data_structure.*; /** * Handle general web page requests such as login and registrations * @author Group 12 - Stephen Xu, JuanYan Huo, Ellen Tatum, JiaQi Lv, Alexander Odewale */ @Controller @RequestMapping("/") public class IndexProcessor { //Server port number @Value("${server.port}") private String PORT; //flags /** * A list of returned flag to indicate error and print message to the webpage * @author Group 12 - Stephen Xu, JuanYan Huo, Ellen Tatum, JiaQi Lv, Alexander Odewale */ private static enum ErrorFlag{ INCORRECT_USERNAME_PASSWORD, DUPLICATE_USERNAME, INCORRECT_EVENTCODE_PASSWORD; } public IndexProcessor(){ } /** * Rendering the redirect page with provided message * @param message Message to render * @param dest The destination after timeout * @param model Model object to put the message * @return The view */ static String renderRedirect(String message, String dest, final Model model){ //rendering redirect page model.addAttribute("message", message); model.addAttribute("destination", dest); return "redirect"; } @GetMapping("/") public final String serveIndex(){ return "index"; } @GetMapping("/terms") public final String serveTerms(){ return "terms"; } @GetMapping("/loginPage") public final String serveLogin(@RequestParam("error") @Nullable ErrorFlag error, Model model){ if(error == ErrorFlag.INCORRECT_USERNAME_PASSWORD){ //inform user about the incorrect username or password model.addAttribute("error", "Incorrect username or password, please try again."); } return "login"; } @PostMapping("/login") public final String handleLogin(@RequestParam() Map<String, String> args, HttpServletRequest request, HttpSession session) { final DatabaseConnection db = App.getInstance().getDbConnection(); final String username = args.get("username").toString(); final String password = args.get("password").toString(); final HostUser user = db.AuthenticateHost(username, password); //if username or password are incorrect if(user == null){ return "redirect:/loginPage?error=" + ErrorFlag.INCORRECT_USERNAME_PASSWORD.toString(); } //create a new session session = request.getSession(); //set user id as session variable session.setAttribute("HostID", user.getUserID()); //The general strategy is, fetch user data from database using the host id //we can also pass some arguments to hostHomePage for initial display, for example firstname lastname etc. return "redirect:/host/hostHomePage"; } @GetMapping("/registerPage") public final String serveRegister(@RequestParam("error") @Nullable ErrorFlag error, Model model){ if(error == ErrorFlag.DUPLICATE_USERNAME){ //inform user that the username has been used model.addAttribute("error", "Username already exists, Please choose another username."); } return "register"; } @PostMapping("/register") public final String handleRegister(HostUser user, Model model){ final DatabaseConnection db = App.getInstance().getDbConnection(); final boolean status = db.RegisterHost(user); if(!status){ //tell user about their error return "redirect:/registerPage?error=" + ErrorFlag.DUPLICATE_USERNAME.toString(); } return IndexProcessor.renderRedirect( "Thanks for registering with us. We are redirecting you to the login page...", "/loginPage", model); } @GetMapping("/joinEventPage") public final String serveJoinEvent(@RequestParam("error") @Nullable ErrorFlag error, Model model){ if(error == ErrorFlag.INCORRECT_EVENTCODE_PASSWORD){ //event code or password are incorrect, inform user model.addAttribute("error", "Incorrect event code or password, please try again."); } return "joinEvent"; } @PostMapping("/joinEvent") public final String handleJoinEvent(@RequestParam() Map<String, String> args, HttpServletRequest request, HttpSession session) { final DatabaseConnection db = App.getInstance().getDbConnection(); final String eventCode = args.get("eventCode").toString(); final String eventPassword = args.get("eventPassword").toString(); final Event event = db.LookupEvent(eventCode, eventPassword); if(event == null){ return "redirect:/joinEventPage?error=" + ErrorFlag.INCORRECT_EVENTCODE_PASSWORD.toString(); } //create a session session = request.getSession(); //set event id as attendee session session.setAttribute("EventID", event.getEventID()); return "redirect:/attendee/feedbackForm"; } }
package com.bestone.service; import com.bestone.model.ArticleModel22; import com.bestone.model.UserArticle22; import java.util.List; public interface ArticleService22 { //create shequ article void save(ArticleModel22 article22); //find all shequ articles List<UserArticle22> findAllShequArticle(); //查询单个社区文章 UserArticle22 findShequArticleById(ArticleModel22 article22); //select shequ articles of user List<UserArticle22> findShequByUser(ArticleModel22 article22); }
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.neuron.mytelkom; import android.view.View; import android.widget.AdapterView; import com.neuron.mytelkom.model.ConferenceAttendees; import java.util.ArrayList; // Referenced classes of package com.neuron.mytelkom: // CreateNewConferenceParticipantActivity, CreateNewConferenceAddParticipantActivity class this._cls0 implements android.widget.ty._cls3 { final CreateNewConferenceParticipantActivity this$0; public void onItemClick(AdapterView adapterview, View view, int i, long l) { CreateNewConferenceAddParticipantActivity.toCreateNewConferenceAddParticipantActivity(CreateNewConferenceParticipantActivity.this, .ParticipantFormType.EDIT, (ConferenceAttendees)CreateNewConferenceParticipantActivity.access$0(CreateNewConferenceParticipantActivity.this).get(i), i); } () { this$0 = CreateNewConferenceParticipantActivity.this; super(); } }
package be.odisee.pajotter.controller; import be.odisee.pajotter.domain.*; import be.odisee.pajotter.service.PajottersSessieService; import be.odisee.pajotter.utilities.RolNotFoundException; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/Administrator") public class AdministratorController { @Autowired protected PajottersSessieService pajottersSessieService = null; @RequestMapping(value = {"/jquery.js","/jquery"}, method = RequestMethod.GET) public String jquery(ModelMap model) { return "js/jquery-2.1.3.min.js"; } @RequestMapping(value = {"/opmaak.css","/opmaak"}, method = RequestMethod.GET) public String opmaak(ModelMap model) { return "css/Opmaak.css"; } //Lijst van alle partijen, meteen op het hoofdsherm @RequestMapping(value = {"/home.html", "/home", "/index.html", "/index", "/lijst.html", "/lijst"}, method = RequestMethod.GET) //@PostAuthorize("#model.get('rol').partij.emailadres == authentication.principal.username") public String index(/*@RequestParam("rolid") int id,*/ ModelMap model) { //Rol rolAuth = pajottersSessieService.zoekRolMetId(id); //model.addAttribute("rol", rolAuth); List<Partij> partijlijst = pajottersSessieService.geefAllePartijen(); model.addAttribute("partijen", partijlijst); return "/Administrator/index"; } //Geef details van de geselecteerde partij op basis van zijn id @RequestMapping(value = {"/partij.html", "/partij"}, method = RequestMethod.GET) public String partijDetail(@RequestParam("id") int id, ModelMap model) { Partij partij = pajottersSessieService.zoekPartijMetId(id); Rol rol = pajottersSessieService.zoekRolMetId(id); model.addAttribute("partij", partij); model.addAttribute("rol", rol); return "/Administrator/partij"; } //Om een partij toe te voegen roepen we de juiste jsp op met een lege partij en rol @RequestMapping(value = {"/nieuwePartij.html", "/nieuwePartij"}, method = RequestMethod.GET) public String partijFormulier(ModelMap model) { String rolnaam = new String(); Partij partij = new Partij(); PartijWrapperVoorForm partijwrapper = new PartijWrapperVoorForm(partij, rolnaam); model.addAttribute("departij", partijwrapper); return "/Administrator/nieuwePartij"; } //Om een nieuwe partij te maken, de ingevulde partij krijgen we binnen en persisteren @RequestMapping(value = {"/nieuwePartij.html", "/nieuwePartij"}, method = RequestMethod.POST) public String partijToevoegen(@ModelAttribute("departij") @Valid PartijWrapperVoorForm partij, BindingResult result, ModelMap model) { if (result.hasErrors()) return "/Administrator/nieuwePartij"; try { Partij toegevoegdPartij = pajottersSessieService.voegPartijToe(partij.getPartij()); Rol nieuweRol = pajottersSessieService.voegRolToe(partij.getRol(), toegevoegdPartij.getId(), partij.getPartij().getEmailadres()); System.out.println("DEBUG Partij toegevoegd met familienaam: " + partij.getPartij().getFamilienaam() + " rol:" + partij.getRol()); return "redirect:/Administrator/partij.html?id=" + toegevoegdPartij.getId(); } catch (RolNotFoundException e) { System.out.println("Probleem bij het toevoegen van een partij!!!"); } List<Partij> deLijst = pajottersSessieService.geefAllePartijen(); model.addAttribute("partijen", deLijst); return "redirect:/Administrator/index"; } //Om de partij te verwijderen @RequestMapping(value = {"/verwijderPartij.html", "/verwijderPartij"}, method = RequestMethod.GET) public String partijDelete(@RequestParam("id") int id, ModelMap model) { //pajottersSessieService.verwijderRol(id); pajottersSessieService.verwijderPartij(id); List<Partij> deLijst = pajottersSessieService.geefAllePartijen(); model.addAttribute("partijen", deLijst); return "/Administrator/index"; } //Om de partij up te daten @RequestMapping(value = {"/updatePartij.html", "/updatePartij", "/editPartij.html", "/editPartij"}, method = RequestMethod.POST) public String telerUpdate(@ModelAttribute("departij") @Valid Partij partij, BindingResult result, ModelMap model, @RequestParam String rol) { if (result.hasErrors()) return "/Administrator/editPartij"; pajottersSessieService.verwijderRol(partij.getId()); pajottersSessieService.updatePartij(partij); try { pajottersSessieService.voegRolToe(rol, partij.getId(), partij.getEmailadres()); } catch (RolNotFoundException e) { e.printStackTrace(); } Rol rol1 = pajottersSessieService.zoekRolMetId(partij.getId()); model.addAttribute("partij", partij); model.addAttribute("rol", rol1); return "/Administrator/partij"; } //Om naar de update pagina te gaan en de partij info mee te geven @RequestMapping(value = {"/updatePartij.html", "/updatePartij", "/editPartij", "/editPartij.html"}, method = RequestMethod.GET) public String telerEditpagina(@RequestParam("id") int id, ModelMap model){ Partij partij = pajottersSessieService.zoekPartijMetId(id); Rol rol = pajottersSessieService.zoekRolMetId(id); model.addAttribute("departij", partij); model.addAttribute("rol", rol); return "/Administrator/editPartij"; } }
package shulei.july24; import java.awt.BorderLayout; import java.awt.DisplayMode; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.security.Key; import javax.swing.JFrame; import javax.swing.border.Border; public class main { /** * @param args */ public static void main(String[] args) { GraphicsDevice device = GraphicsEnvironment .getLocalGraphicsEnvironment().getDefaultScreenDevice(); DisplayMode dMode = device.getDisplayMode(); int width = dMode.getWidth(); int height = dMode.getHeight(); System.out.println("with:" + width + " " + "height:" + height); MainScreen mainScreen=new MainScreen(width,height); final JFrame frame=new JFrame(); frame.getContentPane().add(mainScreen,BorderLayout.CENTER); frame.setUndecorated(true); device.setFullScreenWindow(frame); new Thread(mainScreen).start(); frame.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode()==KeyEvent.VK_ENTER) { System.exit(0); } } @Override public void keyPressed(KeyEvent e) { } }); } }
package android.support.v4.media; import android.os.Bundle; import android.support.annotation.RestrictTo; import android.support.annotation.RestrictTo.Scope; @RestrictTo({Scope.LIBRARY_GROUP}) public class MediaBrowserCompatUtils { public static boolean areSameOptions(Bundle bundle, Bundle bundle2) { boolean z = true; if (bundle == bundle2) { return z; } boolean z2 = false; int i = -1; if (bundle == null) { if (!(bundle2.getInt("android.media.browse.extra.PAGE", i) == i && bundle2.getInt("android.media.browse.extra.PAGE_SIZE", i) == i)) { z = z2; } return z; } else if (bundle2 == null) { if (!(bundle.getInt("android.media.browse.extra.PAGE", i) == i && bundle.getInt("android.media.browse.extra.PAGE_SIZE", i) == i)) { z = z2; } return z; } else { if (!(bundle.getInt("android.media.browse.extra.PAGE", i) == bundle2.getInt("android.media.browse.extra.PAGE", i) && bundle.getInt("android.media.browse.extra.PAGE_SIZE", i) == bundle2.getInt("android.media.browse.extra.PAGE_SIZE", i))) { z = z2; } return z; } } public static boolean hasDuplicatedItems(Bundle bundle, Bundle bundle2) { int i; int i2; int i3; int i4 = -1; int i5 = bundle == null ? i4 : bundle.getInt("android.media.browse.extra.PAGE", i4); if (bundle2 == null) { i = i4; } else { i = bundle2.getInt("android.media.browse.extra.PAGE", i4); } if (bundle == null) { i2 = i4; } else { i2 = bundle.getInt("android.media.browse.extra.PAGE_SIZE", i4); } if (bundle2 == null) { i3 = i4; } else { i3 = bundle2.getInt("android.media.browse.extra.PAGE_SIZE", i4); } int i6 = Integer.MAX_VALUE; boolean z = false; boolean z2 = true; if (i5 == i4 || i2 == i4) { i2 = i6; i5 = z; } else { i5 *= i2; i2 = (i2 + i5) - z2; } if (i == i4 || i3 == i4) { i4 = z; } else { i4 = i3 * i; i6 = (i3 + i4) - 1; } if (i5 > i4 || i4 > i2) { return (i5 > i6 || i6 > i2) ? z : z2; } else { return z2; } } }
/* * 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 org.exist.xquery.modules.mpeg7.x3d.helpers; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; /** * * @author Patti Spala <pd.spala@gmail.com> */ public class CommonUtils { private static final Logger logger = Logger.getLogger(CommonUtils.class); public static void printMap(Map mp) { Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); // logger.info(pairs.getKey() + " : " + pairs.getValue()); System.out.println(pairs.getKey() + " : " + pairs.getValue()); it.remove(); // avoids a ConcurrentModificationException } } public static int[] toIntArray(List<int[]> list) { int[] ret = new int[list.size() * 3]; for (int i = 0; i < list.size(); i++) { ret[3 * i] = list.get(i)[0]; ret[3 * i + 1] = list.get(i)[1]; ret[3 * i + 2] = list.get(i)[2]; } return ret; } public static void downloadFile(String fileName, URL link) throws IOException { //Code to download InputStream in = new BufferedInputStream(link.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream(fileName); fos.write(response); fos.close(); //End download code } }
package com.wmc.springboot.service; import org.springframework.stereotype.Service; /** * @author: WangMC * @date: 2019/7/10 18:19 * @description: */ @Service public class AsyncService { public void hello(){ System.out.println("hello"); } }
/* PROBLEM: Calculate factorial of number */ public class Factorial { //Uses recursion due to nature public static int fact(int i) { if (i <= 1) return 1; //0! = 1! = 1 else return i * fact(i-1); } public static void main(String[] args) { System.out.println(fact(5)); } }
package mikfuans.security.dao; import mikfuans.security.bean.SysRolePermission; import mikfuans.security.bean.SysRolePermissionCriteria; import org.apache.ibatis.annotations.*; import org.apache.ibatis.type.JdbcType; import java.util.List; @Mapper public interface SysRolePermissionMapper { @SelectProvider(type=SysRolePermissionSqlProvider.class, method="countByExample") long countByExample(SysRolePermissionCriteria example); @DeleteProvider(type=SysRolePermissionSqlProvider.class, method="deleteByExample") int deleteByExample(SysRolePermissionCriteria example); @Delete({ "delete from sys_role_permission", "where id = #{id,jdbcType=BIGINT}" }) int deleteByPrimaryKey(Long id); @Insert({ "insert into sys_role_permission (role_id, permission_id)", "values (#{roleId,jdbcType=BIGINT}, #{permissionId,jdbcType=BIGINT})" }) @Options(useGeneratedKeys=true,keyProperty="id") int insert(SysRolePermission record); @InsertProvider(type=SysRolePermissionSqlProvider.class, method="insertSelective") @Options(useGeneratedKeys=true,keyProperty="id") int insertSelective(SysRolePermission record); @SelectProvider(type=SysRolePermissionSqlProvider.class, method="selectByExample") @Results({ @Result(column="id", property="id", jdbcType= JdbcType.BIGINT, id=true), @Result(column="role_id", property="roleId", jdbcType= JdbcType.BIGINT), @Result(column="permission_id", property="permissionId", jdbcType= JdbcType.BIGINT) }) List<SysRolePermission> selectByExample(SysRolePermissionCriteria example); @Select({ "select", "id, role_id, permission_id", "from sys_role_permission", "where id = #{id,jdbcType=BIGINT}" }) @Results({ @Result(column="id", property="id", jdbcType= JdbcType.BIGINT, id=true), @Result(column="role_id", property="roleId", jdbcType= JdbcType.BIGINT), @Result(column="permission_id", property="permissionId", jdbcType= JdbcType.BIGINT) }) SysRolePermission selectByPrimaryKey(Long id); @UpdateProvider(type=SysRolePermissionSqlProvider.class, method="updateByExampleSelective") int updateByExampleSelective(@Param("record") SysRolePermission record, @Param("example") SysRolePermissionCriteria example); @UpdateProvider(type=SysRolePermissionSqlProvider.class, method="updateByExample") int updateByExample(@Param("record") SysRolePermission record, @Param("example") SysRolePermissionCriteria example); @UpdateProvider(type=SysRolePermissionSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(SysRolePermission record); @Update({ "update sys_role_permission", "set role_id = #{roleId,jdbcType=BIGINT},", "permission_id = #{permissionId,jdbcType=BIGINT}", "where id = #{id,jdbcType=BIGINT}" }) int updateByPrimaryKey(SysRolePermission record); }
package jianzhioffer; import jianzhioffer.utils.ListNode; /** * @ClassName : Solution23 * @Description : 链表中环的入口节点 第一步:判断链表中是否有环 // 定义两个速度不同的指针,慢的一次一步,快的一次两步,如果有环,走得快的指针一定能追上走得慢的指针,如果走得快的指针到达链表的末尾时还没追上,则意味着没有环。 // 第3步:找到环的出入口 // 定义两个指针,若环的节点数为n,则指针P1先行n步时,P2指针开始以相同的速度移动,此时P1已经到达环的入口了。 // 第2步:得到环的节点数 // 两指针相遇的节点一定在环中,从该节点出发进行遍历,当再回到该节点时,即可得到节点数。 * @Date : 2019/9/16 13:36 */ public class Solution23 { public ListNode EntryNodeOfLoop(ListNode pHead){ if (pHead==null) return null; ListNode meetNode=findMeetNode(pHead); ListNode curNode=meetNode; int loopLen=1; while (curNode.next!=meetNode){ curNode=curNode.next; loopLen++; } curNode=pHead; int i=0; while (i<loopLen){ curNode=curNode.next; i++; } ListNode tmp=pHead; while (tmp!=curNode){ tmp=tmp.next; curNode=curNode.next; } return curNode; } //找到环中任意一个点 private ListNode findMeetNode(ListNode pHead) { ListNode slow=pHead.next; if (slow==null) return null; ListNode quick=slow.next; while (quick!=null && slow!=null){ if (quick==slow)//当相等时,停止 return quick; slow=slow.next; //慢的指针一次一步 quick=quick.next; if (quick!=slow) quick=quick.next; //快的指针一次走两步 } return null; } }
package com.globallogic.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.security.core.GrantedAuthority; @Entity @Table(name="ROLE_DETAILS") public class RoleDetails implements GrantedAuthority { private static final long serialVersionUID = -6907317178208338118L; @Id @Column(name="ROLE_NAME",length=20) private String roleName; @Column(name="ROLE_DESC", length=50) private String roleDesc; public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; } public String getAuthority() { return roleName; } @Override public String toString() { return "RoleDetails [roleName=" + roleName + ", roleDesc=" + roleDesc + "]"; } }
package br.mg.puc.sica.evento.evento.model.response; import br.mg.puc.sica.evento.evento.model.Sensor; import java.util.List; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class SensorResponse { private Long idSensor; private String nomeSensor; private String localizacao; }
package MachineLearning; import java.io.File; import java.io.IOException; import java.util.ArrayList; public class SameNumberofLines { public static void main(String args[]) throws IOException{ String type = args[0]; String outdir = "/home/c-tyabe/Data/MLResults_"+type+"13/"; String outdir3 = outdir+"forML/calc/"; String outdir4 = outdir+"forML/calc/sameexp/"; ArrayList<String> subjects = new ArrayList<String>(); subjects.add("home_exit_diff"); subjects.add("tsukin_time_diff"); subjects.add("office_enter_diff"); subjects.add("office_time_diff"); subjects.add("office_exit_diff"); subjects.add("kitaku_time_diff"); subjects.add("home_return_diff"); for(String subject:subjects){ String plusminus_multiplelinesclean = outdir3+subject+"_ML2_plusminus_lineforeach.csv"; String plusminus_multiplelinesclean_samenumlines = outdir4+subject+"_ML2_plusminus_lineforeach_same.csv"; MLData2.samenumberoflines(new File(plusminus_multiplelinesclean), new File(plusminus_multiplelinesclean_samenumlines)); } } }
import java.util.*; public class GraphMatrix { //produces an adjacency matrix to implement a graph private static int V; //number of vertices in the graph private static List<int[]> adjacencyMatrix = new ArrayList<int[]>(V); GraphMatrix(int VSize) { V = VSize; for (int i = 0; i < V; i++) { adjacencyMatrix.add(new int[V]); } } private static void addEdge(int v, int u) { if (v > V || u > V) { System.out.println("You cannot connect edges for vertices that are not yet in the graph"); } adjacencyMatrix.get(v)[u] += 1; } /*private static void addNode(int v) { if (v > V + 1 || v < 0) { System.out.println("Can only add node valued " + V + 1); } if (v <= V) { System.out.println("Node is already in the graph."); } V = v; adjacencyMatrix.add(new int[V]); for (int i = 0; i < adjacencyMatrix.size() - 1; i++) { adjacencyMatrix.get(i)[V - 1]; } */ private static void printGraph(GraphMatrix graph) { List<int[]> graphMatrix = graph.adjacencyMatrix; System.out.print(" "); for (int i = 0; i < graph.V; i++) { System.out.print(i + " "); } System.out.println("\n ------------------"); int count = 0; for (int[] row : graphMatrix) { System.out.print(count++ + "|"); for (int col : row) { System.out.print(col + " "); } System.out.println(); } } public static void main(String []args) { GraphMatrix graph = new GraphMatrix(5); graph.addEdge(0, 1); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(3, 4); graph.addEdge(4, 0); printGraph(graph); } }
/* * 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 tokomainankita; /** * * @author windows10 */ public class Barang { private int id_barang; private int id_supplier; private String nama; private char stok_barang; /** * @return the id_barang */ public int getId_barang() { return id_barang; } /** * @param id_barang the id_barang to set */ public void setId_barang(int id_barang) { this.id_barang = id_barang; } /** * @return the id_supplier */ public int getId_supplier() { return id_supplier; } /** * @param id_supplier the id_supplier to set */ public void setId_supplier(int id_supplier) { this.id_supplier = id_supplier; } /** * @return the nama */ public String getNama() { return nama; } /** * @param nama the nama to set */ public void setNama(String nama) { this.nama = nama; } /** * @return the stok_barang */ public char getStok_barang() { return stok_barang; } /** * @param stok_barang the stok_barang to set */ public void setStok_barang(char stok_barang) { this.stok_barang = stok_barang; } }
package in.msmartpay.agent.myWallet; class BalHistoryModel { public String dateBal; public String timeBal; public String modeBal; public String amountBal; public String statusBal; public String refIdBal; public String getDateBal() { return dateBal; } public void setDateBal(String dateBal) { this.dateBal = dateBal; } public String getTimeBal() { return timeBal; } public void setTimeBal(String timeBal) { this.timeBal = timeBal; } public String getModeBal() { return modeBal; } public void setModeBal(String modeBal) { this.modeBal = modeBal; } public String getAmountBal() { return amountBal; } public void setAmountBal(String amountBal) { this.amountBal = amountBal; } public String getStatusBal() { return statusBal; } public void setStatusBal(String statusBal) { this.statusBal = statusBal; } public String getRefIdBal() { return refIdBal; } public void setRefIdBal(String refIdBal) { this.refIdBal = refIdBal; } }
package defenseSystem_levels; import defenseSystem.ID; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.image.ImageObserver; import java.util.LinkedList; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.swing.JPanel; import asset_code.IngameUI; import asset_code.SiloOne; import asset_code.SmartTest; import asset_code.TestMark; import asset_code.TestPMissile; import asset_code.standard_explosion; import defenseSystem.*; public class LevelTwo extends JPanel{/* private Timer timer; private Random r = new Random(); public float mouseX; public float mouseY; public int deleteThisNumber; private boolean spawnAlot = true; public int mouseState; int countAlot; int lvlScore = 0, lvlWave = 0; // int targetNum; int secondSpawn; public IngameUI ingameUI; public LinkedList<SmartTest> smart2 = new LinkedList<SmartTest>(); public LinkedList<SiloOne> siloOne = new LinkedList<SiloOne>(); public LinkedList<TestMark> testMark = new LinkedList<TestMark>(); public LinkedList<TestPMissile> testPMissile = new LinkedList<TestPMissile>(); public LinkedList<standard_explosion> stExplosion = new LinkedList<standard_explosion>(); public int MissileCount = 8; public boolean gameOver = false; public LevelTwo() { initialization(); } public void initialization() { setDoubleBuffered(true); addNextWave(); ingameUI = new IngameUI(0,0,null); ingameUI.updateUI(lvlScore, lvlWave); timer = new Timer(); timer.scheduleAtFixedRate(new ScheduleTask(), Universal.DELAY, Universal.PERIOD); siloOne.add(new SiloOne(Universal.WIDTH/8, (Universal.HEIGHT-Universal.HEIGHT/8), ID.silo1)); siloOne.add(new SiloOne(Universal.WIDTH/3, (Universal.HEIGHT-Universal.HEIGHT/8), null)); siloOne.add(new SiloOne((Universal.WIDTH-Universal.WIDTH/3), (Universal.HEIGHT-Universal.HEIGHT/8), null)); siloOne.add(new SiloOne((Universal.WIDTH-Universal.WIDTH/8), (Universal.HEIGHT-Universal.HEIGHT/8), null)); } public void drawObjects(Graphics2D g2d) { setBackground(Color.BLUE); //<--- does not work //ingameUI.drwRect(g2d); for(int n=0;n<testMark.size(); n++) { testMark.get(n).drwImage(g2d); } for(int n=0;n<testPMissile.size(); n++) { testPMissile.get(n).drwImage(g2d); } for(int n = 0; n<siloOne.size(); n++) { siloOne.get(n).drwImage(g2d); } for(int n=0;n<smart2.size(); n++) { smart2.get(n).drwImage(g2d); } for(int n=0;n<stExplosion.size();n++) { stExplosion.get(n).drwImage(g2d); } if(gameOver == true) { g2d.drawString("Game Over", Universal.HEIGHT/2, Universal.WIDTH/2); } ingameUI.drwRect(g2d); } // --| Listener is in Hub public void mouseMoved(MouseEvent e) { mouseX = (float)e.getX(); mouseY = (float)e.getY(); if(e.getX()<Universal.WIDTH/8) mouseState = 0; else if(e.getX()>Universal.WIDTH/8 && e.getX()<Universal.WIDTH/2) mouseState = 1; else if(e.getX()>Universal.WIDTH/3 && e.getX()<(Universal.WIDTH-Universal.WIDTH/3)) mouseState = 2; else if(e.getX()>(Universal.WIDTH-Universal.WIDTH/3) && e.getX()<(Universal.WIDTH-Universal.WIDTH/8)) mouseState = 3; } public void mouseReleased(MouseEvent e) { if(MissileCount != 0) { testMark.add(new TestMark(e.getX(), e.getY(), null)); if(mouseState == 0) { testPMissile.add(new TestPMissile((int)siloOne.get(0).getCentralX(), (int)siloOne.get(0).getCentralY(), null)); } if(mouseState == 1) { testPMissile.add(new TestPMissile((int)siloOne.get(1).getCentralX(), (int)siloOne.get(0).getCentralY(), null)); } if(mouseState == 2) { testPMissile.add(new TestPMissile((int)siloOne.get(2).getCentralX(), (int)siloOne.get(0).getCentralY(), null)); } if(mouseState == 3) { testPMissile.add(new TestPMissile((int)siloOne.get(3).getCentralX(), (int)siloOne.get(0).getCentralY(), null)); } // smart2.get(n).seek(siloOne.get(smart2.get(n).targetNum)); //testPMissile.getLast().toPosition(testMark.getLast()); MissileCount -= 1; } } //will be called to increase difficulty while spamming public void addNextWave() { smart2.add(new SmartTest(r.nextInt(Universal.WIDTH),(-5), null)); smart2.add(new SmartTest(r.nextInt(Universal.WIDTH),(-5), null)); smart2.add(new SmartTest(r.nextInt(Universal.WIDTH),(-5), null)); smart2.add(new SmartTest(r.nextInt(Universal.WIDTH),(-5), null)); smart2.add(new SmartTest(r.nextInt(Universal.WIDTH),(-5), null)); lvlWave+=1; } //will add random number of non-standard missiles public void addExtraMissiles() { } //real-time updates are done here private class ScheduleTask extends TimerTask { @Override public void run() { if(gameOver == false) { if(stExplosion.size()>0) { for(int n=0;n<stExplosion.size();n++) { if(stExplosion.get(n).lifetime < stExplosion.get(n).maxLifetime) { stExplosion.get(n).lifetime += 1; stExplosion.get(n).setHeight(0.33); stExplosion.get(n).setWidth(0.33); }else if(stExplosion.get(n).lifetime >= stExplosion.get(n).maxLifetime) { stExplosion.remove(n); } } } for(int n=0;n<testMark.size();n++) { testPMissile.get(n).toPosition(mouseX, mouseY); if(testMark.get(n).expload == true) { // stExplosion.add(new standard_explosion((int)testMark.get(n).getCentralX(), (int)testMark.get(n).getCentralY(), null)); testPMissile.remove(n); testMark.remove(n); } // testMark.get(n).setHeight(0.33); // testMark.get(n).setWidth(0.33); } //add scalable things for(int n=0;n<testMark.size();n++) { for(int i=0;i<testPMissile.size();i++) { if(testMark.get(n).getRect().intersects(testPMissile.get(i).getRect())) { testMark.get(n).sExplode(); } } } //testPMissile.getLast().seek(testMark.getLast()); //countAlot++; if(smart2.size() == 0) { addNextWave(); MissileCount = 2; // countAlot = 0; } try{ for(int n=0;n<smart2.size(); n++) { if(smart2.get(n).targetNum == -1) { smart2.get(n).targetNum = r.nextInt(siloOne.size()); smart2.get(n).diff += (r.nextFloat() - 0.5f); } if(smart2.get(n).getX() <= (Universal.HEIGHT/2 + Universal.HEIGHT/4)) { if(smart2.get(n).splitCheck == false) { smart2.get(n).splitTimer = r.nextInt(10); System.out.println(" " + smart2.get(n).splitTimer + " "); if(smart2.get(n).splitTimer >= 2) { System.out.print(" SPLIT! SPLIT!"); smart2.add(new SmartTest((int)smart2.get(n).getCentralX(),(int)smart2.get(n).getCentralY(), null)); smart2.getLast().splitCheck = true; smart2.add(new SmartTest((int)smart2.get(n).getCentralX(),(int)smart2.get(n).getCentralY(), null)); smart2.getLast().splitCheck = true; smart2.add(new SmartTest((int)smart2.get(n).getCentralX(),(int)smart2.get(n).getCentralY(), null)); smart2.getLast().splitCheck = true; smart2.remove(n); } smart2.get(n).splitCheck = true; } } // smart2.get(n).seek(siloOne.get(smart2.get(n).targetNum)); smart2.get(n).toPosition(siloOne.get(smart2.get(n).targetNum)); if(smart2.get(n).onCollission(siloOne)) { System.out.println("hit"); // siloOne.remove(i); // smart2.remove(n); // deleteThisNumber = n; lvlScore += 1; } for(int i=0; i<stExplosion.size(); i++) { if(smart2.get(n).getRect().intersects(stExplosion.get(i).getRect())) { System.out.println("hit"); // siloOne.remove(i); lvlScore += 1; smart2.remove(n); // deleteThisNumber = n; } } } }catch (IndexOutOfBoundsException e) { //System.err.println("IndexOutOfBoundsException: " + e.getMessage()); for(int n=0;n<smart2.size(); n++) { smart2.get(n).targetNum = r.nextInt(siloOne.size()); } } for(int n=0;n<siloOne.size(); n++) { for(int i=0;i<smart2.size(); i++) { try{ if(siloOne.get(n).getRect().intersects(smart2.get(i).getRect())) { siloOne.remove(n); } }catch(IndexOutOfBoundsException e) { if(siloOne.size() == 0) { gameOver = true; System.out.println("Game Over"); } else { smart2.get(n).targetNum = r.nextInt(siloOne.size()); } } } } ingameUI.updateUI(lvlScore, lvlWave); } } } */ }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licensing information. * * Created on 18 jan 2015 * Author: P. Piernik */ /** * Common code related to confirmation subsystem * @author P. Piernik */ package pl.edu.icm.unity.confirmations;
package com.design.pattern.factoryDemo; /** * 抽象工厂类 * Created by zhouliang on 2017/10/19. */ public abstract class Factory { /*创建方法*/ public abstract <T extends AudiCar> T creatAudiCar(Class<T> clz); }
/** * */ package de.calendarmodule.calendar.client.model; import de.smartmirror.smf.client.model.Model; /** * @author julianschultehullern * */ public interface CalendarModel extends Model { }
/* * 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 br.edu.ifrs.mostra.models; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author jean */ @Entity @Table(name = "voluntario") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Voluntario.findAll", query = "SELECT v FROM Voluntario v"), @NamedQuery(name = "Voluntario.findByFkUsuario", query = "SELECT v FROM Voluntario v WHERE v.fkUsuario = :fkUsuario"), @NamedQuery(name = "Voluntario.findByObservacoes", query = "SELECT v FROM Voluntario v WHERE v.observacoes = :observacoes"), @NamedQuery(name = "Voluntario.findByManha", query = "SELECT v FROM Voluntario v WHERE v.manha = :manha"), @NamedQuery(name = "Voluntario.findByTarde", query = "SELECT v FROM Voluntario v WHERE v.tarde = :tarde"), @NamedQuery(name = "Voluntario.findByNoite", query = "SELECT v FROM Voluntario v WHERE v.noite = :noite"), @NamedQuery(name = "Voluntario.findByTelefone1", query = "SELECT v FROM Voluntario v WHERE v.telefone1 = :telefone1"), @NamedQuery(name = "Voluntario.findByTelefone2", query = "SELECT v FROM Voluntario v WHERE v.telefone2 = :telefone2"), @NamedQuery(name = "Voluntario.findByTelefone3", query = "SELECT v FROM Voluntario v WHERE v.telefone3 = :telefone3"), @NamedQuery(name = "Voluntario.findByPresenca", query = "SELECT v FROM Voluntario v WHERE v.presenca = :presenca"), @NamedQuery(name = "Voluntario.findByStatus", query = "SELECT v FROM Voluntario v WHERE v.status = :status")}) public class Voluntario implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull(message = "fk_usuario nao pode ser null na tabela") @Column(name = "fk_usuario") private Integer fkUsuario; @Size(max = 200) @Column(name = "observacoes") private String observacoes; @Basic(optional = false) @NotNull @Size(min = 1, max = 1) @Column(name = "manha") private String manha; @Basic(optional = false) @NotNull @Size(min = 1, max = 1) @Column(name = "tarde") private String tarde; @Basic(optional = false) @NotNull @Size(min = 1, max = 1) @Column(name = "noite") private String noite; @Basic(optional = false) @NotNull @Size(min = 1, max = 12) @Column(name = "telefone1") private String telefone1; @Basic(optional = false) @NotNull @Size(min = 1, max = 12) @Column(name = "telefone2") private String telefone2; @Basic(optional = false) @NotNull @Size(min = 1, max = 12) @Column(name = "telefone3") private String telefone3; @Basic(optional = false) @NotNull @Column(name = "presenca") private boolean presenca; @Column(name = "status") private Integer status; @JoinColumn(name = "fk_curso", referencedColumnName = "id_curso") @ManyToOne private Curso fkCurso; @JoinColumn(name = "fk_usuario", referencedColumnName = "id_usuario", insertable = false, updatable = false) @OneToOne(optional = false) private Usuario usuario; public Voluntario() { } public Voluntario(Integer fkUsuario) { this.fkUsuario = fkUsuario; } public Voluntario(Integer fkUsuario, String manha, String tarde, String noite, String telefone1, String telefone2, String telefone3, boolean presenca) { this.fkUsuario = fkUsuario; this.manha = manha; this.tarde = tarde; this.noite = noite; this.telefone1 = telefone1; this.telefone2 = telefone2; this.telefone3 = telefone3; this.presenca = presenca; } public Integer getFkUsuario() { return fkUsuario; } public void setFkUsuario(Integer fkUsuario) { this.fkUsuario = fkUsuario; } public String getObservacoes() { return observacoes; } public void setObservacoes(String observacoes) { this.observacoes = observacoes; } public String getManha() { return manha; } public void setManha(String manha) { this.manha = manha; } public String getTarde() { return tarde; } public void setTarde(String tarde) { this.tarde = tarde; } public String getNoite() { return noite; } public void setNoite(String noite) { this.noite = noite; } public String getTelefone1() { return telefone1; } public void setTelefone1(String telefone1) { this.telefone1 = telefone1; } public String getTelefone2() { return telefone2; } public void setTelefone2(String telefone2) { this.telefone2 = telefone2; } public String getTelefone3() { return telefone3; } public void setTelefone3(String telefone3) { this.telefone3 = telefone3; } public boolean getPresenca() { return presenca; } public void setPresenca(boolean presenca) { this.presenca = presenca; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Curso getFkCurso() { return fkCurso; } public void setFkCurso(Curso fkCurso) { this.fkCurso = fkCurso; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } @Override public int hashCode() { int hash = 0; hash += (fkUsuario != null ? fkUsuario.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Voluntario)) { return false; } Voluntario other = (Voluntario) object; if ((this.fkUsuario == null && other.fkUsuario != null) || (this.fkUsuario != null && !this.fkUsuario.equals(other.fkUsuario))) { return false; } return true; } @Override public String toString() { return "br.edu.ifrs.mostra.models.Voluntario[ fkUsuario=" + fkUsuario + " ]"; } }
package com.lenovohit.hwe.treat.service.impl; import java.util.Map; import org.springframework.stereotype.Service; import com.lenovohit.hwe.treat.dto.GenericRestDto; import com.lenovohit.hwe.treat.model.Profile; import com.lenovohit.hwe.treat.service.HisProfileService; import com.lenovohit.hwe.treat.transfer.RestEntityResponse; import com.lenovohit.hwe.treat.transfer.RestListResponse; @Service public class HisProfileRestServiceImpl implements HisProfileService { GenericRestDto<Profile> dto; public HisProfileRestServiceImpl(final GenericRestDto<Profile> dto) { super(); this.dto = dto; } public HisProfileRestServiceImpl(){ } @Override public RestEntityResponse<Profile> getInfo(Profile model, Map<String, ?> variables) { //TODO 如果后续有数据字典或转换此处接收数据后还要处理 return dto.getForEntity("hcp/app/base/profile/info", model); } @Override public RestListResponse<Profile> findList(Profile model, Map<String, ?> variables) { return dto.getForList("hcp/app/base/profile/list", model, variables); } @Override public RestEntityResponse<Profile> create(Profile model, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestEntityResponse<Profile> update(Profile model, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestEntityResponse<Profile> logoff(Profile model, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestEntityResponse<Profile> logon(Profile model, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestEntityResponse<Profile> acctOpen(Profile request, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestEntityResponse<Profile> acctFreeze(Profile request, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } @Override public RestEntityResponse<Profile> acctUnfreeze(Profile request, Map<String, ?> variables) { // TODO Auto-generated method stub return null; } }
package com.getkhaki.api.bff.domain.persistence; import com.getkhaki.api.bff.domain.models.EmployeeDm; import com.getkhaki.api.bff.domain.models.EmployeeWithStatisticsDm; import com.getkhaki.api.bff.persistence.models.EmployeeDao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.time.Instant; import java.util.UUID; public interface EmployeePersistenceInterface { EmployeeDao getEmployee(UUID id); Page<EmployeeDm> getEmployees(Pageable pageable); EmployeeDm getAuthedEmployee(); Page<EmployeeDm> getEmployeesByDepartment(String department, Pageable pageable); Page<EmployeeWithStatisticsDm> getEmployeesWithStatistics( Instant sDate, Instant eDate, String department, Pageable pageable); EmployeeDm updateEmployee(UUID id, EmployeeDm employeeDm); EmployeeDao createEmployee(String firstName, String lastName, String email, String departmentName); }
package me.libraryaddict.disguise.disguisetypes.watchers; import org.bukkit.inventory.ItemStack; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; public class DroppedItemWatcher extends FlagWatcher { public DroppedItemWatcher(Disguise disguise) { super(disguise); } public ItemStack getItemStack() { return getData(MetaIndex.DROPPED_ITEM); } public void setItemStack(ItemStack item) { setData(MetaIndex.DROPPED_ITEM, item); sendData(MetaIndex.DROPPED_ITEM); } }
/** * Copyright (C) 2015-2016, Zhichun Wu * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.github.cassandra.jdbc; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.sql.SQLException; import java.sql.SQLWarning; import static org.testng.Assert.*; public class BaseJdbcObjectTest { private BaseJdbcObject jdbcObj; @BeforeClass(groups = {"unit", "base"}) public void setUp() throws Exception { jdbcObj = new BaseJdbcObject(false) { @Override protected SQLException tryClose() { return null; } @Override protected Object unwrap() { return null; } }; } @AfterClass(groups = {"unit", "base"}) public void tearDown() throws Exception { jdbcObj = null; } @Test(groups = {"unit", "base"}) public void testGetWarnings() { try { assertNull(jdbcObj.getWarnings()); SQLWarning w = new SQLWarning("warning1"); jdbcObj.appendWarning(w); assertEquals(w, jdbcObj.getWarnings()); assertNull(jdbcObj.getWarnings().getNextWarning()); jdbcObj.clearWarnings(); assertNull(jdbcObj.getWarnings()); jdbcObj.appendWarning(w); jdbcObj.appendWarning(w); assertEquals(w, jdbcObj.getWarnings()); assertNull(jdbcObj.getWarnings().getNextWarning()); jdbcObj.clearWarnings(); assertNull(jdbcObj.getWarnings()); SQLWarning w2 = new SQLWarning("warning2"); jdbcObj.appendWarning(w); jdbcObj.appendWarning(w2); assertEquals(w, jdbcObj.getWarnings()); assertEquals(w2, jdbcObj.getWarnings().getNextWarning()); assertNull(jdbcObj.getWarnings().getNextWarning().getNextWarning()); jdbcObj.clearWarnings(); assertNull(jdbcObj.getWarnings()); } catch (Exception e) { e.printStackTrace(); fail("Exception happened during test: " + e.getMessage()); } } }
package Testabcd; import org.openqa.selenium.By; public class ShoppingCartPage extends Utils { private By _shoppingCart = By.xpath("//div[@class='page-title']"); //Asserting Shopping cart page public void userShoulcSeeAllProductAddToCart() { Utils.assertMessagetext(_shoppingCart); } }
package com.san.fieldType; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @RestController @RequestMapping("/fieldType") public class FieldTypeRestController { @Autowired private FieldTypeService fieldTypeService; /* **Return a listing of all the resources */ @RequestMapping(method = RequestMethod.GET) public List<FieldType> getAll() { return fieldTypeService.getAll(); } /* **Return one resource */ @RequestMapping("/{id}") public FieldType getOne(@PathVariable Integer id) { return fieldTypeService.getOne(id); } /* **Store a newly created resource in storage. */ @RequestMapping(method = RequestMethod.POST) public void add(@RequestBody FieldType fieldType) { fieldTypeService.add(fieldType); } /* **Update the specified resource in storage. */ @RequestMapping(method = RequestMethod.PUT) public void update(@RequestBody FieldType fieldType) { fieldTypeService.update(fieldType); } /* **Remove the specified resource from storage. */ @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public void delete(@PathVariable Integer id) { fieldTypeService.delete(id); } }
package BoardDAO; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import BoardDTO.BoardDTO; public class BoardDAO { private Connection getConnection() { String url="jdbc:oracle:thin:@localhost:1521:XE"; String user="hong"; String password="123"; Connection conn=null; try{ Class.forName("oracle.jdbc.OracleDriver"); conn=DriverManager.getConnection(url, user, password); } catch(ClassNotFoundException e){System.out.println(e);} catch(SQLException e){System.out.println(e);} return conn; } public List<BoardDTO> boardView() { Connection conn=null; PreparedStatement pstmt=null; StringBuilder sb=new StringBuilder(); ResultSet rs=null; sb.append(" select "); sb.append(" num "); sb.append(" ,title "); sb.append(" ,content "); sb.append(" ,writer "); sb.append(" from board "); ArrayList<BoardDTO> arr=new ArrayList<>(); try{ conn=getConnection(); pstmt=conn.prepareStatement(sb.toString()); rs=pstmt.executeQuery(); while(rs.next()) { BoardDTO dto=new BoardDTO(); dto.setNum(rs.getInt("num")); dto.setTitle(rs.getString("title")); dto.setContent(rs.getString("content")); dto.setWriter(rs.getString("writer")); arr.add(dto); } }catch(SQLException e){System.out.println(e);} finally { if(rs!=null)try{rs.close();}catch(Exception e){} if(pstmt!=null)try{pstmt.close();}catch(SQLException e){} if(conn!=null)try{conn.close();}catch(SQLException e){} } return arr; } public int boardappend(BoardDTO data) { Connection conn=null; PreparedStatement pstmt=null; StringBuilder sql=new StringBuilder(); sql.append(" insert into board (num,title,content,writer) "); sql.append(" values (se1.nextval, ?,?,? ) "); int r=0; try{ conn=getConnection(); pstmt=conn.prepareStatement(sql.toString()); pstmt.setString(1, data.getTitle()); pstmt.setString(2, data.getContent()); pstmt.setString(3, data.getWriter()); r=pstmt.executeUpdate(); }catch(SQLException e){System.out.println(e);} finally{ if(pstmt!=null)try{pstmt.close();}catch(SQLException e){System.out.println(e);} if(conn!=null)try{conn.close();}catch(SQLException e){System.out.println(e);} } return r; } public BoardDTO readData(int id) { Connection conn=null; PreparedStatement pstmt=null; StringBuilder sql=new StringBuilder(); ResultSet rs=null; sql.append(" select "); sql.append(" num "); sql.append(" ,title "); sql.append(" ,content "); sql.append(" ,writer "); sql.append(" from "); sql.append(" board "); sql.append(" where num=? "); BoardDTO dto=new BoardDTO(); try{ conn=getConnection(); pstmt=conn.prepareStatement(sql.toString()); pstmt.setInt(1, id); rs=pstmt.executeQuery(); if(rs.next()) { dto.setNum(rs.getInt("num")); dto.setTitle(rs.getString("title")); dto.setContent(rs.getString("content")); dto.setWriter(rs.getString("writer")); } else { } }catch(SQLException e){System.out.println(e);} finally {if(pstmt!=null)try{pstmt.close();}catch(SQLException e){System.out.println(e);} if(conn!=null)try{conn.close();}catch(SQLException e){System.out.println(e);} if(rs!=null)try{rs.close();}catch(SQLException e){System.out.println(e);} } return dto; } public void delData(int num) { Connection conn=null; PreparedStatement pstmt=null; StringBuilder sql=new StringBuilder(); sql.append(" delete from board "); sql.append(" where num=? "); try{ conn=getConnection(); pstmt=conn.prepareStatement(sql.toString()); pstmt.setInt(1, num); pstmt.executeUpdate(); }catch(SQLException e){System.out.println(e);} finally { if(pstmt!=null)try{pstmt.close();}catch(SQLException e){System.out.println(e);} if(conn!=null)try{conn.close();}catch(SQLException e){System.out.println(e);} } } public void moditydata(BoardDTO dto) { Connection conn=null; PreparedStatement pstmt=null; StringBuilder sql=new StringBuilder(); sql.append(" update board "); sql.append(" set content=? "); sql.append(" where num=? "); try{ conn=getConnection(); pstmt=conn.prepareStatement(sql.toString()); pstmt.setInt(2,dto.getNum()); pstmt.setString(1, dto.getContent()); pstmt.executeUpdate(); }catch(SQLException e){System.out.println(e);} finally { if(pstmt!=null)try{pstmt.close();}catch(SQLException e){System.out.println(e);} if(conn!=null)try{conn.close();}catch(SQLException e){System.out.println(e);} } } }
package test.thread; public class MyRunnable implements Runnable { private int i; public MyRunnable(int i) { this.i = i; } @Override public void run(){ for(i=0;i<100;i++){ System.out.println(Thread.currentThread().getName() + " " + i); } } }
package com.meehoo.biz.core.basic.handler; import com.meehoo.biz.common.util.BaseUtil; import com.meehoo.biz.common.util.DateUtil; import com.meehoo.biz.core.basic.exception.SearchConditionException; import com.meehoo.biz.core.basic.param.SearchCondition; import org.hibernate.criterion.*; import org.springframework.stereotype.Component; /** * @author zc * @date 2020-01-09 */ @Component public class SearchConditionHandler { public Object transform(String value,String fieldType){ switch (fieldType) { case "String": return value; case "Long": case "long": return Long.valueOf(value); case "Integer": case "int": return Integer.parseInt(value); case "Date": return DateUtil.stringToDate(value); } return null; } public void handle(String name,Object value,String operand,DetachedCriteria criteria) throws SearchConditionException{ try { if (operand.equals(SearchCondition.ORDER_BY_ASC)){ criteria.addOrder(Order.asc(name)); }else if (operand.equals(SearchCondition.ORDER_BY_DESC)){ criteria.addOrder(Order.desc(name)); } else if (SearchCondition.IS_NULL.equalsIgnoreCase(operand)){ criteria.add(Restrictions.isNull(name)); } else if (SearchCondition.IS_NOT_NULL.equalsIgnoreCase(operand)){ criteria.add(Restrictions.isNotNull(name)); } else if (BaseUtil.objectNotNull(value)){ switch (operand) { case "like": criteria.add(Restrictions.like(name, (String)value, MatchMode.ANYWHERE)); break; case "equal": case "=": criteria.add(Restrictions.eq(name, value)); break; case "!=": case "<>": criteria.add(Restrictions.ne(name, value)); break; case ">": case "gt": criteria.add(Restrictions.gt(name, value)); break; case "<": case "lt": criteria.add(Restrictions.lt(name, value)); break; case "in": criteria.add(Restrictions.in(name, ((String)value).split(","))); break; default: break; } } }catch (Exception e){ throw new SearchConditionException("条件不对"); } } }
package com.redsun.platf.entity.sys; // default package // Generated 2010/8/12 下午 05:52:38 by Hibernate Tools 3.3.0.GA import java.util.Date; import javax.persistence.Entity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.redsun.platf.entity.BaseEntity; /** * Sys103mId generated by hbm2java */ @Entity @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Sys103mId extends BaseEntity { private static final long serialVersionUID = -2263723530530102898L; private String osHost; private String osUser; private Date logonDay; public Sys103mId() { } public Sys103mId(String osHost, String osUser, Date logonDay) { this.osHost = osHost; this.osUser = osUser; this.logonDay = logonDay; } public String getOsHost() { return this.osHost; } public void setOsHost(String osHost) { this.osHost = osHost; } public String getOsUser() { return this.osUser; } public void setOsUser(String osUser) { this.osUser = osUser; } public Date getLogonDay() { return this.logonDay; } public void setLogonDay(Date logonDay) { this.logonDay = logonDay; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof Sys103mId)) return false; Sys103mId castOther = (Sys103mId) other; return ((this.getOsHost() == castOther.getOsHost()) || (this .getOsHost() != null && castOther.getOsHost() != null && this.getOsHost().equals( castOther.getOsHost()))) && ((this.getOsUser() == castOther.getOsUser()) || (this .getOsUser() != null && castOther.getOsUser() != null && this.getOsUser() .equals(castOther.getOsUser()))) && ((this.getLogonDay() == castOther.getLogonDay()) || (this .getLogonDay() != null && castOther.getLogonDay() != null && this .getLogonDay().equals(castOther.getLogonDay()))); } public int hashCode() { int result = 17; result = 37 * result + (getOsHost() == null ? 0 : this.getOsHost().hashCode()); result = 37 * result + (getOsUser() == null ? 0 : this.getOsUser().hashCode()); result = 37 * result + (getLogonDay() == null ? 0 : this.getLogonDay().hashCode()); return result; } }
package proghf.view; import javafx.fxml.FXMLLoader; import proghf.Main; import proghf.controller.TableColumnController; import proghf.model.Label; import proghf.model.Table; import java.io.IOException; /** * Táblaoszlop nézete */ public class TableColumnView extends View { /** * Az oszlophoz tartozó tábla modellje */ private final Table table; /** * Az oszlophoz tartozó címke */ private final Label label; /** * A nézethez tartozó kontroller */ private TableColumnController controller; /** * Új táblaoszlop nézet létrehozása * @param table az oszlophoz tartozó tábla * @param label az oszlophoz tartozó címke */ public TableColumnView(Table table, Label label) { FXMLLoader loader = new FXMLLoader(Main.class.getResource("tableColumn.fxml")); this.table = table; this.label = label; try { view = loader.load(); controller = loader.getController(); controller.bindView(this); } catch (IOException e) { e.printStackTrace(); } } /** * A tábla modelljének lekérése * @return a tábla modellje */ public Table getTable() { return table; } /** * Az oszlophoz tartozó címke lekérése * @return az oszlophoz tartozó címke */ public Label getLabel() { return label; } /** * Az oszlop törlése */ public void delete() { if (label != null) { table.removeColumn(label); } } /** * Az oszlop újrarajzolása */ public void refresh() { controller.renderTasks(); } }
package ui; /** * 用户信息修改 */ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import Dao.Impl.UserDaoImpl; import entity.User; public class UpdataUser extends JFrame { JPanel contentPane; private JTextField txtname; private JTextField txtidentity_number; private JTextField txtaccout; private JTextField txtPassword; private UserDaoImpl userDao; public UpdataUser(User user) { setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(500, 100, 800, 800); contentPane = new JPanel(); JLabel label = new JLabel("用户姓名:"); label.setBounds(250, 100, 70, 23); add(label); txtname = new JTextField(); txtname.setBounds(350, 100, 180, 23); add(txtname); txtname.setColumns(10); txtname.setText(user.getName()); JLabel label_1 = new JLabel("证件号码"); label_1.setBounds(250, 170, 70, 23); add(label_1); txtidentity_number = new JTextField(); txtidentity_number.setBounds(350, 170, 180, 23); add(txtidentity_number); txtidentity_number.setColumns(10); txtidentity_number.setText(user.getIdentity_number()); JLabel label_2 = new JLabel("账号"); label_2.setBounds(250, 240, 70, 23); add(label_2); txtaccout = new JTextField(); txtaccout.setBounds(350, 240, 180, 23); add(txtaccout); txtaccout.setColumns(10); txtaccout.setText(user.getAccount()); JLabel label_3 = new JLabel("密码"); label_3.setBounds(250, 310, 70, 23); add(label_3); txtPassword = new JTextField(); txtPassword.setBounds(350, 310, 180, 23); add(txtPassword); txtPassword.setColumns(10); txtPassword.setText(user.getPassword()); userDao = new UserDaoImpl(); JButton btnNewButton = new JButton("修改用户"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(txtname.getText().equals("")) { //判断用户输入是否为空; JOptionPane.showMessageDialog(null, "请输入姓名","警告对话框",JOptionPane.WARNING_MESSAGE); return; } if(txtidentity_number.getText().equals("")) { //判断用户输入是否为空; JOptionPane.showMessageDialog(null, "请输入身份证号","警告对话框",JOptionPane.WARNING_MESSAGE); return; } if(txtaccout.getText().equals("")) { //判断用户输入是否为空; JOptionPane.showMessageDialog(null, "请输入账号","警告对话框",JOptionPane.WARNING_MESSAGE); return; } if(txtPassword.getText().equals("")) { //判断用户输入是否为空; JOptionPane.showMessageDialog(null, "请输入密码","警告对话框",JOptionPane.WARNING_MESSAGE); return; } try { boolean flag; int userid = user.getUserid(); String name=txtname.getText(); String identity_number=txtidentity_number.getText(); String account = txtaccout.getText(); String password = txtPassword.getText(); if (account.length()<8) { JOptionPane.showMessageDialog(null, "账号必须大于8位!"); txtname.setText(""); txtidentity_number.setText(""); txtaccout.setText(""); txtPassword.setText(""); return; } if (password.length()<8) { JOptionPane.showMessageDialog(null, "添密码必须大于8位!"); txtname.setText(""); txtidentity_number.setText(""); txtaccout.setText(""); txtPassword.setText(""); return; } User user1 = new User(userid, name, identity_number, account, password); flag = userDao.update(user1); try { if(flag){ JOptionPane.showMessageDialog(null, "修改成功"); txtname.setText(""); txtidentity_number.setText(""); txtaccout.setText(""); txtPassword.setText(""); dispose(); }else{ JOptionPane.showMessageDialog(null, "修改失败"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); btnNewButton.setBounds(320, 400, 116, 23); add(btnNewButton); } }
package com.fuzz.android.location; import android.location.Location; public interface LocationApplication { public Location getCurrentLocation(); public void startLocation(); public void endLocation(); public boolean oneTime(); }
import java.util.*; class FiveArray { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int i=0; System.out.println("Enter Array Size :"); int size=sc.nextInt(); int Arr[]=new int[size]; System.out.println("Enter Array Elements :"); for(i=0;i<Arr.length;i++) { System.out.print("Enter "+i+1+" Element :"); Arr[i]=sc.nextInt(); } System.out.println("Array "); for(i=0;i<Arr.length;i++) { System.out.print(" "+Arr[i]); } System.out.println(); int Even[]=new int[5]; int Odd[]=new int[5]; int Ecnt=0,Ocnt=0; for(i=0;i<Arr.length;i++) { if(Arr[i]%2==0) Even[Ecnt++]=Arr[i]; else Odd[Ocnt++]=Arr[i]; } int y=0; for(int k=0;k<Even.length;k++) { System.out.print(" "+Even[k]); } for(int k=0;k<Odd.length;k++) { System.out.print(" "+Odd[k]); } } }
package dev.mher.taskhunter.models.misc.task; import lombok.Getter; import lombok.Setter; /** * User: MheR * Date: 12/5/19. * Time: 2:51 PM. * Project: taskhunter. * Package: dev.mher.taskhunter.models.misc.task. */ @Getter @Setter public class CreateTaskParams { private Integer projectId; private Integer parentTaskId; private String name; private String text; }
package com.controller; import java.sql.Timestamp; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.entity.Comment; import com.entity.Demande; import com.service.BookService; import com.service.CommentService; import com.service.DeliveryCalService; import com.service.DeliveryService; import com.service.DemandeCalService; import com.service.DemandeService; import com.service.RefundService; import com.service.UserService; @Controller @RequestMapping("/comment") public class CommentController { @Resource private CommentService commentService; @Resource private UserService userService; @Resource private BookService bookService; @Resource private DemandeService demandeService; @Resource private DeliveryService deliveryService; @Resource private DeliveryCalService deliveryCalService; @Resource private DemandeCalService demandeCalService; @Resource private RefundService refundService; @ResponseBody @RequestMapping("insertComment") public String insertComment(@RequestParam(value="demandeId")String demandeId,@RequestParam(value="bookId")String bookId,@RequestParam(value="userId")String userId,@RequestParam(value="bookComment")String bookComment,@RequestParam(value="grade")String grade) { Comment comment=new Comment(); comment.setBookId(bookId.substring(1)); comment.setDemandeId(demandeId.substring(1)); comment.setUserId(userId); float t=Float.parseFloat(grade); comment.setgrade(t); comment.setBookComment(bookComment); Timestamp timestamp=new Timestamp(System.currentTimeMillis()); comment.setCommentDate(timestamp); int temp=commentService.searchCommentByBIdDid(demandeId, bookId).size(); comment.setCommentNo(Integer.toString(temp+1)); commentService.addComment(comment); Demande demande=demandeService.getDemandeByBookId(demandeId.substring(1), bookId.substring(1)).get(0); demande.setCommentOrNot(0); demandeService.updateDemande(demande); return "thanks for your comment."; } @RequestMapping("inverseToRefund") public String inverseToRefund() { return "/refund"; } @ResponseBody @RequestMapping("listComment") public Map<String, Object>listComment(@RequestParam(value="bookId")String bookId) { Map<String, Object> result=new HashMap<String,Object>(); if(commentService.searchCommentByBookId(bookId).size()==0) { result.put("status", 0); result.put("errorMsg", "no comments"); } else { List<Comment> comments=commentService.searchCommentByBookId(bookId); result.put("status", 1); result.put("data", comments); } return result; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.arbol_activacion.abs.instruccion; import com.mycompany.arbol_activacion.abs.Arbol; import com.mycompany.arbol_activacion.abs.Instruccion; import com.mycompany.arbol_activacion.abs.Nodo; import com.mycompany.arbol_activacion.abs.Tabla; import java.util.List; /** * * @author julio */ public class Programa extends Instruccion { private String id; private List<Instruccion> lstInstrucciones; private List<Instruccion> lst; public Programa(String id, List<Instruccion> lstInstrucciones, List<Instruccion> lst, int fila, int columna) { super(fila, columna); this.id = id; this.lstInstrucciones = lstInstrucciones; this.lst = lst; } public List<Instruccion> getLst() { return lst; } public void setLst(List<Instruccion> lst) { this.lst = lst; } @Override public Object interpretar(Tabla tabla, Arbol arbol) { if (lstInstrucciones != null && lstInstrucciones.size() > 0) { lstInstrucciones.forEach(x -> { x.interpretar(tabla, arbol); }); return false; } return true; } @Override public Nodo getNodo(Arbol arbol) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<Instruccion> getLstInstrucciones() { return lstInstrucciones; } public void setLstInstrucciones(List<Instruccion> lstInstrucciones) { this.lstInstrucciones = lstInstrucciones; } }
package com.fzw.education.activity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.fzw.education.R; import com.fzw.education.R.id; import com.fzw.education.R.layout; import com.fzw.education.R.menu; import com.fzw.education.db.ImportDatabase; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Point; import android.os.Bundle; import android.view.GestureDetector.OnGestureListener; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; public class MyZone_Multiple extends Activity implements OnGestureListener, OnClickListener{ private int id=2; private TextView zhangjiequestion=null; private CheckBox checkA,checkB,checkC,checkD,checkE; private Button tijiaoButton=null; private TextView zhangjiejiexi=null; private ImportDatabase impDB=null; private SQLiteDatabase sqldb=null; private ActionBar ab; private Cursor cursor=null; private String questionString=null; private GestureDetector gdDetector=null; private List<HashMap<String, String>> list=new ArrayList<HashMap<String,String>>(); private int Length=0; private int Pointer=0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.moniduoxuan); init(); id=getIntent().getExtras().getInt("MYZONE_ID"); impDB=new ImportDatabase(this); sqldb=impDB.getDB(); if(id==2){ //收藏多选 cursor=sqldb.rawQuery("select * from collect where type=1", null); } else if(id==4){ //错题多选 cursor=sqldb.rawQuery("select * from wrong where type=1", null); } if(cursor!=null&&cursor.getCount()!=0){ Length=cursor.getCount(); cursor.moveToFirst(); for(int i=0;i<cursor.getCount();++i){ HashMap<String, String> map=new HashMap<String, String>(); map.put("question", cursor.getString(cursor.getColumnIndex("question"))); map.put("A", cursor.getString(cursor.getColumnIndex("A"))); map.put("B", cursor.getString(cursor.getColumnIndex("B"))); map.put("C", cursor.getString(cursor.getColumnIndex("C"))); map.put("C", cursor.getString(cursor.getColumnIndex("D"))); map.put("E", cursor.getString(cursor.getColumnIndex("E"))); map.put("answer", cursor.getString(cursor.getColumnIndex("answer"))); map.put("jiexi", cursor.getString(cursor.getColumnIndex("jiexi"))); list.add(map); cursor.moveToNext(); } //questionString=list.get(Pointer).getString(list.get(Pointer).getColumnIndex("question")); questionString=list.get(Pointer).get("question"); zhangjiequestion.setText(questionString); checkA.setText(list.get(Pointer).get("A")); checkB.setText(list.get(Pointer).get("A")); checkC.setText(list.get(Pointer).get("A")); checkD.setText(list.get(Pointer).get("A")); checkE.setText(list.get(Pointer).get("A")); } else { checkA.setVisibility(View.INVISIBLE); checkB.setVisibility(View.INVISIBLE); checkC.setVisibility(View.INVISIBLE); checkD.setVisibility(View.INVISIBLE); checkE.setVisibility(View.INVISIBLE); tijiaoButton.setVisibility(View.INVISIBLE); if(id==2){ Toast.makeText(this, "还木有收藏", Toast.LENGTH_LONG).show(); } else if(id==4){ Toast.makeText(this, "还木有错题", Toast.LENGTH_LONG).show(); } } gdDetector=new GestureDetector(this); tijiaoButton.setOnClickListener(this); } private void init(){ zhangjiequestion=(TextView)findViewById(R.id.zhangjie_question); checkA=(CheckBox)findViewById(R.id.checkA); checkB=(CheckBox)findViewById(R.id.checkB); checkC=(CheckBox)findViewById(R.id.checkC); checkD=(CheckBox)findViewById(R.id.checkD); checkE=(CheckBox)findViewById(R.id.checkE); tijiaoButton=(Button)findViewById(R.id.tijiao); zhangjiejiexi=(TextView)findViewById(R.id.zhangjie_jiexi); ab=this.getActionBar(); ab.setDisplayHomeAsUpEnabled(true); ab.setDisplayUseLogoEnabled(false); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // TODO Auto-generated method stub return false; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub if(e1.getX()-e2.getX()>100){/* //向右划 System.out.println("下一题"); if(cursor.isLast()){ //Toast.makeText(this, "后面已经每题了", Toast.LENGTH_SHORT).show(); } else { cursor.moveToNext(); if (remain[cursor.getPosition()]==1) { questionString = cursor.getString(cursor .getColumnIndex("question")); zhangjiequestion.setText(questionString); //如果选中,则去掉 if (checkA.isChecked()) { checkA.toggle(); } if (checkB.isChecked()) { checkB.toggle(); } if (checkC.isChecked()) { checkC.toggle(); } if (checkD.isChecked()) { checkD.toggle(); } if (checkE.isChecked()) { checkE.toggle(); } checkA.setEnabled(true); checkB.setEnabled(true); checkC.setEnabled(true); checkD.setEnabled(true); checkE.setEnabled(true); checkA.setClickable(true); checkB.setClickable(true); checkC.setClickable(true); checkD.setClickable(true); checkE.setClickable(true); checkA.setText(cursor.getString(cursor.getColumnIndex("A"))); checkB.setText(cursor.getString(cursor.getColumnIndex("B"))); checkC.setText(cursor.getString(cursor.getColumnIndex("C"))); checkD.setText(cursor.getString(cursor.getColumnIndex("D"))); checkE.setText(cursor.getString(cursor.getColumnIndex("E"))); zhangjiejiexi.setText(""); } } */ if(Pointer+1>=Length){ Toast.makeText(this, "后面已经每题了", Toast.LENGTH_SHORT).show(); } else { ++Pointer; questionString = list.get(Pointer).get("question"); zhangjiequestion.setText(questionString); //如果选中,则去掉 if (checkA.isChecked()) { checkA.toggle(); } if (checkB.isChecked()) { checkB.toggle(); } if (checkC.isChecked()) { checkC.toggle(); } if (checkD.isChecked()) { checkD.toggle(); } if (checkE.isChecked()) { checkE.toggle(); } checkA.setEnabled(true); checkB.setEnabled(true); checkC.setEnabled(true); checkD.setEnabled(true); checkE.setEnabled(true); checkA.setClickable(true); checkB.setClickable(true); checkC.setClickable(true); checkD.setClickable(true); checkE.setClickable(true); checkA.setText(list.get(Pointer).get("A")); checkB.setText(list.get(Pointer).get("B")); checkC.setText(list.get(Pointer).get("C")); checkD.setText(list.get(Pointer).get("D")); checkE.setText(list.get(Pointer).get("E")); zhangjiejiexi.setText(""); } } else if(e1.getX()-e2.getX()<-100){/* //向前滑动 System.out.println("前一题"); if(cursor.isFirst()){ Toast.makeText(this, "前面没题了", Toast.LENGTH_SHORT).show(); } else { cursor.moveToPrevious(); System.out.println("cursor 向前移动一格"); if (remain[cursor.getPosition()]==1) { //没被删除 questionString = cursor.getString(cursor .getColumnIndex("question")); zhangjiequestion.setText(questionString); //如果选中,则去掉 if (checkA.isChecked()) { checkA.toggle(); } if (checkB.isChecked()) { checkB.toggle(); } if (checkC.isChecked()) { checkC.toggle(); } if (checkD.isChecked()) { checkD.toggle(); } if (checkE.isChecked()) { checkE.toggle(); } checkA.setEnabled(true); checkB.setEnabled(true); checkC.setEnabled(true); checkD.setEnabled(true); checkE.setEnabled(true); checkA.setClickable(true); checkB.setClickable(true); checkC.setClickable(true); checkD.setClickable(true); checkE.setClickable(true); System.out.println(cursor.getString(cursor .getColumnIndex("A"))); checkA.setText(cursor.getString(cursor.getColumnIndex("A"))); checkB.setText(cursor.getString(cursor.getColumnIndex("B"))); checkC.setText(cursor.getString(cursor.getColumnIndex("C"))); checkD.setText(cursor.getString(cursor.getColumnIndex("D"))); checkE.setText(cursor.getString(cursor.getColumnIndex("E"))); zhangjiejiexi.setText(""); } } */ if(Pointer-1<0){ Toast.makeText(this, "前面没题了", Toast.LENGTH_SHORT).show(); } else { --Pointer; questionString = list.get(Pointer).get("question"); zhangjiequestion.setText(questionString); //如果选中,则去掉 if (checkA.isChecked()) { checkA.toggle(); } if (checkB.isChecked()) { checkB.toggle(); } if (checkC.isChecked()) { checkC.toggle(); } if (checkD.isChecked()) { checkD.toggle(); } if (checkE.isChecked()) { checkE.toggle(); } checkA.setEnabled(true); checkB.setEnabled(true); checkC.setEnabled(true); checkD.setEnabled(true); checkE.setEnabled(true); checkA.setClickable(true); checkB.setClickable(true); checkC.setClickable(true); checkD.setClickable(true); checkE.setClickable(true); checkA.setText(list.get(Pointer).get("A")); checkB.setText(list.get(Pointer).get("B")); checkC.setText(list.get(Pointer).get("C")); checkD.setText(list.get(Pointer).get("D")); checkE.setText(list.get(Pointer).get("E")); zhangjiejiexi.setText(""); } } return true; } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub return this.gdDetector.onTouchEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub super.dispatchTouchEvent(ev); return gdDetector.onTouchEvent(ev); } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.getId()==R.id.tijiao){ Action(); } } private void Action(){ System.out.println("提交"); String ansString=list.get(Pointer).get("question"); String checkString=new String(""); if(checkA.isChecked()) checkString=checkString+"A"; if(checkB.isChecked()) checkString=checkString+"B"; if(checkC.isChecked()) checkString=checkString+"C"; if(checkD.isChecked()) checkString=checkString+"D"; if(checkE.isChecked()) checkString=checkString+"E"; if(checkString.equals("")){ Toast.makeText(MyZone_Multiple.this, "请选择答案", Toast.LENGTH_SHORT).show(); } else if(ansString.equals(checkString)){ //答对了 Toast.makeText(MyZone_Multiple.this, "答对啦", Toast.LENGTH_SHORT).show(); zhangjiejiexi.setText(list.get(Pointer).get("jiexi")); }else { //答错了 Toast.makeText(MyZone_Multiple.this, "答错啦", Toast.LENGTH_SHORT).show(); zhangjiejiexi.setText(list.get(Pointer).get("jiexi")); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode==KeyEvent.KEYCODE_BACK){ ScrollView scrollView=(ScrollView)getLayoutInflater() .inflate(R.layout.dialog_zhangjielianxi, null); AlertDialog.Builder aBuilder=new AlertDialog.Builder(this); aBuilder.setTitle("温馨提示"); aBuilder.setView(scrollView); aBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); aBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub finish(); } }); } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.my_zone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case android.R.id.home: ScrollView scrollView=(ScrollView)getLayoutInflater() .inflate(R.layout.dialog_zhangjielianxi, null); AlertDialog.Builder aBuilder=new AlertDialog.Builder(this); aBuilder.setTitle("温馨提示"); aBuilder.setView(scrollView); aBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); aBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub finish(); } }); aBuilder.show(); break; case R.id.delete: if (Length!=0) { if (id == 2) { if (cursor != null && cursor.getCount() != 0) { sqldb.execSQL("delete from collect where question='" + questionString + "'"); //删除链表某项 list.remove(Pointer); --Length; Next(); } else { Toast.makeText(this, "还木有数据", Toast.LENGTH_SHORT) .show(); } } else if (id == 4) { if (cursor != null && cursor.getCount() != 0) { sqldb.execSQL("delete from wrong where question='" + questionString + "'"); list.remove(Pointer); --Length; Next(); } else { Toast.makeText(this, "还木有数据", Toast.LENGTH_SHORT) .show(); } } } break; } return super.onOptionsItemSelected(item); } private void Next(){/* int flag=0; for(int i=0;i<cursor.getCount();++i){ if(remain[i]==1){ flag=1; } if(flag==0){ //隐藏控件 System.out.println("隐藏控件"); zhangjiequestion.setVisibility(View.INVISIBLE); checkA.setVisibility(View.INVISIBLE); checkB.setVisibility(View.INVISIBLE); checkC.setVisibility(View.INVISIBLE); checkD.setVisibility(View.INVISIBLE); checkE.setVisibility(View.INVISIBLE); tijiaoButton.setVisibility(View.INVISIBLE); return; } } if(cursor.isLast()){ cursor.moveToFirst(); } else { cursor.moveToNext(); if(remain[cursor.getPosition()]==1){ //如果选中,则去掉 if(checkA.isChecked()){ checkA.toggle(); } if(checkB.isChecked()){ checkB.toggle(); } if(checkC.isChecked()){ checkC.toggle(); } if(checkD.isChecked()){ checkD.toggle(); } if(checkE.isChecked()){ checkE.toggle(); } checkA.setEnabled(true); checkB.setEnabled(true); checkC.setEnabled(true); checkD.setEnabled(true); checkE.setEnabled(true); questionString=cursor.getString(cursor.getColumnIndex("question")); zhangjiequestion.setText(questionString); checkA.setText("A"+cursor.getString(cursor.getColumnIndex("A"))); checkB.setText("B"+cursor.getString(cursor.getColumnIndex("B"))); checkC.setText("C"+cursor.getString(cursor.getColumnIndex("C"))); checkD.setText("D"+cursor.getString(cursor.getColumnIndex("D"))); checkE.setText("E"+cursor.getString(cursor.getColumnIndex("E"))); checkA.setClickable(true); checkB.setClickable(true); checkC.setClickable(true); checkD.setClickable(true); checkE.setClickable(true); } else { Next(); } } */ if(Length==0){ //隐藏控件 System.out.println("隐藏控件"); zhangjiequestion.setVisibility(View.INVISIBLE); checkA.setVisibility(View.INVISIBLE); checkB.setVisibility(View.INVISIBLE); checkC.setVisibility(View.INVISIBLE); checkD.setVisibility(View.INVISIBLE); checkE.setVisibility(View.INVISIBLE); tijiaoButton.setVisibility(View.INVISIBLE); zhangjiejiexi.setVisibility(View.INVISIBLE); } else { //如果选中,则去掉 if(Pointer==Length){ --Pointer; } if(checkA.isChecked()){ checkA.toggle(); } if(checkB.isChecked()){ checkB.toggle(); } if(checkC.isChecked()){ checkC.toggle(); } if(checkD.isChecked()){ checkD.toggle(); } if(checkE.isChecked()){ checkE.toggle(); } checkA.setEnabled(true); checkB.setEnabled(true); checkC.setEnabled(true); checkD.setEnabled(true); checkE.setEnabled(true); questionString=list.get(Pointer).get("question"); zhangjiequestion.setText(questionString); checkA.setText(list.get(Pointer).get("A")); checkB.setText(list.get(Pointer).get("B")); checkC.setText(list.get(Pointer).get("C")); checkD.setText(list.get(Pointer).get("D")); checkE.setText(list.get(Pointer).get("E")); checkA.setClickable(true); checkB.setClickable(true); checkC.setClickable(true); checkD.setClickable(true); checkE.setClickable(true); zhangjiejiexi.setText(""); } } }
import java.util.Scanner; public class HelloWorld{ // 1、变量,常量 public static void values(){ System.out.println("常量 变量"); int a = 1; // 变量 final double pi = 3.1415926; // 常量 System.out.println(a + "\n" + pi); } // 2、字符串类型 public void string_method(){ System.out.println("字符串类型"); String s0 = "hello world!"; // 字符串类型 int ls0 = s0.length(); System.out.println(s0 +'\n' +ls0); System.out.println("1、字符串比较"); String h1 = "hello"; String h2 = "Hello"; System.out.println("用equals()比较,java和Java结果为"+h1.equals(h2)); //不忽略大小写 System.out.println("用equalsIgnoreCase()比较,java和Java结果为"+h1.equalsIgnoreCase(h2)); //忽略大小写 System.out.println(h1==h2); // == 比较对象在内存中存储地址是否一样 System.out.println("2、字符串连接 + s.concat"); String h = h1 + h2; System.out.println(h); h = h.concat(h1); System.out.println(h); System.out.println("3、索引 charAt"); char c = h.charAt(0); System.out.println(c); System.out.println("4、字符串常用的方法"); String s = "abcdefabc"; System.out.println("字符a第一次出现的位置为"+s.indexOf('a')); System.out.println("字符串bc第一次出现的位置为"+s.indexOf("bc")); System.out.println("字符a最后一次出现的位置为"+s.lastIndexOf('a')); System.out.println("从位置3开始到结束的字符串"+s.substring(3)); System.out.println("从位置3开始到6之间的字符串"+s.substring(3,6)); } // 3、 算数运算符 public void operation(){ System.out.println("算数运算符"); int a = 5; int b = 3; int c = 3; int d = 3; System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); System.out.println("a++ = " + (a++)); System.out.println("++a = " + (++a)); System.out.println("b-- = " + (b--)); System.out.println("--b = " + (--b)); System.out.println("c++ = " + (c++)); System.out.println("++d = " + (++d)); } //4、位+逻辑 运算符 public void logic_operation(){ System.out.println("位 运算符"); int a = 60; int b = 13; System.out.println("a & b = " + (a & b)); System.out.println("a | b = " + (a | b)); System.out.println("a ^ b = " + (a ^ b)); System.out.println("~a = " + (~a)); System.out.println("a << 2 = " + (a << 2)); System.out.println("a >> 2 = " + (a >> 2)); System.out.println("a >>> 2 = " + (a >>> 2)); System.out.println("逻辑 运算符"); boolean c = true; boolean d = false; System.out.println("c && d = " + (c && d)); System.out.println("c || d = " + (c || d)); System.out.println("!c = " + (!c)); System.out.println("c ^ d = " + (c ^ d)); } // 5、关系运算符 public void relation(){ System.out.println("关系运算符"); int a = 3; int b = 5; System.out.println("a == b = " + (a == b)); System.out.println("a != b = " + (a != b)); System.out.println("a > b = " + (a > b)); System.out.println("a < b = " + (a < b)); System.out.println("a >= b = " + (a >= b)); System.out.println("a <= b = " + (a <= b)); System.out.println("a > b ? a : b = " + (a > b ? a : b)); } // 6、控制台输入 public void keyboard(){ Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); System.out.println(a + b); } public static void main(String[] args){ HelloWorld hh = new HelloWorld(); //hh.values(); //hh.string_method(); // hh.operation(); // hh.logic_operation(); // hh.relation(); // hh.keyboard(); hh.values(); values(); } }
package org.point85.domain.opc.da; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Objects; import org.openscada.opc.dcom.da.PropertyDescription; import org.openscada.opc.dcom.da.impl.OPCItemProperties; import org.openscada.opc.lib.da.browser.Leaf; public class OpcDaBrowserLeaf { private static final String PATH_DELIMITERS = "\\."; private static final char PATH_DELIMITER = '.'; private OpcDaVariant dataType; private final Leaf leaf; private Collection<PropertyDescription> properties; private final OPCItemProperties propertyManager; public OpcDaBrowserLeaf(Leaf leaf, OPCItemProperties propertyManager) { this.leaf = leaf; this.propertyManager = propertyManager; } public String getItemId() { return leaf.getItemId(); } public Leaf getLeaf() { return leaf; } public Collection<PropertyDescription> getProperties() throws Exception { if (properties == null) { properties = propertyManager.queryAvailableProperties(leaf.getItemId()); } return properties; } @Override public String toString() { return getItemId(); } @Override public boolean equals(Object obj) { if (obj instanceof OpcDaBrowserLeaf) { OpcDaBrowserLeaf other = (OpcDaBrowserLeaf) obj; if (getItemId().equals(other.getItemId())) { return true; } } return false; } @Override public int hashCode() { return 41 + Objects.hashCode(leaf); } public List<String> getAccesspath() { return (LinkedList<String>) getLeaf().getParent().getBranchStack(); } public String getName() { return leaf.getName(); } public String getPathName() { StringBuilder sb = new StringBuilder(); List<String> path = getAccesspath(); for (int i = 0; i < path.size(); i++) { sb.append(path.get(i)).append(PATH_DELIMITER); } sb.append(getName()); return sb.toString(); } public static String[] getPath(String pathName) { return pathName.split(PATH_DELIMITERS); } public OpcDaVariant getDataType() { return dataType; } public void setDataType(OpcDaVariant dataType) { this.dataType = dataType; } }
package plugins.fmp.capillarytrack; import java.awt.GridLayout; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JPanel; import javax.swing.JTabbedPane; import icy.gui.util.GuiUtil; import plugins.fmp.fmpTools.EnumStatusPane; public class ResultsPane extends JPanel implements PropertyChangeListener { /** * */ private static final long serialVersionUID = 3841093170110565530L; public JTabbedPane tabsPane = new JTabbedPane(); public ResultsTab_Graphics graphicsTab = new ResultsTab_Graphics(); public ResultsTab_Excel excelTab = new ResultsTab_Excel(); public void init (JPanel mainPanel, String string, Capillarytrack parent0) { final JPanel capPanel = GuiUtil.generatePanel(string); mainPanel.add(GuiUtil.besidesPanel(capPanel)); GridLayout capLayout = new GridLayout(2, 2); graphicsTab.init(capLayout, parent0); tabsPane.addTab("Graphics", null, graphicsTab, "Display results as graphics"); graphicsTab.addPropertyChangeListener(this); excelTab.init(capLayout, parent0); tabsPane.addTab("Export", null, excelTab, "Export results to Excel"); excelTab.addPropertyChangeListener(this); tabsPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); capPanel.add(GuiUtil.besidesPanel(tabsPane)); } @Override public void propertyChange(PropertyChangeEvent arg0) { if (arg0.getPropertyName().equals("EXPORT_TO_EXCEL")) { firePropertyChange("EXPORT_TO_EXCEL", false, true); } } public void enableItems(EnumStatusPane status) { // boolean enable1 = !(status == StatusPane.DISABLED); // graphicsTab.enableItems(enable1); // excelTab.enableItems(enable1); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.mvc.method.annotation; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.ConversionNotSupportedException; import org.springframework.beans.TypeMismatchException; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.lang.Nullable; import org.springframework.validation.BindException; import org.springframework.validation.method.MethodValidationException; import org.springframework.web.ErrorResponse; import org.springframework.web.ErrorResponseException; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingPathVariableException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; import org.springframework.web.method.annotation.HandlerMethodValidationException; import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.web.servlet.resource.NoResourceFoundException; import org.springframework.web.util.WebUtils; /** * A class with an {@code @ExceptionHandler} method that handles all Spring MVC * raised exceptions by returning a {@link ResponseEntity} with RFC 7807 * formatted error details in the body. * * <p>Convenient as a base class of an {@link ControllerAdvice @ControllerAdvice} * for global exception handling in an application. Subclasses can override * individual methods that handle a specific exception, override * {@link #handleExceptionInternal} to override common handling of all exceptions, * or override {@link #createResponseEntity} to intercept the final step of creating * the {@link ResponseEntity} from the selected HTTP status code, headers, and body. * * @author Rossen Stoyanchev * @since 3.2 */ public abstract class ResponseEntityExceptionHandler implements MessageSourceAware { /** * Log category to use when no mapped handler is found for a request. * @see #pageNotFoundLogger */ public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound"; /** * Specific logger to use when no mapped handler is found for a request. * @see #PAGE_NOT_FOUND_LOG_CATEGORY */ protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY); /** * Common logger for use in subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); @Nullable private MessageSource messageSource; @Override public void setMessageSource(MessageSource messageSource) { this.messageSource = messageSource; } /** * Get the {@link MessageSource} that this exception handler uses. * @since 6.0.3 */ @Nullable protected MessageSource getMessageSource() { return this.messageSource; } /** * Handle all exceptions raised within Spring MVC handling of the request. * @param ex the exception to handle * @param request the current request */ @ExceptionHandler({ HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class, MissingPathVariableException.class, MissingServletRequestParameterException.class, MissingServletRequestPartException.class, ServletRequestBindingException.class, MethodArgumentNotValidException.class, HandlerMethodValidationException.class, NoHandlerFoundException.class, NoResourceFoundException.class, AsyncRequestTimeoutException.class, ErrorResponseException.class, ConversionNotSupportedException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, HttpMessageNotWritableException.class, MethodValidationException.class, BindException.class }) @Nullable public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) throws Exception { if (ex instanceof HttpRequestMethodNotSupportedException subEx) { return handleHttpRequestMethodNotSupported(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof HttpMediaTypeNotSupportedException subEx) { return handleHttpMediaTypeNotSupported(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof HttpMediaTypeNotAcceptableException subEx) { return handleHttpMediaTypeNotAcceptable(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof MissingPathVariableException subEx) { return handleMissingPathVariable(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof MissingServletRequestParameterException subEx) { return handleMissingServletRequestParameter(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof MissingServletRequestPartException subEx) { return handleMissingServletRequestPart(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof ServletRequestBindingException subEx) { return handleServletRequestBindingException(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof MethodArgumentNotValidException subEx) { return handleMethodArgumentNotValid(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof HandlerMethodValidationException subEx) { return handleHandlerMethodValidationException(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof NoHandlerFoundException subEx) { return handleNoHandlerFoundException(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof NoResourceFoundException subEx) { return handleNoResourceFoundException(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof AsyncRequestTimeoutException subEx) { return handleAsyncRequestTimeoutException(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } else if (ex instanceof ErrorResponseException subEx) { return handleErrorResponseException(subEx, subEx.getHeaders(), subEx.getStatusCode(), request); } // Lower level exceptions, and exceptions used symmetrically on client and server HttpHeaders headers = new HttpHeaders(); if (ex instanceof ConversionNotSupportedException theEx) { return handleConversionNotSupported(theEx, headers, HttpStatus.INTERNAL_SERVER_ERROR, request); } else if (ex instanceof TypeMismatchException theEx) { return handleTypeMismatch(theEx, headers, HttpStatus.BAD_REQUEST, request); } else if (ex instanceof HttpMessageNotReadableException theEx) { return handleHttpMessageNotReadable(theEx, headers, HttpStatus.BAD_REQUEST, request); } else if (ex instanceof HttpMessageNotWritableException theEx) { return handleHttpMessageNotWritable(theEx, headers, HttpStatus.INTERNAL_SERVER_ERROR, request); } else if (ex instanceof MethodValidationException subEx) { return handleMethodValidationException(subEx, headers, HttpStatus.INTERNAL_SERVER_ERROR, request); } else if (ex instanceof BindException theEx) { return handleBindException(theEx, headers, HttpStatus.BAD_REQUEST, request); } else { // Unknown exception, typically a wrapper with a common MVC exception as cause // (since @ExceptionHandler type declarations also match nested causes): // We only deal with top-level MVC exceptions here, so let's rethrow the given // exception for further processing through the HandlerExceptionResolver chain. throw ex; } } /** * Customize the handling of {@link HttpRequestMethodNotSupportedException}. * <p>This method logs a warning and delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleHttpRequestMethodNotSupported( HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { pageNotFoundLogger.warn(ex.getMessage()); return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link HttpMediaTypeNotSupportedException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleHttpMediaTypeNotSupported( HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link HttpMediaTypeNotAcceptableException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleHttpMediaTypeNotAcceptable( HttpMediaTypeNotAcceptableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link MissingPathVariableException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 4.2 */ @Nullable protected ResponseEntity<Object> handleMissingPathVariable( MissingPathVariableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link MissingServletRequestParameterException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleMissingServletRequestParameter( MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link MissingServletRequestPartException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleMissingServletRequestPart( MissingServletRequestPartException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link ServletRequestBindingException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleServletRequestBindingException( ServletRequestBindingException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link MethodArgumentNotValidException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to be written to the response * @param status the selected response status * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link HandlerMethodValidationException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to be written to the response * @param status the selected response status * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 6.1 */ @Nullable protected ResponseEntity<Object> handleHandlerMethodValidationException( HandlerMethodValidationException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link NoHandlerFoundException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 4.0 */ @Nullable protected ResponseEntity<Object> handleNoHandlerFoundException( NoHandlerFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link NoResourceFoundException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 6.1 */ @Nullable protected ResponseEntity<Object> handleNoResourceFoundException( NoResourceFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link AsyncRequestTimeoutException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 4.2.8 */ @Nullable protected ResponseEntity<Object> handleAsyncRequestTimeoutException( AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of any {@link ErrorResponseException}. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 6.0 */ @Nullable protected ResponseEntity<Object> handleErrorResponseException( ErrorResponseException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } /** * Customize the handling of {@link ConversionNotSupportedException}. * <p>By default this method creates a {@link ProblemDetail} with the status * and a short detail message, and also looks up an override for the detail * via {@link MessageSource}, before delegating to * {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleConversionNotSupported( ConversionNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { Object[] args = {ex.getPropertyName(), ex.getValue()}; String defaultDetail = "Failed to convert '" + args[0] + "' with value: '" + args[1] + "'"; ProblemDetail body = createProblemDetail(ex, status, defaultDetail, null, args, request); return handleExceptionInternal(ex, body, headers, status, request); } /** * Customize the handling of {@link TypeMismatchException}. * <p>By default this method creates a {@link ProblemDetail} with the status * and a short detail message, and also looks up an override for the detail * via {@link MessageSource}, before delegating to * {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleTypeMismatch( TypeMismatchException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { Object[] args = {ex.getPropertyName(), ex.getValue()}; String defaultDetail = "Failed to convert '" + args[0] + "' with value: '" + args[1] + "'"; String messageCode = ErrorResponse.getDefaultDetailMessageCode(TypeMismatchException.class, null); ProblemDetail body = createProblemDetail(ex, status, defaultDetail, messageCode, args, request); return handleExceptionInternal(ex, body, headers, status, request); } /** * Customize the handling of {@link HttpMessageNotReadableException}. * <p>By default this method creates a {@link ProblemDetail} with the status * and a short detail message, and also looks up an override for the detail * via {@link MessageSource}, before delegating to * {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleHttpMessageNotReadable( HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { ProblemDetail body = createProblemDetail(ex, status, "Failed to read request", null, null, request); return handleExceptionInternal(ex, body, headers, status, request); } /** * Customize the handling of {@link HttpMessageNotWritableException}. * <p>By default this method creates a {@link ProblemDetail} with the status * and a short detail message, and also looks up an override for the detail * via {@link MessageSource}, before delegating to * {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleHttpMessageNotWritable( HttpMessageNotWritableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { ProblemDetail body = createProblemDetail(ex, status, "Failed to write request", null, null, request); return handleExceptionInternal(ex, body, headers, status, request); } /** * Customize the handling of {@link BindException}. * <p>By default this method creates a {@link ProblemDetail} with the status * and a short detail message, and then delegates to * {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @deprecated as of 6.0 since {@link org.springframework.web.method.annotation.ModelAttributeMethodProcessor} * now raises the {@link MethodArgumentNotValidException} subclass instead. */ @Nullable @Deprecated(since = "6.0", forRemoval = true) protected ResponseEntity<Object> handleBindException( BindException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { ProblemDetail body = ProblemDetail.forStatusAndDetail(status, "Failed to bind request"); return handleExceptionInternal(ex, body, headers, status, request); } /** * Customize the handling of {@link MethodValidationException}. * <p>By default this method creates a {@link ProblemDetail} with the status * and a short detail message, and also looks up an override for the detail * via {@link MessageSource}, before delegating to * {@link #handleExceptionInternal}. * @param ex the exception to handle * @param headers the headers to use for the response * @param status the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed * @since 6.1 */ @Nullable protected ResponseEntity<Object> handleMethodValidationException( MethodValidationException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ProblemDetail body = createProblemDetail(ex, status, "Validation failed", null, null, request); return handleExceptionInternal(ex, body, headers, status, request); } /** * Convenience method to create a {@link ProblemDetail} for any exception * that doesn't implement {@link ErrorResponse}, also performing a * {@link MessageSource} lookup for the "detail" field. * @param ex the exception being handled * @param status the status to associate with the exception * @param defaultDetail default value for the "detail" field * @param detailMessageCode the code to use to look up the "detail" field * through a {@code MessageSource}, falling back on * {@link ErrorResponse#getDefaultDetailMessageCode(Class, String)} * @param detailMessageArguments the arguments to go with the detailMessageCode * @param request the current request * @return the created {@code ProblemDetail} instance * @since 6.0 */ protected ProblemDetail createProblemDetail( Exception ex, HttpStatusCode status, String defaultDetail, @Nullable String detailMessageCode, @Nullable Object[] detailMessageArguments, WebRequest request) { ErrorResponse.Builder builder = ErrorResponse.builder(ex, status, defaultDetail); if (detailMessageCode != null) { builder.detailMessageCode(detailMessageCode); } if (detailMessageArguments != null) { builder.detailMessageArguments(detailMessageArguments); } return builder.build().updateAndGetBody(this.messageSource, LocaleContextHolder.getLocale()); } /** * Internal handler method that all others in this class delegate to, for * common handling, and for the creation of a {@link ResponseEntity}. * <p>The default implementation does the following: * <ul> * <li>return {@code null} if response is already committed * <li>set the {@code "jakarta.servlet.error.exception"} request attribute * if the response status is 500 (INTERNAL_SERVER_ERROR). * <li>extract the {@link ErrorResponse#getBody() body} from * {@link ErrorResponse} exceptions, if the {@code body} is {@code null}. * </ul> * @param ex the exception to handle * @param body the body to use for the response * @param headers the headers to use for the response * @param statusCode the status code to use for the response * @param request the current request * @return a {@code ResponseEntity} for the response to use, possibly * {@code null} when the response is already committed */ @Nullable protected ResponseEntity<Object> handleExceptionInternal( Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) { if (request instanceof ServletWebRequest servletWebRequest) { HttpServletResponse response = servletWebRequest.getResponse(); if (response != null && response.isCommitted()) { if (logger.isWarnEnabled()) { logger.warn("Response already committed. Ignoring: " + ex); } return null; } } if (statusCode.equals(HttpStatus.INTERNAL_SERVER_ERROR)) { request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST); } if (body == null && ex instanceof ErrorResponse errorResponse) { body = errorResponse.updateAndGetBody(this.messageSource, LocaleContextHolder.getLocale()); } return createResponseEntity(body, headers, statusCode, request); } /** * Create the {@link ResponseEntity} to use from the given body, headers, * and statusCode. Subclasses can override this method to inspect and possibly * modify the body, headers, or statusCode, e.g. to re-create an instance of * {@link ProblemDetail} as an extension of {@link ProblemDetail}. * @param body the body to use for the response * @param headers the headers to use for the response * @param statusCode the status code to use for the response * @param request the current request * @return the {@code ResponseEntity} instance to use * @since 6.0 */ protected ResponseEntity<Object> createResponseEntity( @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) { return new ResponseEntity<>(body, headers, statusCode); } }
package com.sohu.live56.view.util; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Space; import android.widget.TabHost; import com.sohu.live56.R; /** * TODO: document your custom view class. */ public class HomeTabHost extends ViewGroup implements CompoundButton.OnCheckedChangeListener { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (buttonView.getId() == R.id.tab_right_btn1) { leftBtn.setChecked(false); leftBtn.setEnabled(true); rightBtn.setEnabled(false); if (onTabButonCheckedListener != null) { onTabButonCheckedListener.onRightChecked(buttonView); } } else if (buttonView.getId() == R.id.tab_left_btn1) { rightBtn.setChecked(false); rightBtn.setEnabled(true); leftBtn.setEnabled(false); if (onTabButonCheckedListener != null) { onTabButonCheckedListener.onLeftChecked(buttonView); } } } } public interface OnTabButonCheckedListener { public void onLeftChecked(View view); public void onRightChecked(View view); public void onCenterClickedListener(); } public static class Position { int left, top, right, bottom; public void setPosition(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } } private View contentView = null; private View divideView = null; private View tabBgView = null; private ImageView centerImg = null; private CheckBox leftBtn = null; private CheckBox rightBtn = null; private Position tabBgViewPosition = new Position(); private Position divideViewPosition = new Position(); private Position leftBtnPosition = new Position(); private Position centerBtnPosition = new Position(); private Position rightBtnPosition = new Position(); private OnTabButonCheckedListener onTabButonCheckedListener; public void setOnTabButonCheckedListener(OnTabButonCheckedListener onTabButonCheckedListener) { this.onTabButonCheckedListener = onTabButonCheckedListener; } public HomeTabHost(Context context, AttributeSet attrs) { super(context, attrs); } /** * 使ViewGroup的LayoutParams支持margin. * * @param attrs * @return */ public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); int cCount = getChildCount(); for (int i = 0; i < cCount; i++) { View cView = getChildAt(i); switch (cView.getId()) { case android.R.id.tabcontent: { contentView = cView; break; } case R.id.tab_bg_view_divid: { divideView = cView; break; } case R.id.tab_bg_view: { tabBgView = cView; break; } case R.id.tab_left_btn1: { leftBtn = (CheckBox) cView; if (leftBtn.isChecked()) leftBtn.setEnabled(false); leftBtn.setOnCheckedChangeListener(this); break; } case R.id.tab_center_btn: { centerImg = (ImageView) cView; centerImg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (onTabButonCheckedListener != null) onTabButonCheckedListener.onCenterClickedListener(); } }); break; } case R.id.tab_right_btn1: { rightBtn = (CheckBox) cView; if (rightBtn.isChecked()) rightBtn.setEnabled(false); rightBtn.setOnCheckedChangeListener(this); break; } } } } public void checkRightBtn() { rightBtn.setChecked(true); } public void checkLeftBtn() { leftBtn.setChecked(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //获取此ViewGroup上级容器为其推荐的宽和高,以及计算模式。 int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); int totalUsedHeihgt = 0; int totalUsedWidth = 0; //计算childView的宽和高。 for (int i = 0; i < getChildCount(); i++) { View childView = getChildAt(i); if (childView.getId() == android.R.id.tabcontent) { //i=4;最后计算tabcontent. measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, totalUsedHeihgt); } else { //计算出除tabcontent 外的childView的尺寸。 measureChild(childView, widthMeasureSpec, heightMeasureSpec); if (childView.getId() == R.id.tab_bg_view_divid || childView.getId() == R.id.tab_left_btn1) totalUsedHeihgt += childView.getMeasuredHeight(); //tab用去的height。 } } setMeasuredDimension(sizeWidth, sizeHeight); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { layoutTabBgView(tabBgView, leftBtn.getMeasuredHeight()); layoutTabDividView(divideView); layoutContentView(contentView); layoutCenterImg(centerImg); layoutLeftBtn(leftBtn, centerBtnPosition.left); layoutRightBtn(rightBtn, centerBtnPosition.right); } private void layoutTabBgView(View view, int height) { // int width = getWidth(); //mactch parent MarginLayoutParams mLayoutParams = (MarginLayoutParams) view.getLayoutParams(); int left, top, right, bottom; left = mLayoutParams.leftMargin ; top = getHeight() - height - mLayoutParams.bottomMargin; right = mLayoutParams.leftMargin + view.getMeasuredWidth(); bottom = getHeight() - mLayoutParams.bottomMargin; view.layout(left, top, right, bottom); tabBgViewPosition.setPosition(left - mLayoutParams.leftMargin, top - mLayoutParams.topMargin, right + mLayoutParams.rightMargin, bottom + mLayoutParams.bottomMargin); } private void layoutTabDividView(View view) { MarginLayoutParams mLayoutParams = (MarginLayoutParams) view.getLayoutParams(); int left, top, right, bottom; left = mLayoutParams.leftMargin; top = tabBgViewPosition.top - view.getMeasuredHeight() - mLayoutParams.bottomMargin; right = mLayoutParams.leftMargin + view.getMeasuredWidth(); bottom = tabBgViewPosition.top - mLayoutParams.bottomMargin; view.layout(left, top, right, bottom); divideViewPosition.setPosition(left - mLayoutParams.leftMargin, top - mLayoutParams.topMargin, right + mLayoutParams.rightMargin, bottom + mLayoutParams.bottomMargin); } private void layoutContentView(View view) { MarginLayoutParams mLayoutParams = (MarginLayoutParams) view.getLayoutParams(); int left, top, right, bottom; left = mLayoutParams.leftMargin; top = mLayoutParams.topMargin; right = getWidth() - mLayoutParams.rightMargin; bottom = divideViewPosition.top - mLayoutParams.bottomMargin; int height = view.getMeasuredHeight(); view.layout(left, top, right, bottom); } private void layoutCenterImg(View view) { MarginLayoutParams mLayoutParams = (MarginLayoutParams) view.getLayoutParams(); int left, top, right, bottom; left = (getWidth() - view.getMeasuredWidth()) / 2; top = getMeasuredHeight() - view.getMeasuredHeight() - mLayoutParams.bottomMargin; right = left + view.getMeasuredWidth(); bottom = getHeight() - mLayoutParams.bottomMargin; view.layout(left, top, right, bottom); centerBtnPosition.setPosition(left - mLayoutParams.leftMargin, top - mLayoutParams.topMargin, right + mLayoutParams.rightMargin, bottom + mLayoutParams.bottomMargin); } /** * @param view * @param _right half of the center button height. */ private void layoutLeftBtn(View view, int _right) { MarginLayoutParams mLayoutParams = (MarginLayoutParams) view.getLayoutParams(); int left, top, right, bottom; left = mLayoutParams.leftMargin; top = getHeight() - view.getMeasuredHeight() - mLayoutParams.bottomMargin; right = _right - mLayoutParams.rightMargin; bottom = getHeight() - mLayoutParams.bottomMargin; view.layout(left, top, right, bottom); leftBtnPosition.setPosition(left - mLayoutParams.leftMargin, top - mLayoutParams.topMargin, right + mLayoutParams.rightMargin, bottom + mLayoutParams.bottomMargin); } private void layoutRightBtn(View view, int _left) { MarginLayoutParams mLayoutParams = (MarginLayoutParams) view.getLayoutParams(); int left, top, right, bottom; left = _left + mLayoutParams.leftMargin; top = getHeight() - view.getMeasuredHeight() - mLayoutParams.bottomMargin; right = getWidth() - mLayoutParams.rightMargin; bottom = getHeight() - mLayoutParams.bottomMargin; view.layout(left, top, right, bottom); rightBtnPosition.setPosition(left - mLayoutParams.leftMargin, top - mLayoutParams.topMargin, right + mLayoutParams.rightMargin, bottom + mLayoutParams.bottomMargin); } public void setLeftBtnChecked() { leftBtn.setChecked(true); } public void setRightBtnChecked() { rightBtn.setChecked(true); } }
package com.mmm.service.advices; import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect.Method; /** * 前置通知 */ public class BeforeAdvice implements MethodBeforeAdvice { /** * 在目标方法执行之前 * @param method 目标方法 * @param objects 目标方法参数列表 * @param o 目标对象 * @throws Throwable */ @Override public void before(Method method, Object[] objects, Object o) throws Throwable { /* System.out.println("target的名称===》"+o); System.out.println("method的名称"+method.getName()); */ System.out.println("执行--前置--通知"); } }
package com.fubang.wanghong.model; import com.fubang.wanghong.model.impl.ActorModelImpl; import com.fubang.wanghong.model.impl.AnchorModelImpl; import com.fubang.wanghong.model.impl.FavoriteModelImpl; import com.fubang.wanghong.model.impl.FollowModelImpl; import com.fubang.wanghong.model.impl.GiftTopModelImpl; import com.fubang.wanghong.model.impl.HomeHeadPicModelImpl; import com.fubang.wanghong.model.impl.HomeIconModelImpl; import com.fubang.wanghong.model.impl.HomeModelImpl; import com.fubang.wanghong.model.impl.RichModelImpl; import com.fubang.wanghong.model.impl.RoomListModelImpl; /** * model工厂类 * Created by dell on 2016/4/5. */ public class ModelFactory { private static volatile ModelFactory instance = null; private ModelFactory(){ } public static ModelFactory getInstance() { if (instance == null) { synchronized (ModelFactory.class) { if (instance == null) { instance = new ModelFactory(); } } } return instance; } public HomeHeadPicModelImpl getHomeHeadPicModelImpl(){ return HomeHeadPicModelImpl.getInstance(); } public HomeIconModelImpl getHomeIconModelImpl(){ return HomeIconModelImpl.getInstance(); } public HomeModelImpl getHomeModelImpl(){ return HomeModelImpl.getInstance(); } public RoomListModelImpl getRoomListModelImpl(){ return RoomListModelImpl.getInstance(); } public RichModelImpl getRichModelImpl(){return RichModelImpl.getInstance();} public GiftTopModelImpl getGiftTopModelImpl(){return GiftTopModelImpl.getInstance();} public AnchorModelImpl getAnchorModelImpl(){return AnchorModelImpl.getInstance();} public FavoriteModelImpl getFavoriteModelImpl(){ return FavoriteModelImpl.getInstance(); } public ActorModelImpl getActorModelImpl(){return ActorModelImpl.getInstance();} public FollowModelImpl getFollowModelImpl(){ return FollowModelImpl.getInstance(); } }
package com.nikita.recipiesapp.views.steps; import com.airbnb.epoxy.EpoxyAttribute; import com.airbnb.epoxy.EpoxyModelWithHolder; import com.nikita.recipiesapp.R; import com.nikita.recipiesapp.common.models.Ingredient; import com.nikita.recipiesapp.views.common.TextViewHolder; class IngredientModel extends EpoxyModelWithHolder<TextViewHolder> { @EpoxyAttribute Ingredient ingredient; @Override protected int getDefaultLayout() { return R.layout.step_list_ingredient_item; } @Override protected TextViewHolder createNewHolder() { return new TextViewHolder(); } @Override public void bind(TextViewHolder holder) { super.bind(holder); holder.text.setText(ingredient.description); } }
package com.gazlaws.codeboard.layout; import com.gazlaws.codeboard.layout.builder.KeyInfo; public class Key { public Box box; public KeyInfo info; }
package com.as.boot.txffc.thread; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import com.as.boot.txffc.controller.ExampleControll; import com.as.boot.txffc.frame.AnyThreeFrame5; import com.as.boot.utils.ZLinkStringUtils; public class AnyThreeThread5 implements Runnable{ private Double zslr = 0d; //盈利回头值 private Double zslr_return = 0d; private Double mnlr = 0d; private String[] fa = {"个","十","百","千","万"}; //private HashMap<String,String> clMap = null; private List<HashMap<String, String>> clList = null; private Double baseMoney = 0.002; //连挂数 private List<Integer> failCountList = Arrays.asList(0,0,0,0,0); //最大连挂 private List<Integer> maxFailCountList = Arrays.asList(0,0,0,0,0); //倍投情况 private List<Integer> btNumList = Arrays.asList(0,0,0,0,0); //中奖情况 private List<Boolean> zjFlagList = Arrays.asList(false,false,false,false,false); //倍投阶梯 private Integer[] btArr = null; private DecimalFormat df = new DecimalFormat("#.000"); private Integer pl = 950; //策略命中数 private List<Integer> sulCountList = Arrays.asList(0,0,0,0,0); //每次策略盈利 private Double everyClYl = 0d; private Double changeClYl = null; @Override public void run() { //初始化投注策略 initTXFFCL(); //初始化盈利回头 if(zslr_return==null&&ZLinkStringUtils.isNotEmpty(AnyThreeFrame5.returnField.getText())) zslr_return = zslr + Double.parseDouble(AnyThreeFrame5.returnField.getText()); //初始化倍投阶梯 String[] btStrArr = AnyThreeFrame5.btArrayField.getText().split(","); btArr = new Integer[btStrArr.length]; for (int i = 0; i < btStrArr.length; i++) btArr[i] = Integer.parseInt(btStrArr[i]); while (true) { try { if(ZLinkStringUtils.isNotEmpty(AnyThreeFrame5.changeYlField.getText())) //初始化倍投阶梯 changeClYl = Double.parseDouble(AnyThreeFrame5.changeYlField.getText()); String resultRound = ExampleControll.FFCRound; String resultKj = ExampleControll.FFCResult; if(ZLinkStringUtils.isNotEmpty(resultKj)){ //更新倍投阶梯 btStrArr = AnyThreeFrame5.btArrayField.getText().split(","); btArr = new Integer[btStrArr.length]; for (int i = 0; i < btStrArr.length; i++) btArr[i] = Integer.parseInt(btStrArr[i]); //将开奖结果取出为数组 String[] kjArray = resultKj.split(","); Double resultRound_i = Double.parseDouble(resultRound); if(AnyThreeFrame5.FFCRound == null || !AnyThreeFrame5.FFCRound.equals(resultRound)){ AnyThreeFrame5.kjTableDefaultmodel.insertRow(0, new String[]{resultRound,resultKj}); //判断是否有投注 if(AnyThreeFrame5.FFCRound !=null && Double.parseDouble(AnyThreeFrame5.FFCRound) == (resultRound_i-1)){ if(clList!=null&&clList.size()>0){ Double tempLr = 0d; Integer clIndex = 0; Integer tableIndex = 0; //利润 for (int i = 0, il = clList.size(); i<il;i++) { HashMap<String, String> clItem = clList.get(i); //key为0则代表无策略 if(!clItem.get("position").equals("0")){ //获取策略注数 String[] clArr = clItem.get("cl").split(","); String key = clItem.get("position"); //累计投入值 tempLr += -clArr.length * baseMoney * btArr[btNumList.get(clIndex)]; String result = ""; //获取下注位置并截取开奖结果 for (int j = 0; j < key.length(); j++) { result += kjArray[Integer.parseInt(key.charAt(j)+"")]; } //判断是否中奖 if(clItem.get("cl").contains(result)){ zjFlagList.set(clIndex, true); failCountList.set(clIndex, 0); AnyThreeFrame5.tableDefaultmodel.setValueAt("中", tableIndex, 7); //计算盈利值 Double itemLr = btArr[btNumList.get(clIndex)] * baseMoney * pl; tempLr += itemLr; AnyThreeFrame5.tableDefaultmodel.setValueAt("0/"+maxFailCountList.get(clIndex), tableIndex, 4); AnyThreeFrame5.tableDefaultmodel.setValueAt(df.format(itemLr), tableIndex, 3); //记录策略命中数 sulCountList.set(clIndex, sulCountList.get(clIndex)+1); }else{ zjFlagList.set(clIndex, false); failCountList.set(clIndex, failCountList.get(clIndex) + 1); if(failCountList.get(clIndex)>maxFailCountList.get(clIndex)) maxFailCountList.set(clIndex, failCountList.get(clIndex)); //记录连挂数 AnyThreeFrame5.tableDefaultmodel.setValueAt(failCountList.get(clIndex)+"/"+maxFailCountList.get(clIndex), tableIndex, 4); AnyThreeFrame5.tableDefaultmodel.setValueAt("挂", tableIndex, 7); Double tempFailP = -clArr.length * baseMoney * btArr[btNumList.get(clIndex)]; AnyThreeFrame5.tableDefaultmodel.setValueAt(df.format(tempFailP), tableIndex, 3); } AnyThreeFrame5.tableDefaultmodel.setValueAt(resultKj, tableIndex, 6); AnyThreeFrame5.tableDefaultmodel.setValueAt(sulCountList.get(clIndex), tableIndex, 5); tableIndex++; } clIndex++; } zslr += tempLr; everyClYl += tempLr; AnyThreeFrame5.szYkValueLabel.setText(df.format(zslr)); if(ZLinkStringUtils.isNotEmpty(AnyThreeFrame5.returnField.getText())&&zslr >= zslr_return){ zslr_return = zslr + Double.parseDouble(AnyThreeFrame5.returnField.getText()); //达到盈利回头目标,所有倍投全部回到起点 btNumList.set(0, 0); btNumList.set(1, 0); btNumList.set(2, 0); btNumList.set(3, 0); btNumList.set(4, 0); }else{ //未达到盈利回头目标,所有挂的增加倍数 for (int i = 0; i < zjFlagList.size(); i++) { if(zjFlagList.get(i)){ //中的初始化倍投 btNumList.set(i, 0); }else{ //判断是否已超出倍投 if(btNumList.get(i)>=btArr.length-1) //超出倍投则回归初始 btNumList.set(i, 0); else //挂的网上倍投 btNumList.set(i, btNumList.get(i)+1); } } } } }else{ //断期 } //是否投注 if(AnyThreeFrame5.button.getText().equals("停止执行")){ Integer _index = 0; for (int i = clList.size()-1; i>=0; i--) { //判断是否需要更改策略,命中changeClYl期更换一次策略 if(sulCountList.get(i)>=changeClYl){ rfreshTXFFCL(i); sulCountList.set(i, 0); } HashMap<String, String> clItem = clList.get(i); if(!clItem.get("position").equals("0")){ if(_index == 0) AnyThreeFrame5.tableDefaultmodel.insertRow(0, new String[]{"--","--","--","--","--","--","--","--","--"}); AnyThreeFrame5.tableDefaultmodel.insertRow(0, new String[]{df.format(resultRound_i + 1),clItem.get("position")+clItem.get("cl"),btArr[btNumList.get(i)].toString(),"--","--","--","待开奖","待开奖","--"}); _index++; } } } AnyThreeFrame5.FFCRound = resultRound; AnyThreeFrame5.FFCResult = resultKj; Thread.sleep(30000);//更新到数据后睡眠30s }else if(AnyThreeFrame5.FFCRound.equals(resultRound)){ Thread.sleep(1000);//未更新到数据睡眠3s } }else Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } //初始化策略 public void initTXFFCL(){ //获取历史开奖情况 String historyRound = historyResult(); //统计历史期数 Integer historyNum = Integer.parseInt(AnyThreeFrame5.historyNumField.getText()); //是否系统初始化策略,只能是 Integer initClFlag = 1; //初始化策略组数 Integer initClNum = Integer.parseInt(AnyThreeFrame5.initClNumField.getText()); //策略数 Integer clNum = Integer.parseInt(AnyThreeFrame5.clNumField.getText()); //期望最大连挂数 Integer aimMaxFail = Integer.parseInt(AnyThreeFrame5.aimMaxFailField.getText()); //重置次数 Integer maxRestN = Integer.parseInt(AnyThreeFrame5.maxRestNField.getText()); Integer _index = 1; List<HashMap<String, String>> temClList = new ArrayList<HashMap<String,String>>(); HashMap<String, String> tempClMap = null; String clname = ""; String clPosition = ""; try { for (int i = 0, il = AnyThreeFrame5.clBoxList.size(); i < il; i++) { if(AnyThreeFrame5.clBoxList.get(i).isSelected()){ clname += _index-1; clPosition += (_index-1)+","; } if(_index%5==0){ tempClMap = new HashMap<String, String>(); _index = 1; if(clname != ""){ tempClMap.put("position", clname); tempClMap.put("cl", getTXFFCL(historyRound, historyNum, clPosition.substring(0,clPosition.length()-1), null, initClFlag, initClNum, clNum, aimMaxFail, maxRestN)); }else tempClMap.put("position", "0");//未选中则标记为空策略 clname = ""; clPosition = ""; temClList.add(tempClMap); }else _index++; } clList = temClList; //更换策略后倍投全部回到起点 btNumList.set(0, 0); btNumList.set(1, 0); btNumList.set(2, 0); btNumList.set(3, 0); btNumList.set(4, 0); } catch (Exception e) { e.printStackTrace(); } } public void rfreshTXFFCL(Integer clIndex){ //获取历史开奖情况 String historyRound = historyResult(); //统计历史期数 Integer historyNum = Integer.parseInt(AnyThreeFrame5.historyNumField.getText()); //是否系统初始化策略,只能是 Integer initClFlag = 1; //初始化策略组数 Integer initClNum = Integer.parseInt(AnyThreeFrame5.initClNumField.getText()); //策略数 Integer clNum = Integer.parseInt(AnyThreeFrame5.clNumField.getText()); //期望最大连挂数 Integer aimMaxFail = Integer.parseInt(AnyThreeFrame5.aimMaxFailField.getText()); //重置次数 Integer maxRestN = Integer.parseInt(AnyThreeFrame5.maxRestNField.getText()); Integer _index = 1; Integer cl_item = 0; HashMap<String, String> tempClMap = null; String clname = ""; String clPosition = ""; try { for (int i = 0, il = AnyThreeFrame5.clBoxList.size(); i < il; i++) { if(AnyThreeFrame5.clBoxList.get(i).isSelected()){ clname += _index-1; clPosition += (_index-1)+","; } if(_index%5==0){ if(cl_item.equals(clIndex)){ tempClMap = new HashMap<String, String>(); if(clname != ""){ tempClMap.put("position", clname); tempClMap.put("cl", getTXFFCL(historyRound, historyNum, clPosition.substring(0,clPosition.length()-1), null, initClFlag, initClNum, clNum, aimMaxFail, maxRestN)); }else tempClMap.put("position", "0");//未选中则标记为空策略 clname = ""; clPosition = ""; clList.set(clIndex, tempClMap); break; }else { clname = ""; clPosition = ""; } cl_item++; _index = 1; }else _index++; } } catch (Exception e) { e.printStackTrace(); } } public String getTXFFCL(String historyRound, Integer historyNum, String putPosition, String initCl, Integer initClFlag, Integer initClNum, Integer clNum, Integer aimMaxFail, Integer maxRestN){ //初始化历史开奖 String[] historyArr = historyRound.trim().split(";"); if(historyNum != null && historyNum > 0) historyArr = Arrays.copyOfRange(historyArr, 0, historyNum); List<String> clList = new ArrayList<String>(); //策略组数如果没有设定则默认为50组 clNum = clNum==null||clNum==0?50:clNum; Integer failCount = 0; Integer maxFailCount = 0; Integer historymaxFail = 0; String maxFailResult = null; //记录最佳策略 Integer bestMaxFail = 0; List<String> bestClList = null; //解析需要投注的位置 String[] positionArr = putPosition.split(","); //获取星数 Integer positionNum = positionArr.length; Integer[] positionArr_i = new Integer[positionArr.length]; for (int i = 0; i < positionArr.length; i++) positionArr_i[i] = Integer.parseInt(positionArr[i]); aimMaxFail = aimMaxFail==null?7:aimMaxFail; //最多重置策略次数 maxRestN = maxRestN==null?200:maxRestN; //获取初始策略 if(initClFlag == 0 && initCl!=null){ String[] initClArr = initCl.split(","); for (String string : initClArr) clList.add(string); }else{ //若无初始策略则用随机数生成固定数量的初始策略 initClNum = initClNum == null||initClNum == 0?40:initClNum; if(positionNum==2)clList = createInitFFCCL_2(initClNum); else if(positionNum==3)clList = createInitFFCCL_3(initClNum); else if(positionNum==4)clList = createInitFFCCL_4(initClNum); } //遍历历史开奖 while (maxRestN != 0) { //反向循环 for (int i = historyArr.length-1; i >= 0; i--) { if(ZLinkStringUtils.isNotEmpty(historyArr[i])){ if(historyArr[i].trim().split(",").length > 1){ //获取开奖 String item_result = historyArr[i].trim().split(",")[1].trim(); String result = ""; for (int j = 0, jl = positionArr_i.length; j < jl; j++) result += item_result.charAt(positionArr_i[j]); if(clList.contains(result)){ //中 failCount = 0; }else{ failCount++; if(failCount > maxFailCount){ //更新最大连挂及重置连挂出奖记录 maxFailCount = failCount; maxFailResult = result; //达到历史最高则可直接停止当前循环 if(historymaxFail == failCount) break; } } } } } //将最大连挂的开奖结果加入策略 if(clList.size()<clNum) clList.add(maxFailResult); //已经没有连挂则退出循环 if(maxFailCount == 0)break; if(clList.size()==clNum){ if(bestMaxFail==0||bestMaxFail>maxFailCount){ bestMaxFail = maxFailCount; bestClList = clList; } //如果连挂小于等于预期,则退出循环返回结果 if(maxFailCount <= aimMaxFail){ break; }else{ //如果不符合预期则重新执行(系统生成随机数的才能重新执行) if(initClFlag == 1){ //重置系统随机初始策略 if(positionNum==2)clList = createInitFFCCL_2(initClNum); else if(positionNum==3)clList = createInitFFCCL_3(initClNum); else if(positionNum==4)clList = createInitFFCCL_4(initClNum); failCount = 0; maxFailResult = null; //控制循环次数为maxRestN次,防止无限循环 maxRestN --; }else break; } } //循环完一期后将最大重新计算 if(maxRestN!=0){ historymaxFail = maxFailCount; maxFailCount = 0; maxFailResult = null; } } return bestClList.toString(); } public static List<String> createInitFFCCL_2(Integer initClNum){ List<String> list = new ArrayList<String>(); for (int i = 0; i < initClNum; i++) { String item = null; item = createRandom()+""+createRandom(); while (true) { if(list.contains(item)) item = createRandom()+""+createRandom(); else{ list.add(item); break; } } } return list; } public static List<String> createInitFFCCL_3(Integer initClNum){ List<String> list = new ArrayList<String>(); for (int i = 0; i < initClNum; i++) { String item = null; item = createRandom()+""+createRandom()+""+createRandom(); while (true) { if(list.contains(item)) item = createRandom()+""+createRandom()+""+createRandom(); else{ list.add(item); break; } } } return list; } public static List<String> createInitFFCCL_4(Integer initClNum){ List<String> list = new ArrayList<String>(); for (int i = 0; i < initClNum; i++) { String item = null; item = createRandom()+""+createRandom()+""+createRandom()+""+createRandom(); while (true) { if(list.contains(item)) item = createRandom()+""+createRandom()+""+createRandom()+""+createRandom(); else{ list.add(item); break; } } } return list; } public static Integer createRandom(){ return (int)(Math.random()*10); } //根据文件获取历史开奖记录 public String historyResult(){ StringBuilder fileContent = new StringBuilder(); try { File file = new File("G:/modeng_gj/OpenCode/TXFFC.txt"); if(!file.exists()) file = new File("E:/modeng_gj/OpenCode/TXFFC.txt"); //获取文件内容 BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String lineTxt = null; while ((lineTxt = bfr.readLine()) != null) { fileContent.append(lineTxt.trim().replace(" ", ",")).append(";"); } bfr.close(); } catch (Exception e) { e.printStackTrace(); } return fileContent.toString(); } }
import java.util.*; import java.lang.*; class GFG { // Fucntion to calculate sum public static int summation(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code public static void main(String args[]) { int n = 100; System.out.println(summation(n)); } } //Sum of the squares //338350 //5050 //25,502,500
package org.example.codingtest.oneLevel; public class IntegerSquare { public static void main(String[] args) { int n = 3; long solution = solution(n); System.out.println(solution); } public static long solution(long n) { double sqrt = Math.sqrt(n); String s = String.valueOf(sqrt); String[] split = s.split("\\."); int[] arr = {10}; // if (!(split[1].length()>1) && Integer.parseInt(split[1])==0) return (long) Math.pow(Double.parseDouble(split[0])+1,2); return -1; } }
/********************************************************************** Copyright (c) 2014 Baris ERGUN and others. All rights reserved. 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. Contributors: ... **********************************************************************/ package org.datanucleus.store.cassandra.query; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.datanucleus.ExecutionContext; import org.datanucleus.FetchPlan; import org.datanucleus.store.query.AbstractQueryResult; import org.datanucleus.store.query.AbstractQueryResultIterator; import org.datanucleus.store.query.Query; import org.datanucleus.util.Localiser; import org.datanucleus.util.StringUtils; public class CassandraQueryResult extends AbstractQueryResult { private static final long serialVersionUID = -3428653031644090769L; /** The ResultSet containing the results. */ private ResultSet rs; /** The Result Objects. */ private List<Row> resultObjs = new ArrayList(); private List resultIds = null; /** resultObjsIndex used by iterator */ private int resultObjsIndex = 0; // TODO applyRangeChecks public CassandraQueryResult(Query query, ResultSet rs) { super(query); this.rs = rs; if (query.useResultsCaching()) { resultIds = new ArrayList(); } } public void initialise() { int fetchSize = query.getFetchPlan().getFetchSize(); if (!rs.iterator().hasNext()) { // ResultSet is empty, so just close it closeResults(); return; } if (fetchSize == FetchPlan.FETCH_SIZE_GREEDY) { // "greedy" mode, so load all results now advanceToEndOfResultSet(); } else if (fetchSize > FetchPlan.FETCH_SIZE_OPTIMAL) { // Load "fetchSize" results now processNumberOfResults(fetchSize); } } /** * Internal method to advance to the end of the ResultSet, populating the resultObjs, and close the * ResultSet when complete. */ private void advanceToEndOfResultSet() { processNumberOfResults(-1); } /** * Internal method to fetch remaining results into resultsObjs */ private void fetchMoreResults() { if (!rs.isFullyFetched()) { resultObjsIndex = 0; resultObjs.clear(); rs.fetchMoreResults(); int fetchSize = query.getFetchPlan().getFetchSize(); ExecutionContext ec = query.getExecutionContext(); for (int i = 0; i < fetchSize; i++) { Row row = rs.one(); if (null == row) { break; } resultObjs.add(row); if (resultIds != null) { resultIds.add(ec.getApiAdapter().getIdForObject(row)); } } } else { closeResults(); } } /** * Method to advance through the results, processing the specified number of results. * @param number Number of results (-1 means process all) */ private void processNumberOfResults(int number) { ExecutionContext ec = query.getExecutionContext(); if (FetchPlan.FETCH_SIZE_GREEDY >= number) { if (resultIds != null) { Iterator<Row> rowIter = rs.iterator(); while (rowIter.hasNext()) { Row row = rs.one(); resultObjs.add(row); resultIds.add(ec.getApiAdapter().getIdForObject(row)); } } else { resultObjs = rs.all(); } } else { for (int i = 0; i < number; i++) { Row row = rs.one(); if (null == row) { break; } resultObjs.add(row); if (resultIds != null) { resultIds.add(ec.getApiAdapter().getIdForObject(row)); } } } } @Override protected void closingConnection() { } @Override public void disconnect() { if (query == null) { // Already disconnected return; } rs = null; resultObjs = null; } /** * Method to close the results, meaning that they are inaccessible after this point. */ @Override public synchronized void close() { super.close(); rs = null; resultObjs = null; } /** * Internal method to close the ResultSet. */ @Override protected void closeResults() { if (resultIds != null) { // Cache the results with the QueryManager query.getQueryManager().addQueryResult(query, query.getInputParameters(), resultIds); resultIds = null; } } @Override public boolean equals(Object o) { if (null == o || !(o instanceof CassandraQueryResult)) { return false; } CassandraQueryResult other = (CassandraQueryResult) o; if (rs != null) { return other.rs == rs; } else if (query != null) { return other.query == query; } return StringUtils.toJVMIDString(other).equals(StringUtils.toJVMIDString(this)); } @Override public int hashCode() { if (rs != null) { return rs.hashCode(); } else if (query != null) { return query.hashCode(); } return StringUtils.toJVMIDString(this).hashCode(); } @Override public Object get(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } return null; } @Override public Iterator iterator() { return new QueryResultIterator(); } @Override public ListIterator listIterator() { return new QueryResultIterator(); } private class QueryResultIterator extends AbstractQueryResultIterator { /** hold the last element **/ Row currentElement = null; @Override public boolean hasNext() { synchronized (CassandraQueryResult.this) { if (!isOpen()) { // Spec 14.6.7 Calling hasNext() on closed Query will return false return false; } if (null != resultObjs && resultObjsIndex < resultObjs.size()) { return true; } return false; } } @Override public Object next() { synchronized (CassandraQueryResult.this) { if (!isOpen()) { // Spec 14.6.7 Calling next() on closed Query will throw NoSuchElementException throw new NoSuchElementException(Localiser.msg("052600")); } int resultObjsSize = resultObjs.size(); if (resultObjsIndex < resultObjsSize) { currentElement = resultObjs.get(resultObjsIndex++); if (resultObjsIndex == resultObjsSize) { fetchMoreResults(); } return currentElement; } throw new NoSuchElementException(Localiser.msg("052602")); } } @Override public boolean hasPrevious() { // We only navigate in forward direction, Cassandra issues mention // about scrolling but looks like not implemented ref:CASSANDRA-2876 throw new UnsupportedOperationException("Not yet implemented"); } @Override public int nextIndex() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public Object previous() { throw new UnsupportedOperationException("Not yet implemented"); } @Override public int previousIndex() { throw new UnsupportedOperationException("Not yet implemented"); } } }
package com.mkdutton.labfour; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Binder; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; import com.mkdutton.labfour.fragments.MainFragment; import java.io.IOException; import java.util.ArrayList; import java.util.Random; /** * Created by Matt on 10/7/14. */ public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnSeekCompleteListener{ public static final String TAG = "MUSIC_SERVICE"; public static final int NOTIF_ID = 0x01222; NotificationManager mNotifMGR; public static final String NEXT_TRACK = "com.mkdutton.labfour.NEXT_TRACK"; public static final String PREV_TRACK = "com.mkdutton.labfour.PREV_TRACK"; //constants for music controls public static final int REW = 0; public static final int PLAY = 1; public static final int PAUSE = 2; public static final int STOP = 3; public static final int FF = 4; public static final int SHUFFLE_MOD = 987654; public static final int REPEAT_MOD = 54321; // initial setting when creating the service is shuffle public int mSelectedModifier = SHUFFLE_MOD; public MediaPlayer mPlayer; boolean mIsPrepared; boolean mPlayWhenPrepared; String[] mSongResource; String[] mTitle; String[] mArtist; int[] mArtwork; int mSong = -1; ArrayList<Integer> mLastSong; public class MusicBinder extends Binder { public MusicService getService(){ return MusicService.this; } } @Override public void onCreate() { super.onCreate(); mLastSong = new ArrayList<Integer>(); mSongResource = new String[]{ "android.resource://"+ getPackageName() + "/raw/duhast", "android.resource://"+ getPackageName() + "/raw/desire", "android.resource://"+ getPackageName() + "/raw/amishparadise", "android.resource://"+ getPackageName() + "/raw/carabella", "android.resource://"+ getPackageName() + "/raw/drunkatdennys", "android.resource://"+ getPackageName() + "/raw/fansong", "android.resource://"+ getPackageName() + "/raw/fusantaclause" }; mArtist = new String[]{ "Rammstein", "Techno Trance", "Weird Al Yankovic", "Techno Trance", "Monsters in the Morning", "Monsters in the Morning", "Monsters in the Morning", }; mTitle = new String[]{ "Du Hast", "Desire", "Amish Paradise", "Carabella", "Drunk At Denny's", "Fan Song", "F.U. Santa Clause" }; mArtwork = new int[]{ R.drawable.rammstein, R.drawable.techno, R.drawable.weirdal, R.drawable.techno, R.drawable.monsters, R.drawable.monsters, R.drawable.monsters, R.drawable.placeholder }; IntentFilter notificationFilter = new IntentFilter(); notificationFilter.addAction(NEXT_TRACK); notificationFilter.addAction(PREV_TRACK); registerReceiver(notificationReceiver, notificationFilter); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(mPlayer == null){ mPlayer = new MediaPlayer(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setOnPreparedListener(this); mPlayer.setOnCompletionListener(this); mPlayer.setOnSeekCompleteListener(this); try { mSong = pickNextSong(); mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong])); } catch (IOException e) { e.printStackTrace(); mPlayer.release(); mPlayer = null; } } if(mPlayer != null && !mIsPrepared) { mPlayer.prepareAsync(); mPlayWhenPrepared = true; } return START_STICKY; } private int pickNextSong() { return new Random().nextInt( mSongResource.length ); } @Override public void onDestroy() { super.onDestroy(); if(mPlayer != null) { mPlayer.release(); } unregisterReceiver(notificationReceiver); } @Override public IBinder onBind(Intent intent) { return new MusicBinder(); } public void musicControl(int _action){ switch (_action){ case REW: gotoPrevTrack(); break; case PLAY: Log.i(TAG, "PLAY MUSIC"); if(mPlayer != null && mIsPrepared) { showNotification(); mPlayer.start(); } break; case PAUSE: Log.i(TAG, "PAUSE MUSIC"); if (mPlayer.isPlaying()) { mPlayer.pause(); stopForeground(true); } break; case STOP: Log.i(TAG, "STOP MUSIC"); if (mPlayer != null && mPlayer.isPlaying()){ stopForeground(true); mPlayer.stop(); mIsPrepared = false; mPlayer.reset(); try { mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong])); } catch (IOException e) { e.printStackTrace(); } mPlayer.prepareAsync(); mPlayWhenPrepared = false; } break; case FF: Log.i(TAG, "FAST FORWARD MUSIC"); stopAndSetToSong(mSong, true); break; } } public void selectedModifier(int _modifier){ if(_modifier == SHUFFLE_MOD){ mSelectedModifier = SHUFFLE_MOD; Log.i(TAG, "shuffle Radio"); } else if(_modifier == REPEAT_MOD){ mSelectedModifier = REPEAT_MOD; Log.i(TAG, "repeat Radio"); } } @Override public void onPrepared(MediaPlayer mediaPlayer) { mIsPrepared = true; if ( mPlayWhenPrepared ) { showNotification(); mPlayer.start(); } // Broadcast to the receiver in the fragment to update the displayed details. Intent showDetailsBroadcast = new Intent(MainFragment.ACTION_UPDATE_DETAILS); showDetailsBroadcast.putExtra(MainFragment.EXTRA_TITLE_UPDATE,mTitle[mSong]); showDetailsBroadcast.putExtra(MainFragment.EXTRA_COVER_UPDATE, mArtwork[mSong]); showDetailsBroadcast.putExtra(MainFragment.EXTRA_ARTIST_UPDATE, mArtist[mSong]); sendBroadcast(showDetailsBroadcast); } private void showNotification(){ mNotifMGR = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE); // notification for the task bar NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.ic_music); builder.setContentTitle(mArtist[mSong]); builder.setContentText(mTitle[mSong]); builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), mArtwork[mSong])); builder.setAutoCancel(false); builder.setOngoing(true); NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle(); style.setBigContentTitle(mArtist[mSong]); style.setSummaryText(mTitle[mSong]); style.bigLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_music )); style.bigPicture(BitmapFactory.decodeResource(this.getResources(), mArtwork[mSong])); builder.setStyle(style); Intent skipIntent = new Intent(PREV_TRACK); PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, skipIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_rew, "Last Track", pIntent); skipIntent = new Intent(NEXT_TRACK); pIntent = PendingIntent.getBroadcast(this, 0, skipIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(android.R.drawable.ic_media_ff, "Next Track", pIntent); Intent clickIntent = new Intent(this, MainActivity.class); clickIntent.putExtra(MainFragment.EXTRA_TITLE_UPDATE,mTitle[mSong]); clickIntent.putExtra(MainFragment.EXTRA_COVER_UPDATE, mArtwork[mSong]); clickIntent.putExtra(MainFragment.EXTRA_ARTIST_UPDATE, mArtist[mSong]); clickIntent.putExtra(MainFragment.EXTRA_SONG_DURATION, mPlayer.getDuration()); PendingIntent pendClickIntent = PendingIntent.getActivity(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendClickIntent); Notification notification = builder.build(); startForeground(NOTIF_ID, notification); } @Override public void onCompletion(MediaPlayer mediaPlayer) { if (mPlayer != null) { stopAndSetToSong(mSong, true); } } public void stopAndSetToSong(int _song, boolean _playwhenpreped ){ if (mPlayer != null) { stopForeground(true); mPlayer.stop(); mIsPrepared = false; int next; if (mSelectedModifier == SHUFFLE_MOD) { next = pickNextSong(); } else { // if its not shuffle its repeat, so play again. next = _song; } //add the current song to the array of previous songs mLastSong.add(_song); // set mSong to the new random number mSong = next; try { mPlayer.reset(); mPlayer.setDataSource(this, Uri.parse(mSongResource[next])); } catch (IOException e) { e.printStackTrace(); } mPlayer.prepareAsync(); mPlayWhenPrepared = _playwhenpreped; } } public void userSeekTo(int _time){ if (mPlayer != null && mIsPrepared ){ mPlayer.pause(); mPlayer.seekTo( _time ); } } @Override public void onSeekComplete(MediaPlayer mediaPlayer) { if (mediaPlayer != null && mIsPrepared ){ mediaPlayer.start(); } } public void gotoPrevTrack(){ Log.i(TAG, "REWIND MUSIC"); if (mPlayer != null && !mLastSong.isEmpty() ){ mPlayer.stop(); mIsPrepared = false; // set the mSong to the last song added in the [] mSong = mLastSong.get( mLastSong.size()-1 ); // remove the last index from the [] mLastSong.remove( mLastSong.size()-1 ); try { // rest the player back to an idle state mPlayer.reset(); // reset the datasource to the mSong that was updated mPlayer.setDataSource(this, Uri.parse(mSongResource[mSong])); } catch (IOException e) { e.printStackTrace(); } mPlayer.prepareAsync(); mPlayWhenPrepared = true; } else { // if the player is null or the array is empty Toast.makeText(this, "No Previous Track Available", Toast.LENGTH_SHORT).show(); } } BroadcastReceiver notificationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(PREV_TRACK)){ Log.i(TAG, "PREV TRACK BROADCAST RECEIVED"); gotoPrevTrack(); } else if (intent.getAction().equals(NEXT_TRACK)){ Log.i(TAG, "NEXT TRACK BROADCAST RECEIVED"); stopAndSetToSong(mSong, true); } } }; }
/** * Graph search algorithms. */ package algopro.algo;
package com.digit88.interview; /* * Given an array find the pairs with the given target */ public class TwoSum { }
package com.xinhua.api.osb; import com.apsaras.hsf.common.Constants; import com.apsaras.hsf.common.URL; import com.apsaras.hsf.rpc.*; import com.apsaras.hsf.rpc.protocol.AbstractInvoker; import com.apsaras.hsf.rpc.protocol.AbstractProtocol; import org.apache.cxf.bus.extension.ExtensionManagerBus; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; import org.apache.cxf.frontend.ClientProxyFactoryBean; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.transport.http.HTTPConduit; import org.apache.cxf.transport.http.HttpDestinationFactory; import org.apache.cxf.transport.servlet.ServletDestinationFactory; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * Created by shibaoning on 2015/9/9. * 新华osb */ public class XinHuaOsbServiceProtocol extends AbstractProtocol { public static final int DEFAULT_PORT = 80; private final ExtensionManagerBus bus = new ExtensionManagerBus(); private final List<Class<?>> rpcExceptions = new CopyOnWriteArrayList<Class<?>>();; private ProxyFactory proxyFactory; public void setProxyFactory(ProxyFactory proxyFactory) { this.proxyFactory = proxyFactory; } public ProxyFactory getProxyFactory() { return proxyFactory; } public XinHuaOsbServiceProtocol() { this.rpcExceptions.add(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); } public int getDefaultPort() { return DEFAULT_PORT; } public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException { throw new UnsupportedOperationException("Unsupported export Osb service. url: " + invoker.getUrl()); } @SuppressWarnings("unchecked") protected <T> T doRefer(final Class<T> serviceType, final URL url) throws RpcException { ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean(); proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString()); proxyFactoryBean.setServiceClass(serviceType); proxyFactoryBean.setBus(bus); T ref = (T) proxyFactoryBean.create(); Client proxy = ClientProxy.getClient(ref); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); HTTPClientPolicy policy = new HTTPClientPolicy(); policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); conduit.setClient(policy); return ref; } protected int getErrorCode(Throwable e) { if (e instanceof Fault) { e = e.getCause(); } if (e instanceof SocketTimeoutException) { return RpcException.TIMEOUT_EXCEPTION; } else if (e instanceof IOException) { return RpcException.NETWORK_EXCEPTION; } return RpcException.UNKNOWN_EXCEPTION; } public <T> Invoker<T> refer(final Class<T> type, final URL url) throws RpcException { final Invoker<T> tagert = proxyFactory.getInvoker(doRefer(type, url), type, url); Invoker<T> invoker = new AbstractInvoker<T>(type, url) { @Override protected Result doInvoke(Invocation invocation) throws Throwable { try { Result result = tagert.invoke(invocation); // String serviceName =url.getParameter(invocation.getMethodName()) ; logger.debug("init url222:="+tagert.toString()); Throwable e = result.getException(); if (e != null) { for (Class<?> rpcException : rpcExceptions) { if (rpcException.isAssignableFrom(e.getClass())) { throw getRpcException(type, url, invocation, e); } } } return result; } catch (RpcException e) { if (e.getCode() == RpcException.UNKNOWN_EXCEPTION) { e.setCode(getErrorCode(e.getCause())); } throw e; } catch (Throwable e) { throw getRpcException(type, url, invocation, e); } } }; invokers.add(invoker); return invoker; } protected RpcException getRpcException(Class<?> type, URL url, Invocation invocation, Throwable e) { RpcException re = new RpcException("Failed to invoke remote service: " + type + ", method: " + invocation.getMethodName() + ", cause: " + e.getMessage(), e); re.setCode(getErrorCode(e)); return re; } }
/** * */ package com.jspmyadmin.app.database.trigger.controllers; import java.sql.SQLException; import com.jspmyadmin.app.common.logic.DataLogic; import com.jspmyadmin.app.database.trigger.beans.TriggerBean; import com.jspmyadmin.app.database.trigger.logic.TriggerLogic; import com.jspmyadmin.framework.constants.AppConstants; import com.jspmyadmin.framework.constants.Constants; import com.jspmyadmin.framework.web.annotations.Detect; import com.jspmyadmin.framework.web.annotations.HandlePost; import com.jspmyadmin.framework.web.annotations.Model; import com.jspmyadmin.framework.web.annotations.ValidateToken; import com.jspmyadmin.framework.web.annotations.WebController; import com.jspmyadmin.framework.web.utils.Messages; import com.jspmyadmin.framework.web.utils.RedirectParams; import com.jspmyadmin.framework.web.utils.RequestLevel; import com.jspmyadmin.framework.web.utils.View; import com.jspmyadmin.framework.web.utils.ViewType; /** * @author Yugandhar Gangu * @created_at 2016/03/30 * */ @WebController(authentication = true, path = "/database_trigger_create.html", requestLevel = RequestLevel.DATABASE) public class CreateTriggerController { @Detect private RedirectParams redirectParams; @Detect private Messages messages; @Detect private View view; @Model private TriggerBean bean; @HandlePost @ValidateToken private void createTrigger() { try { TriggerLogic triggerLogic = new TriggerLogic(); if (triggerLogic.isExisted(bean.getTrigger_name(), bean.getRequest_db())) { redirectParams.put(Constants.ERR, messages.getMessage(AppConstants.MSG_TRIGGER_ALREADY_EXISTED)); view.setType(ViewType.REDIRECT); view.setPath(AppConstants.PATH_DATABASE_TRIGGERS); return; } bean.setOther_trigger_name_list(triggerLogic.getTriggerList(bean.getRequest_db())); bean.setDatabase_name(bean.getRequest_db()); DataLogic dataLogic = new DataLogic(); bean.setDatabase_name_list(dataLogic.getDatabaseList()); } catch (SQLException e) { redirectParams.put(Constants.ERR, e.getMessage()); view.setType(ViewType.REDIRECT); view.setPath(AppConstants.PATH_DATABASE_TRIGGERS); return; } view.setType(ViewType.FORWARD); view.setPath(AppConstants.JSP_DATABASE_TRIGGER_CREATETRIGGER); } }
package org.cryptable.asn1.runtime.ber; import org.cryptable.asn1.runtime.ASN1Real; import org.cryptable.asn1.runtime.exception.ASN1Exception; import java.math.BigInteger; import java.text.NumberFormat; /** * The BER implementation of ASN1 Real values * Default will be binary encoding * * Created by david on 23/06/15. */ public class BERReal implements ASN1Real { private Encoding encoding = Encoding.ISO6093; private Double berDouble = 0.0; private String iso6093 = null; private ISO6093 iso6093Form = ISO6093.NR1; private Base base = Base.BASE_10; private SpecialRealValues specialRealValue = null; public Double getASN1Real() { return berDouble; } public void setASN1Real(Double value) throws ASN1Exception { setASN1Real(berDouble, null); } public void setASN1Real(Double berDouble, NumberFormat numberFormat) throws ASN1Exception { if (berDouble.isNaN()) { this.encoding = Encoding.SpecialRealValue; this.specialRealValue = SpecialRealValues.NOT_A_NUMBER; } else if (berDouble.isInfinite()) { this.encoding = Encoding.SpecialRealValue; if (berDouble > 0) { this.specialRealValue = SpecialRealValues.PLUS_INFINITY; } else { this.specialRealValue = SpecialRealValues.MINUS_INFINITY; } } else { if (numberFormat == null) { setASN1RealAsString(berDouble.toString()); } else { setASN1RealAsString(numberFormat.format(berDouble)); } } } public Encoding getEncoding() { return encoding; } public void setASN1RealAsString(String berValue) throws ASN1Exception { if ("NaN".equals(berValue)) { this.encoding = Encoding.SpecialRealValue; this.berDouble = Double.NaN; this.base = Base.BASE_10; this.specialRealValue = SpecialRealValues.NOT_A_NUMBER; } else if ("Infinity".equals(berValue)) { this.encoding = Encoding.SpecialRealValue; this.berDouble = Double.POSITIVE_INFINITY; this.base = Base.BASE_10; this.specialRealValue = SpecialRealValues.PLUS_INFINITY; } else if ("-Infinity".equals(berValue)) { this.encoding = Encoding.SpecialRealValue; this.berDouble = Double.NEGATIVE_INFINITY; this.base = Base.BASE_10; this.specialRealValue = SpecialRealValues.MINUS_INFINITY; } else { this.encoding = Encoding.ISO6093; if (berValue.matches("^ *(\\+|-)?\\d\\d*$")) { this.iso6093Form = ISO6093.NR1; } else if (berValue.matches("^ *(\\+|-)?((\\d\\d*\\.\\d*)|(\\d*\\.\\d\\d*))$")) { this.iso6093Form = ISO6093.NR2; } else if (berValue.matches("^ *(\\+|-)?((\\d*\\.\\d\\d*)|(\\d*\\.\\d\\d*))(E|e)(\\+|-)?\\d\\d*")) { this.iso6093Form = ISO6093.NR3; } else { throw new ASN1Exception("Illegal ISO6093 format [" + berValue + "]"); } this.berDouble = Double.valueOf(berValue); this.base = Base.BASE_10; this.iso6093 = berValue; } } public void setSpecialRealValue(SpecialRealValues specialRealValue) { this.encoding = Encoding.SpecialRealValue; this.specialRealValue = specialRealValue; this.base = Base.BASE_10; if (specialRealValue == SpecialRealValues.PLUS_INFINITY) { this.berDouble = Double.POSITIVE_INFINITY; } else if (specialRealValue == SpecialRealValues.MINUS_INFINITY) { this.berDouble = Double.NEGATIVE_INFINITY; } else if (specialRealValue == SpecialRealValues.NOT_A_NUMBER) { this.berDouble = Double.NaN; } else { this.berDouble = null; } } public SpecialRealValues getASN1SpecialRealValue() { return this.specialRealValue; } public boolean isIndefiniteLength() { return false; } public int getLength() throws ASN1Exception { int result; if (this.encoding == Encoding.BINARY) { // TODO Support Base 2, 8, 16 binary values throw new ASN1Exception("Base 2, 8, 16 is not supported"); } else if (this.encoding == Encoding.ISO6093) { result = 1 // TAG + Utils.calculateLengthByteLength(this.iso6093.length()) // nbr Length bytes + 1 // Tag for the BERReal content + this.iso6093.length(); // length of the content } else { result = 1 // TAG + 1 // Length + 1; // Content length } return result; } public byte[] encode() throws ASN1Exception { byte[] byteReal = new byte[getLength()]; if (encoding == Encoding.BINARY) { // TODO Support Base 2, 8, 16 binary values throw new ASN1Exception("Base 2, 8, 16 is not supported"); } else if (encoding == Encoding.ISO6093) { byte[] byteLength = Utils.getLengthInBytes(iso6093.toCharArray().length); byte[] byteValue = iso6093.getBytes(); // TAG byteReal[0] = 0x09; // Length System.arraycopy(byteLength, 0, byteReal, 1, byteLength.length); // Value byteReal[1 + byteLength.length] = iso6093Form.getBitPattern(); System.arraycopy(byteValue, 0, byteReal, 1 + byteLength.length + 1, byteValue.length); } else { // TAG byteReal[0] = 0x09; byteReal[1] = 0x01; byteReal[2] = specialRealValue.getBitPattern(); } return byteReal; } private double convertDouble(byte[] value, int offset, int length) { byte doubleBytes[] = new byte[length - 1]; System.arraycopy(value, offset, doubleBytes, 0, (length - 1)); return Double.parseDouble(new String(doubleBytes)); } public void decode(byte[] value) throws ASN1Exception { int offset = 0; if (value.length < 3) throw new ASN1Exception("Wrong BERReal minimal length [" + value.length + "]"); // TAG if (value[0] != 0x09) throw new ASN1Exception("Wrong BERReal tag value [" + value[0] + "]"); offset += 1; // Length int length; if ((value[1] & 0x80) == 0x80) { int lengthLength = value[1] & 0x7F; length = Utils.getLengthOfBytes(value, lengthLength); offset += lengthLength; } else { length = value[1]; offset += 1; } // Test on Base 2, 8, 16 if ((length >= 1) && ((value[offset] & 0x80) == 0x80)) { throw new ASN1Exception("Base 2, 8, 16 not supported."); } // Test Special value & set SpecialValue else if ((length == 1) && ((value[offset] & 0xC0) == 0x40)) { switch (value[offset]) { // 0x40 -> PLUS-INFINITY case 0x40 : this.encoding = Encoding.SpecialRealValue; this.specialRealValue = SpecialRealValues.PLUS_INFINITY; this.berDouble = Double.POSITIVE_INFINITY; break; // 0x41 -> MINUS-INFINITY case 0x41 : this.encoding = Encoding.SpecialRealValue; this.specialRealValue = SpecialRealValues.MINUS_INFINITY; this.berDouble = Double.NEGATIVE_INFINITY; break; // 0x42 -> NOT-A-NUMBER case 0x42 : this.encoding = Encoding.SpecialRealValue; this.specialRealValue = SpecialRealValues.NOT_A_NUMBER; this.berDouble = Double.NaN; break; // 0x43 -> MINUS-ZERO case 0x43 : this.encoding = Encoding.SpecialRealValue; this.specialRealValue = SpecialRealValues.MINUS_ZERO; break; default: throw new ASN1Exception("Unknown SpecialRealValue [" + value[2] + "]"); } } // ISO 6093 else { switch (value[offset]) { case 0x01: this.iso6093Form = ISO6093.NR1; break; case 0x02: this.iso6093Form = ISO6093.NR2; break; case 0x03: this.iso6093Form = ISO6093.NR3; break; default: throw new ASN1Exception("Unknown type of ISO 6093 [" + value[2] + "]"); } offset += 1; this.encoding = Encoding.ISO6093; this.berDouble = convertDouble(value, offset, length); } } }
package br.com.herculano.urlshortener.api.service; import java.util.Optional; import javax.persistence.EntityNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.herculano.urlshortener.api.configuration.system_message.CommonMessage; import br.com.herculano.urlshortener.api.constant.ConfiguracaoEnum; import br.com.herculano.urlshortener.api.entity.Configuracao; import br.com.herculano.urlshortener.api.respository.jpa_respository.ConfiguracaoRepository; @Service public class ConfiguracaoService extends ServiceTemplate<Configuracao, ConfiguracaoRepository, CommonMessage>{ @Autowired public ConfiguracaoService(ConfiguracaoRepository repository, CommonMessage message) { super(repository, message); } public String getValorPorCodigo(ConfiguracaoEnum configuracaoEnum) { Optional<Configuracao> optional = getRepository().findById(configuracaoEnum.getCodigo()); if (!optional.isPresent()) { Object[] args = {configuracaoEnum.getCodigo()}; throw new EntityNotFoundException(CommonMessage.getCodigo(message.getNotFound(), args)); } return optional.get().getValor(); } }
package video_storm; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import video_storm.input.KeyInput; import video_storm.input.MouseInput; public class MainTest { public static void main( String[] args ) throws LWJGLException { new Window(640, 480); KeyInput k = new KeyInput(); MouseInput m = new MouseInput(); System.out.println( "*** " + Keyboard.KEY_SPACE ); while(true) { k.get(); m.get(); Display.update(); } } }
package com.example.agustinuswidiantoro.icp_mobile.activity; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.agustinuswidiantoro.icp_mobile.R; import com.example.agustinuswidiantoro.icp_mobile.util.HttpHandler; import com.example.agustinuswidiantoro.icp_mobile.util.SessionUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; public class UserProfileActivity extends AppCompatActivity { TextView text_fullname, text_username; Button btn_logout; SessionUtils session; private String TAG = UserProfileActivity.class.getSimpleName(); private ProgressDialog pDialog; // URL to get contacts JSON String url = "http://test.incenplus.com:5000/users/me?token="; HashMap<String, String> user_token; String token; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_userprofile); btn_logout = (Button) findViewById(R.id.btn_logout); // Session class instance session = new SessionUtils(getApplicationContext()); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); session.checkLogin(); // get user data from session user_token = session.getUserDetails(); token = user_token.get(SessionUtils.KEY_TOKEN); Log.e(TAG, "Session token: " + token); new GetUserProfile().execute(); btn_logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Logout().execute(); } }); } private class Logout extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { // get user data from session // Defined URL where to send data HttpHandler sh = new HttpHandler(); // get user data from session HashMap<String, String> user = session.getUserDetails(); String token = user.get(SessionUtils.KEY_TOKEN); // Making a request to url and getting response sh.makeServiceCall("http://test.incenplus.com:5000/users/logout?token=" + token); session.logoutUser(); // get user data from session user_token = session.getUserDetails(); String name = user_token.get(SessionUtils.KEY_TOKEN); Log.e(TAG, "Session clear: " + name); startActivity(new Intent(getApplicationContext(), LoginActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); return null; } } private class GetUserProfile extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(UserProfileActivity.this); pDialog.setMessage("Please wait ..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // get user data from session HashMap<String, String> user = session.getUserDetails(); String token = user.get(SessionUtils.KEY_TOKEN); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url + token); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); JSONObject data = jsonObj.getJSONObject("data"); String username = data.getString("username"); String fullname = data.getString("fullname"); Log.e(TAG, "User detail: " + username + " dan " + fullname); text_fullname = (TextView) findViewById(R.id.fullname); text_username = (TextView) findViewById(R.id.username); text_fullname.setText(fullname); text_username.setText(username); } catch (final JSONException e) { e.printStackTrace(); Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); } } @Override public void onBackPressed() { // code here to show dialog startActivity(new Intent(getApplicationContext(), BookActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); super.onBackPressed(); // optional depending on your needs } }
package com.swapping.springcloud.ms.hystrix.turbine; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.cloud.netflix.turbine.EnableTurbine; import org.springframework.cloud.openfeign.EnableFeignClients; /** * * IP:turbine服务所在服务器IP localhost * port:turbine服务所配置的服务端口 10000 * 监控项目访问: http://IP:port/turbine.stream * 展示信息: * ping: * {.....} * * * * 图形化监控页面:http://IP:port/hystrix * * 图形化监控页面使用说明: * 1.在进入豪猪主页后,在输入框输入http://localhost:10000/turbine.stream,点击Monitor Stream按钮 * 2.展示所有配置了Hystrix Dashboard仪表盘展示的 各个服务之间的feign调用情况 */ @EnableTurbine//开启turbine @EnableHystrixDashboard//开启仪表盘 @EnableDiscoveryClient @SpringBootApplication public class SpringcloudMsHystrixTurbineApplication { public static void main(String[] args) { SpringApplication.run(SpringcloudMsHystrixTurbineApplication.class, args); } }
package com.hackucla.chatbot; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ChatBot extends AppCompatActivity { /** * These are parameters for the API call. * API_USER and API_KEY are found from the cleverbot.io user dashboard * API_BASEURL should not be changed */ private static final String API_BASEURL = "https://cleverbot.io/1.0/"; private static final String API_USER; private static final String API_KEY; /** * To use retrofit, we defined an interface ChatBotHTTP, which is turned * into a class by retrofit. chatBotService is how we send/receive data * to/from the chatbot API. * * chatBot is an instance of ChatBotInstance. This is the information we get * back from the API call when we create a chatbot. The important field is * chatBot.nick, which is a like a unique identifier for our chatbot. */ private ChatBotHTTP chatBotService; private ChatBotInstance chatBot = null; /** * This represent the UI elements. * They are instantiated later. * * submitButton: the button * botChatText: the text entered by the user * botResponseText: the text received from the bot API */ private Button submitButton; private EditText botChatText; private TextView botResponseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat_bot); // TODO: Initialize the chatbot // TODO: Load references to the UI elements // TODO: implement onClickListener for submit button } /** * This function initializes the chat bot. It does several important things: * 1. Use Retrofit to turn the ChatBotHTTP interface into an actual service * that we can use to interact with the API * 2. Registers the API_BASEURL (the path to prepend in all API calls) * 3. Loads our JSON interpreter * 4. Sends an API request to /create (via the created service) to get a unique * identifier for a new chat bot and set the response object globally */ private void initializeChatbot() { // TODO: create a retrofit instance and the chatBotService // TODO: Create the API call for POST /create // TODO: Asynchronously handle the response/failure } /** * This method actually sends a message to the chat bot via the established service * and updates the UI with the chat bot's response. * @param chatMessage The message to send the chat bot */ private void sendChat(String chatMessage) { // TODO: add some bounds checking (chatBot != null, chatMessage.length() > 0) // TODO: Set the response text to "Thinking..." while we wait for the API call to return // TODO: Create the API call for POST /ask // TODO: Asynchronously handle the response } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.itcs.helpdesk.util; import com.itcs.helpdesk.jsfcontrollers.util.ApplicationBean; import com.itcs.helpdesk.jsfcontrollers.util.UserSessionBean; import com.itcs.helpdesk.persistence.entities.Accion; import com.itcs.helpdesk.persistence.entities.Area; import com.itcs.helpdesk.persistence.entities.AuditLog; import com.itcs.helpdesk.persistence.entities.Caso; import com.itcs.helpdesk.persistence.entities.Categoria; import com.itcs.helpdesk.persistence.entities.Condicion; import com.itcs.helpdesk.persistence.entities.FieldType; import com.itcs.helpdesk.persistence.entities.Grupo; import com.itcs.helpdesk.persistence.entities.Prioridad; import com.itcs.helpdesk.persistence.entities.ReglaTrigger; import com.itcs.helpdesk.persistence.entities.TipoComparacion; import com.itcs.helpdesk.persistence.entities.Usuario; import com.itcs.helpdesk.persistence.entityenums.EnumFieldType; import com.itcs.helpdesk.persistence.entityenums.EnumTipoAccion; import com.itcs.helpdesk.persistence.entityenums.EnumTipoComparacion; import com.itcs.helpdesk.persistence.jpa.custom.CasoJPACustomController; import com.itcs.helpdesk.persistence.jpa.service.JPAServiceFacade; import com.itcs.helpdesk.persistence.utils.CasoChangeListener; import com.itcs.helpdesk.persistence.utils.ComparableField; import com.itcs.helpdesk.rules.Action; import com.itcs.helpdesk.rules.actionsimpl.ScheduleJobAction; import com.thoughtworks.xstream.XStream; import java.beans.Expression; import java.lang.reflect.Constructor; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.bean.ManagedProperty; import javax.resource.NotSupportedException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.mail.EmailException; /** * * @author jorge * @author jonathan */ public class RulesEngine implements CasoChangeListener { @ManagedProperty(value = "#{UserSessionBean}") private UserSessionBean userSessionBean; private final JPAServiceFacade jpaController; // private final ManagerCasos managerCasos; // private EntityManagerFactory emf = null; private ApplicationBean applicationBean; public RulesEngine(JPAServiceFacade jpaController) { this.jpaController = jpaController; // this.managerCasos = managerCasos; // this.emf = emf; } private JPAServiceFacade getJpaController() { return jpaController; } @Override public void notifyAllWatchersOnline(Caso caso, String whoMadeTheChange, String message) { String[] userToBeNotified = null;//no-one String idCaso = caso.getIdCaso().toString(); String originalTema = caso.getTema(); String agentUserId = null; String customerUserId = null; //next, implement a list of watchers of the case. if (caso.getOwner() != null && caso.getOwner().getIdUsuario() != null) { agentUserId = caso.getOwner().getIdUsuario(); } if (caso.getEmailCliente() != null && caso.getEmailCliente().getEmailCliente() != null) { customerUserId = caso.getEmailCliente().getEmailCliente(); } if (whoMadeTheChange == null) { //notify all, customer and agent userToBeNotified = new String[]{agentUserId, customerUserId}; } else { if (whoMadeTheChange.equalsIgnoreCase(agentUserId)) { //agent made the change userToBeNotified = new String[]{customerUserId}; } else if (whoMadeTheChange.equalsIgnoreCase(customerUserId)) { //customer made the change userToBeNotified = new String[]{agentUserId}; } } if (applicationBean != null) { if (userToBeNotified != null) { for (String user : userToBeNotified) { if (!StringUtils.isEmpty(user)) { applicationBean.sendFacesMessageNotification(user, message); } } } } } @Override public void casoCreated(Caso caso) { //TODO Permitir que el caso no tenga area! una regla podria ser que si el el area es null asignar DEFAULT. List<ReglaTrigger> listaSup = Collections.EMPTY_LIST; //Area en la que viene el caso si es que viene. Area areaDelCaso = caso.getIdArea(); // a = EnumAreas.DEFAULT_AREA.getArea(); if (areaDelCaso != null) { try { listaSup = (List<ReglaTrigger>) getJpaController().findReglasToExecute(areaDelCaso.getIdArea(), "CREATE"); } catch (Exception ex) { Logger.getLogger(RulesEngine.class.getName()).log(Level.SEVERE, "error on finding rules! by Vista", ex); } } else { //Si el caso no trae area aplicarle todas las reglas de todas las areas! listaSup = (List<ReglaTrigger>) getJpaController().findAll(ReglaTrigger.class); } List<ReglaTrigger> lista; Log.createLogger(this.getClass().getName()).logInfo("*** Reglas Found for new caso: " + caso + " -> " + listaSup); do { lista = new LinkedList<ReglaTrigger>(listaSup); for (ReglaTrigger reglaTrigger : lista) { if (reglaTrigger.getReglaActiva()) { // Log.createLogger(this.getClass().getName()).logInfo("*** Verificando regla -> " + reglaTrigger); boolean aplica = false; for (Condicion condicion : reglaTrigger.getCondicionList()) { try { aplica = verificarCondicion(condicion, caso, new ArrayList<AuditLog>());//no changes =) if (!aplica) { break; } } catch (Exception e) { Log.createLogger(this.getClass().getName()).log(Level.SEVERE, "error on casoCreated Listener", e); break; } } if (aplica) { Log.createLogger(this.getClass().getName()).logInfo("regla " + reglaTrigger.getIdTrigger() + " APLICA_AL_CASO " + caso.toString()); listaSup.remove(reglaTrigger); for (Accion accion : reglaTrigger.getAccionList()) { ejecutarAccion(accion, caso); } } } } } while (lista.size() > listaSup.size()); if (ApplicationConfig.getInstance(getJpaController().getSchema()).isRealTimeNotifToAgentsEnabled()) { caso = getJpaController().getReference(Caso.class, caso.getIdCaso()); //Online notification if (caso.getOwner() != null) { String user = caso.getOwner().getIdUsuario(); notifyAllWatchersOnline(caso, user, "Un nuevo caso ha sido asignado a ud. Tipo:" + (caso.getTipoCaso() != null ? caso.getTipoCaso().getNombre() : "caso") + " #" + caso.getIdCaso() + ": " + caso.getTema()); } } if (ApplicationConfig.getInstance(getJpaController().getSchema()).isSendGroupNotifOnNewCaseEnabled()) { //Notify all agents in the groups if (caso.getIdProducto() != null) { for (Grupo grupo : caso.getIdProducto().getGrupoList()) { MailNotifier.notifyGroupCasoReceived(grupo, caso, getJpaController().getSchema()); } } }//TODO config what to do when case has no product when created } @Override public void casoChanged(Caso caso, List<AuditLog> changeList) { //TODO Permitir que el caso no tenga area! una regla podria ser que si el el area es null asignar DEFAULT. List<ReglaTrigger> listaSup = Collections.EMPTY_LIST; //Area en la que viene el caso si es que viene. Area areaDelCaso = caso.getIdArea(); // a = EnumAreas.DEFAULT_AREA.getArea(); if (areaDelCaso != null) { try { listaSup = (List<ReglaTrigger>) getJpaController().findReglasToExecute(areaDelCaso.getIdArea(), "UPDATE"); } catch (Exception ex) { Logger.getLogger(RulesEngine.class.getName()).log(Level.SEVERE, "error on finding rules! by Vista", ex); } } else { //Si el caso no trae area aplicarle todas las reglas de todas las areas! listaSup = (List<ReglaTrigger>) getJpaController().findAll(ReglaTrigger.class); } List<ReglaTrigger> lista; Log.createLogger(this.getClass().getName()).logInfo("*** Reglas Found for caso updated: " + caso + " -> " + listaSup); do { lista = new LinkedList<ReglaTrigger>(listaSup); for (ReglaTrigger reglaTrigger : lista) { if (reglaTrigger.getReglaActiva()) { boolean aplica = true; for (Condicion condicion : reglaTrigger.getCondicionList()) { // Log.createLogger(this.getClass().getName()).logInfo("***********" + condicion.toString()); try { aplica = verificarCondicion(condicion, caso, changeList); if (!aplica) { // Log.createLogger(this.getClass().getName()).logInfo("regla " + reglaTrigger.getIdTrigger() + " no aplica al caso " + caso.getIdCaso()); // Log.createLogger(this.getClass().getName()).logInfo("condicion fallida " + condicion.getIdCampo().getIdCampo() + " " + condicion.getIdComparador().getSimbolo() + " " + condicion.getValor()); break; } } catch (Exception ex) { Logger.getLogger(RulesEngine.class.getName()).log(Level.SEVERE, "error on casoChanged verificarCondicion", ex); break; } } if (aplica) { Log.createLogger(this.getClass().getName()).logInfo("regla " + reglaTrigger.getIdTrigger() + " APLICA_AL_CASO " + caso.toString()); listaSup.remove(reglaTrigger); for (Accion accion : reglaTrigger.getAccionList()) { ejecutarAccion(accion, caso); } } } } } while (lista.size() > listaSup.size()); if (ApplicationConfig.getInstance(getJpaController().getSchema()).isRealTimeNotifToAgentsEnabled() || ApplicationConfig.getInstance(getJpaController().getSchema()).isRealTimeNotifToCustomerEnabled()) { //Online notification if (changeList != null && !changeList.isEmpty()) { String user = changeList.get(0).getIdUser(); notifyAllWatchersOnline(caso, user, "Uno de sus casos ha sido modificado, " + (caso.getTipoCaso() != null ? caso.getTipoCaso().getNombre() : "caso") + " #[" + caso.getIdCaso() + "]: " + caso.getTema()); } } } public void applyRuleOnThisCasos(ReglaTrigger reglaTrigger, List<Caso> selectedCasos) { for (Caso caso : selectedCasos) { if (reglaTrigger.getReglaActiva()) { boolean aplica = false; for (Condicion condicion : reglaTrigger.getCondicionList()) { try { aplica = verificarCondicion(condicion, caso, new ArrayList<AuditLog>());//no changes =) if (!aplica) { break; } } catch (Exception e) { Log.createLogger(this.getClass().getName()).log(Level.SEVERE, "error applyRuleOnThisCasos", e); break; } } if (aplica) { Log.createLogger(this.getClass().getName()).logInfo("regla " + reglaTrigger.getIdTrigger() + " APLICA_AL_CASO " + caso.toString()); for (Accion accion : reglaTrigger.getAccionList()) { ejecutarAccion(accion, caso); } } } } } /** * TODO implement changeList * * @param filtro * @param caso * @param changeList * @return * @throws NotSupportedException * @throws ClassNotFoundException * @throws Exception */ private boolean verificarCondicion(Condicion filtro, Caso caso, List<AuditLog> changeList) throws NotSupportedException, ClassNotFoundException, Exception { TipoComparacion operador = filtro.getIdComparador(); Map<String, ComparableField> annotatedFields = getJpaController().getAnnotatedComparableFieldsMap(Caso.class); ComparableField comparableField = annotatedFields.get(filtro.getIdCampo()); FieldType fieldType = comparableField.getFieldTypeId(); String valorAttributo = filtro.getValor(); if (operador == null || comparableField == null || valorAttributo == null || fieldType == null) { throw new NotSupportedException("La condicion no cumple con los requisitos minimos!"); } Expression expresion; String methodName = "get" + WordUtils.capitalize(comparableField.getIdCampo()); expresion = new Expression(caso, methodName, new Object[0]); expresion.execute(); final Object value = expresion.getValue(); if (ApplicationConfig.getInstance(getJpaController().getSchema()).isAppDebugEnabled()) { System.out.println("caso." + methodName + " = " + value); } if (fieldType.equals(EnumFieldType.TEXT.getFieldType()) || fieldType.equals(EnumFieldType.TEXTAREA.getFieldType())) { //El valor es de tipo String, usarlo tal como esta if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { if (value != null) { return valorAttributo.equals((String) value); } } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { if (value != null) { return !valorAttributo.equals((String) value); } } else if (operador.equals(EnumTipoComparacion.CO.getTipoComparacion())) { if (value != null) { final String patternToSearch = "\\b" + valorAttributo + "\\b"; Pattern p = Pattern.compile(patternToSearch, Pattern.CASE_INSENSITIVE); //Match the given string with the pattern Matcher m = p.matcher((String) value); if (ApplicationConfig.getInstance(getJpaController().getSchema()).isAppDebugEnabled()) { System.out.println("patternToSearch:" + patternToSearch); } return m.find(); // return ((String) expresion.getValue()).toLowerCase().contains(valorAttributo.toLowerCase());//removes case sensitive issue } } else if (operador.equals(EnumTipoComparacion.CT.getTipoComparacion())) {//Changed TO =) if (value != null) { for (AuditLog auditLog : changeList) { if (comparableField.getIdCampo().equalsIgnoreCase(auditLog.getCampo())) { return valorAttributo.equals((String) value); } } } } else { throw new NotSupportedException("Comparador " + operador.getIdComparador() + " is not supported!!"); } } else if (fieldType.equals(EnumFieldType.CALENDAR.getFieldType())) { //El valor es de tipo Fecha, usar el String parseado a una fecha SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); try { Date fecha1 = sdf.parse(valorAttributo); Date beanDate = ((Date) value); if (fecha1 != null && beanDate != null) { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { return (fecha1.compareTo(beanDate) == 0); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { return (fecha1.compareTo(beanDate) != 0); } else if (operador.equals(EnumTipoComparacion.LE.getTipoComparacion())) { return (beanDate.getTime() <= fecha1.getTime()); //lessThanOrEqualTo } else if (operador.equals(EnumTipoComparacion.GE.getTipoComparacion())) { return (beanDate.getTime() >= fecha1.getTime()); } else if (operador.equals(EnumTipoComparacion.LT.getTipoComparacion())) { return (beanDate.getTime() < fecha1.getTime()); } else if (operador.equals(EnumTipoComparacion.GT.getTipoComparacion())) { return (beanDate.getTime() > fecha1.getTime()); } else if (operador.equals(EnumTipoComparacion.BW.getTipoComparacion())) { Date fecha2 = sdf.parse(filtro.getValor2()); return ((beanDate.getTime() >= fecha1.getTime()) && (beanDate.getTime() <= fecha2.getTime())); } else { throw new NotSupportedException("Comparador " + operador.getIdComparador() + " is not supported!!"); } } } catch (ParseException ex) { //ignore and do not add this filter to the query Logger.getLogger(CasoJPACustomController.class.getName()).log(Level.SEVERE, null, ex); } } else if (fieldType.equals(EnumFieldType.SELECTONE_ENTITY.getFieldType())) { // EntityManager em = null; try { // em = emf.createEntityManager(); //El valor es el id de un entity, que tipo de Entity?= comparableField.tipo Class class_ = comparableField.getTipo();//Class.forName(comparableField.getTipo()); Object oneEntity = value; //One or more values?? if (operador.equals(EnumTipoComparacion.SC.getTipoComparacion())) { //One or more values, as list select many. List<String> valores = filtro.getValoresList(); if (oneEntity != null) { return valores.contains(getJpaController().getIdentifier(oneEntity).toString()); } else { return false; } } else { if (CasoJPACustomController.PLACE_HOLDER_ANY.equalsIgnoreCase(valorAttributo)) { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { return (oneEntity != null); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { return (oneEntity == null); } else if (operador.equals(EnumTipoComparacion.CT.getTipoComparacion())) {//Changed TO =) if (value != null) { for (AuditLog auditLog : changeList) { if (comparableField.getIdCampo().equalsIgnoreCase(auditLog.getCampo())) { return (oneEntity != null); } } } } else { throw new NotSupportedException("Tipo comparacion " + operador.getIdComparador() + " is not supported here!!"); } } else if (CasoJPACustomController.PLACE_HOLDER_NULL.equalsIgnoreCase(valorAttributo)) { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { return (oneEntity == null); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { return (oneEntity != null); } else if (operador.equals(EnumTipoComparacion.CT.getTipoComparacion())) {//Changed TO =) if (value != null) { for (AuditLog auditLog : changeList) { if (comparableField.getIdCampo().equalsIgnoreCase(auditLog.getCampo())) { return (oneEntity == null); } } } } else { throw new NotSupportedException("Tipo comparacion " + operador.getIdComparador() + " is not supported here!!"); } } else if (CasoJPACustomController.PLACE_HOLDER_CURRENT_USER.equalsIgnoreCase(valorAttributo)) { if (userSessionBean != null && userSessionBean.getCurrent() != null) { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { // return (oneEntity == null); return (oneEntity != null ? userSessionBean.getCurrent().equals(oneEntity) : false); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { // return (oneEntity != null); return (oneEntity != null ? !userSessionBean.getCurrent().equals(oneEntity) : false); } else if (operador.equals(EnumTipoComparacion.CT.getTipoComparacion())) {//Changed TO =) if (value != null) { for (AuditLog auditLog : changeList) { if (comparableField.getIdCampo().equalsIgnoreCase(auditLog.getCampo())) { return (oneEntity != null ? userSessionBean.getCurrent().equals(oneEntity) : false); } } } } else { throw new NotSupportedException("Tipo comparacion " + operador.getIdComparador() + " is not supported here!!"); } } else { return false; } } else { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { try { final Object find = getJpaController().find(class_, valorAttributo); if (find != null) { return find.equals(oneEntity); } else { return false; } } catch (java.lang.IllegalArgumentException e) { return getJpaController().find(class_, Integer.valueOf(valorAttributo)).equals(oneEntity); } } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { try { return !getJpaController().find(class_, valorAttributo).equals(oneEntity); } catch (java.lang.IllegalArgumentException e) { return !getJpaController().find(class_, Integer.valueOf(valorAttributo)).equals(oneEntity); } } else if (operador.equals(EnumTipoComparacion.CT.getTipoComparacion())) {//Changed TO =) if (value != null) { for (AuditLog auditLog : changeList) { if (comparableField.getIdCampo().equalsIgnoreCase(auditLog.getCampo())) { try { return getJpaController().find(class_, valorAttributo).equals(oneEntity); } catch (java.lang.IllegalArgumentException e) { return getJpaController().find(class_, Integer.valueOf(valorAttributo)).equals(oneEntity); } } } } } else { throw new NotSupportedException("Tipo comparacion " + operador.getIdComparador() + " is not supported here!!"); } } } } catch (Exception e) { e.printStackTrace(); } } else if (fieldType.equals(EnumFieldType.SELECTONE_PLACE_HOLDER.getFieldType())) { Object oneEntity = value; if (CasoJPACustomController.PLACE_HOLDER_ANY.equalsIgnoreCase(valorAttributo)) { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { return (oneEntity != null); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { return (oneEntity == null); } else { throw new NotSupportedException("Tipo comparacion " + operador.getIdComparador() + " is not supported here!!"); } } else if (CasoJPACustomController.PLACE_HOLDER_NULL.equalsIgnoreCase(valorAttributo)) { if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { return (oneEntity == null); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { return (oneEntity != null); } else { throw new NotSupportedException("Tipo comparacion " + operador.getIdComparador() + " is not supported here!!"); } } } else if (fieldType.equals(EnumFieldType.CHECKBOX.getFieldType())) { //Boolean comparation //El valor es de tipo boolean, usar el String parseado a un boolean try { Boolean valueBoolean = (Boolean) value; if (valueBoolean == null) { valueBoolean = false; } boolean boolValue = Boolean.valueOf(valorAttributo); if (operador.equals(EnumTipoComparacion.EQ.getTipoComparacion())) { return (valueBoolean == boolValue); } else if (operador.equals(EnumTipoComparacion.NE.getTipoComparacion())) { return (valueBoolean != boolValue); } else if (operador.equals(EnumTipoComparacion.CT.getTipoComparacion())) {//Changed TO =) if (valueBoolean != null) { for (AuditLog auditLog : changeList) { if (comparableField.getIdCampo().equalsIgnoreCase(auditLog.getCampo())) { return (valueBoolean == boolValue); } } } } else { throw new NotSupportedException("Comparador " + operador.getIdComparador() + " is not supported in RulesEngine!!"); } } catch (Exception e) { e.printStackTrace(); return false; } } else { throw new NotSupportedException("fieldType " + fieldType.getFieldTypeId() + " is not supported yet!!"); } return false; } /** * TODO redo all this actions architecture based in Action execute class! * @param accion * @param caso */ private void ejecutarAccion(Accion accion, Caso caso) { if (accion.getIdTipoAccion().equals(EnumTipoAccion.CAMBIO_CAT.getTipoAccion())) { cambiarCategoria(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.ASIGNAR_A_GRUPO.getTipoAccion())) { asignarCasoAGrupo(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.ASIGNAR_A_AREA.getTipoAccion())) { asignarCasoArea(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.CUSTOM.getTipoAccion())) { executeCustomAction(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.SCHEDULE_ACTION.getTipoAccion())) { executeScheduleAction(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.ASIGNAR_A_USUARIO.getTipoAccion())) { asignarCasoAUsuario(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.CAMBIAR_PRIORIDAD.getTipoAccion())) { cambiarPrioridad(accion, caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.RECALCULAR_SLA.getTipoAccion())) { recalcularSLA(caso); } else if (accion.getIdTipoAccion().equals(EnumTipoAccion.ENVIAR_EMAIL.getTipoAccion())) { enviarCorreo(accion, caso); } } private void enviarCorreo(Accion accion, Caso caso) { try { XStream xstream = new XStream(); EmailStruct emailStruct = (EmailStruct) xstream.fromXML(accion.getParametros()); MailClientFactory.getInstance(getJpaController().getSchema(), caso.getIdArea().getIdArea()) .sendHTML(emailStruct.getToAdress(), ManagerCasos.formatIdCaso(caso.getIdCaso()) + " " + emailStruct.getSubject(), emailStruct.getBody(), null); } catch (EmailException ex) { Logger.getLogger(RulesEngine.class.getName()).log(Level.SEVERE, "enviarCorreo", ex); } } private Integer extractId(String parametros) { try { int index = parametros.lastIndexOf(" ID[");//no tocar cuero pico de pulga if (index >= 0) { String sub = parametros.substring(index).split("\\[")[1]; String id = sub.replaceAll("]", ""); return Integer.parseInt(id); } } catch (Exception e) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "No se pudo extraer ID de categoria", e); } return null; } private void asignarCasoAUsuarioConMenosCasos(Grupo grupo, Caso caso) throws Exception { Usuario usuarioConMenosCasos = null; for (Usuario usuario : grupo.getUsuarioList()) { if (usuario.getActivo()) { if (usuarioConMenosCasos == null) { usuarioConMenosCasos = usuario; } else { if (usuarioConMenosCasos.getCasoList().size() > usuario.getCasoList().size()) { usuarioConMenosCasos = usuario; } } } } if (usuarioConMenosCasos != null) { caso.setOwner(usuarioConMenosCasos); getJpaController().mergeCasoWithoutNotify(caso); if (ApplicationConfig.getInstance(getJpaController().getSchema()).isSendNotificationOnTransfer()) { try { MailNotifier.notifyCasoAssigned(caso, null, getJpaController().getSchema()); } catch (Exception ex) { Logger.getLogger(RulesEngine.class.getName()).log(Level.SEVERE, "No se puede enviar notificacion por correo al agente asignado, dado que el area es null.", ex); } } } } private void cambiarCategoria(Accion accion, Caso caso) { try { int idCat = extractId(accion.getParametros()); Categoria cat = getJpaController().find(Categoria.class, idCat); caso.setIdCategoria(cat); getJpaController().mergeCasoWithoutNotify(caso); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "cambiarCategoria", ex); } } private void asignarCasoAGrupo(Accion accion, Caso caso) { try { Grupo grupo = getJpaController().find(Grupo.class, accion.getParametros()); asignarCasoAUsuarioConMenosCasos(grupo, caso); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "asignarCasoAGrupo", ex); } } private void asignarCasoAUsuario(Accion accion, Caso caso) { try { if (accion.getParametros() != null) { Usuario usuario = getJpaController().find(Usuario.class, accion.getParametros()); caso.setOwner(usuario); getJpaController().mergeCasoWithoutNotify(caso); if (ApplicationConfig.getInstance(getJpaController().getSchema()).isSendNotificationOnTransfer()) { try { MailNotifier.notifyCasoAssigned(caso, null, getJpaController().getSchema()); } catch (Exception ex) { Logger.getLogger(RulesEngine.class.getName()).log(Level.SEVERE, "asignarCasoAUsuario: No se puede enviar notificacion por correo al agente asignado, dado que el area es null."); } } } else { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "IllegalArgumentException: An instance of a null Usuario PK has been incorrectly provided for this find operation."); } } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, null, ex); } } private void asignarCasoArea(Accion accion, Caso caso) { try { Area area = getJpaController().find(Area.class, accion.getParametros()); caso.setIdArea(area); getJpaController().mergeCasoWithoutNotify(caso); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "asignarCasoArea", ex); } } private void executeCustomAction(Accion accion, Caso caso) { try { String clazzName = accion.getParametros(); // Constructor actionConstructor = Class.forName(clazzName).getConstructor(JPAServiceFacade.class, ManagerCasos.class); // Action actionInstance = (Action) actionConstructor.newInstance(getJpaController(), managerCasos); Action actionInstance = (Action) Class.forName(clazzName).newInstance(); // actionInstance.setJpaController(getJpaController()); // actionInstance.setManagerCasos(managerCasos); actionInstance.execute(caso, getJpaController().getSchema()); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "executeCustomAction", ex); } } private void executeScheduleAction(Accion accion, Caso caso) { try { Action actionInstance = new ScheduleJobAction(); actionInstance.setConfig(accion.getParametros()); actionInstance.execute(caso, getJpaController().getSchema()); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "executeCustomAction", ex); } } private void cambiarPrioridad(Accion accion, Caso caso) { try { Prioridad prioridad = getJpaController().find(Prioridad.class, accion.getParametros()); caso.setIdPrioridad(prioridad); getJpaController().mergeCasoWithoutNotify(caso); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "cambiarPrioridad", ex); } } private void recalcularSLA(Caso caso) { try { ManagerCasos.calcularSLA(caso); getJpaController().mergeCasoWithoutNotify(caso); } catch (Exception ex) { Logger.getLogger(ManagerCasos.class.getName()).log(Level.SEVERE, "recalcularSLA", ex); } } /** * @param userSessionBean the userSessionBean to set */ public void setUserSessionBean(UserSessionBean userSessionBean) { this.userSessionBean = userSessionBean; } /** * @param applicationBean the applicationBean to set */ public void setApplicationBean(ApplicationBean applicationBean) { this.applicationBean = applicationBean; } }
package interfaces; /** * @author dylan * */ public interface DrawAPI { /** * @param radius * @param x * @param y */ public void drawCircle(int radius, int x, int y); }
package use_multi_thread; /** * 实现多线程法二: * 实现 Runnable 接口 */ public class MyRunnable implements Runnable { private static int shareVar = 5; // 共享数据 private int var = 5; // 非共享数据,每个实例一份 @Override synchronized public void run() { shareVar--; var--; System.out.println("MyRunnable运行中, shareVar=" + shareVar + " var=" + var); } }
package generics; import java.util.Collection; import java.util.Map; import java.util.Set; /** * Created by user on 05.12.16. */ public abstract class Machine <Key, Value> { private Map<Key, Value> MAP = new Map<Key, Value>() { @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean containsKey(Object key) { return false; } @Override public boolean containsValue(Object value) { return false; } @Override public Value get(Object key) { return null; } @Override public Value put(Object key, Object value) { return null; } @Override public Value remove(Object key) { return null; } @Override public void putAll(Map m) { } @Override public void clear() { } @Override public Set keySet() { return null; } @Override public Collection values() { return null; } @Override public Set<Entry<Key, Value>> entrySet() { return null; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 0; } }; private long id; public Map<Key, Value> getMAP() { return MAP; } public long getId() { return id; } public void setId(long id) { this.id = id; } }
package com.fanoi.ximi.modules; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.widget.Toast; import com.fanoi.ximi.GlobalApplication; /** * activity的base类,用于基本数据的初始化 * * @author JetteZh */ public class BaseActivity extends FragmentActivity { private boolean isCloseBackKey = false; private boolean isOpenDoubleClickToExit = false; private long exitTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 默认存储所有的activity,用于管理应用的退出 GlobalApplication.getInstance().addActivity(this); } /** * 关闭返回键 */ public void closeBackKey() { this.isCloseBackKey = true; } /** * 打开返回键 */ public void openBackkey() { this.isCloseBackKey = false; } /** * 关闭二次点击退出功能 */ public void closeDoubleClickToExit() { this.isOpenDoubleClickToExit = false; } /** * 打开二次点击退出功能 */ public void openDoubleClickToExit() { this.isOpenDoubleClickToExit = true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (isCloseBackKey) { if (keyCode == KeyEvent.KEYCODE_BACK) return true; } if (isOpenDoubleClickToExit) { if (keyCode == KeyEvent.KEYCODE_BACK) { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(BaseActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); return true; } else { GlobalApplication.getInstance().exitApp(); } } } return super.onKeyDown(keyCode, event); } }
package com.zantong.mobilecttx.user.bean; import com.zantong.mobilecttx.base.bean.Result; /** * Created by zhengyingbing on 16/6/1. */ public class VcodeResult extends Result { private VcodeBean RspInfo; public VcodeBean getRspInfo() { return RspInfo; } public void setRspInfo(VcodeBean rspInfo) { RspInfo = rspInfo; } }
package edu.ptc.salter.bella; import edu.jenks.dist.ptc.*; public class PhoneNumber implements PhoneNumberable { String number = ""; String areaCode = ""; String prefix = ""; String lineNumber = ""; public static void main(String[] args) { PhoneNumber tester = new PhoneNumber("1-800-111 6222"); System.out.println(tester.toString()); } public PhoneNumber(String phoneNumber) { setNumber(phoneNumber); } public boolean equals(Object obj) { if(!(obj instanceof PhoneNumberable)) { return false; } PhoneNumberable num = (PhoneNumberable)obj; if(num.getAreaCode().contentEquals(areaCode) && num.getPrefix().contentEquals(prefix) && num.getLineNumber().contentEquals(lineNumber)) { return true; } return false; } public String getAreaCode() { if(!isValid()) { return "unknown area code"; } if(areaCode.length() == 3) { return areaCode; } return "unknown area code"; } public String getLineNumber() { if(!isValid()) { return "unknown line number"; } if(lineNumber.length() == 4) return lineNumber; return "unknown line number"; } public String getPrefix() { if(!isValid()) { return "unknown prefix"; } if(prefix.length() == 3) return prefix; return "unknown prefix"; } //this method checks to see if its valid number public boolean isValid() { for(int i = 0; i < number.length(); i++) { if(!isNum(number.substring(i, i+1)) && !(number.substring(i, i+1).equals(" ") || number.substring(i, i + 1).equals("-"))) { return false; } } number = getJustNum(number); if(number.length() > 11 || number.length() < 10) { return false; } else if(number.length() == 11 && !(number.substring(0 , 1).contentEquals("1"))) { return false; }else if((areaCode.contentEquals("") || prefix.contentEquals("")) || lineNumber.contentEquals("")) { return false; } else { return true; } } //this method does stuff public void setNumber(String phoneNumber) { System.out.println(number); String num = ""; num = phoneNumber; number = getJustNum(phoneNumber); if(number.length() == 11) { number = number.substring(1); } if(number.length() == 10) { areaCode = number.substring(0,3); prefix = number.substring(3,6); lineNumber = number.substring(6); } number = num; System.out.println(number); } public String toString() { if(!isValid()) { return "not valid"; } String finalStr = ""; finalStr = finalStr + areaCode + "-" + prefix + "-" + lineNumber; return finalStr; } public String getJustNum(String phoneNumber) { String num = ""; for(int i = 0; i < phoneNumber.length(); i++) { if(isNum(phoneNumber.substring(i, i + 1))) { num = num + phoneNumber.substring(i, i + 1); } } return num; } public boolean isNum(String str) { return (str.contentEquals("0")|| str.contentEquals("1") || str.contentEquals("2") || str.contentEquals("3") || str.contentEquals("4") || str.contentEquals("5") || str.contentEquals("6") || str.contentEquals("7") || str.contentEquals("8") || str.contentEquals("9")); } }
package db.connection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DbConnection { private static final String URL = "jdbc:mysql://localhost:3306/library"; private static String DB_NAME = "library"; private static final String USERNAME = "root"; private static final String PASSWORDS = "root"; public static Connection getConnectionDb() { try { return DriverManager.getConnection(URL, USERNAME, PASSWORDS); } catch (SQLException e) { e.printStackTrace(); return null; } } public static void setDbName(String dbName) { DB_NAME = dbName; } }
package com.auro.scholr.util.alert_dialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.ImageView; import androidx.fragment.app.DialogFragment; import com.auro.scholr.R; import com.auro.scholr.core.common.AppConstant; import com.auro.scholr.databinding.CertificateDialogBinding; import com.auro.scholr.util.ImageUtil; public class NativeQuizImageDialog extends DialogFragment implements View.OnClickListener { public Context context; private String msg; Dialog dialog; String imageLink; public static NativeQuizImageDialog newInstance(String imageName) { NativeQuizImageDialog f = new NativeQuizImageDialog(); // Supply num input as an argument. Bundle args = new Bundle(); args.putString(AppConstant.QuizNative.IMAGEINLARGE, imageName); f.setArguments(args); return f; } private CertificateDialogBinding binding; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (getArguments() != null) { imageLink = getArguments().getString(AppConstant.QuizNative.IMAGEINLARGE); } dialog = new Dialog(getActivity(), R.style.FullWidth_Dialog); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); View view = LayoutInflater.from(getActivity()).inflate(R.layout.certificate_dialog, null); ImageView imageView = (ImageView) view.findViewById(R.id.img); ImageView closeButton = (ImageView) view.findViewById(R.id.close_button); ImageView download = (ImageView) view.findViewById(R.id.download_icon); download.setVisibility(View.GONE); closeButton.setOnClickListener(this); download.setOnClickListener(this); ImageUtil.loadNormalImage(imageView,imageLink); dialog.setContentView(view); dialog.show(); return dialog; } @Override public void onClick(View view) { int id = view.getId(); if (id == R.id.close_button) { dismiss(); } else if (id == R.id.download_icon) { } } }
package com.github.rosjava.android_apps.blind_guide.data_manager; public interface dataLoader extends org.ros.internal.message.Message{ java.lang.String _TYPE = "com.github.rosjava.android_apps.blind_guide/data_manager/dataLoader"; java.lang.String _DEFINITION = "string a\n---\nstring result\n"; }
import javax.sound.sampled.Line; import java.awt.*; public class Main { public static void main(String[] args) { //an example of using linear regression to predict hunting success in chimpanzee hunting parties depending on the number of chimps in the party LinearRegression linreg = new LinearRegression(); double[] xData = {1,2,3,4,5,6,7,8}; double[] yData = {30, 45, 51, 57, 60, 65, 70, 71}; linreg.fit(xData, yData); System.out.println(linreg.predict(4)); } }
package be.vdab.teno.video.dao; import be.vdab.teno.video.entities.IVerhuurbaar; public interface IVerhuurbaarDao { IVerhuurbaar findById(int id); }
// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html // Decompiler options: packimports(3) fieldsfirst ansi // Source File Name: Base64Encoder.java package com.git.cloud.sys.tools; import java.io.*; import java.security.MessageDigest; /** * 加密工具辅助类 * @ClassName:Base64Encoder * @Description:TODO * @author dongjinquan * @date 2014-11-17 下午3:23:17 */ public final class Base64Encoder { private static final int BUFFER_SIZE = 1024; private static final byte encoding[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47, 61 }; public Base64Encoder() { } public static void encode(InputStream in, OutputStream out) throws IOException { process(in, out); } public static void encode(byte input[], OutputStream out) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(input); process(in, out); } public static String encode(String input) throws IOException { byte bytes[] = input.getBytes("ISO-8859-1"); return encode(bytes); } public static String encode(byte bytes[]) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(bytes); ByteArrayOutputStream out = new ByteArrayOutputStream(); process(in, out); return out.toString("ISO-8859-1"); } public static void main(String args[]) throws Exception { if(args.length == 1) System.out.println("[" + encode(args[0]) + "]"); else if(args.length == 2) { byte hash[] = MessageDigest.getInstance(args[1]).digest(args[0].getBytes()); System.out.println("[" + encode(hash) + "]"); } else { System.out.println("Usage: Base64Encoder <string> <optional hash algorithm>"); } } private static int get1(byte buf[], int off) { return (buf[off] & 0xfc) >> 2; } private static int get2(byte buf[], int off) { return (buf[off] & 0x3) << 4 | (buf[off + 1] & 0xf0) >>> 4; } private static int get3(byte buf[], int off) { return (buf[off + 1] & 0xf) << 2 | (buf[off + 2] & 0xc0) >>> 6; } private static int get4(byte buf[], int off) { return buf[off + 2] & 0x3f; } private static void process(InputStream in, OutputStream out) throws IOException { byte buffer[] = new byte[1024]; int got = -1; int off = 0; int count = 0; while((got = in.read(buffer, off, 1024 - off)) > 0) if(got >= 3) { got += off; for(off = 0; off + 3 <= got; off += 3) { int c1 = get1(buffer, off); int c2 = get2(buffer, off); int c3 = get3(buffer, off); int c4 = get4(buffer, off); switch(count) { case 73: // 'I' out.write(encoding[c1]); out.write(encoding[c2]); out.write(encoding[c3]); out.write(10); out.write(encoding[c4]); count = 1; break; case 74: // 'J' out.write(encoding[c1]); out.write(encoding[c2]); out.write(10); out.write(encoding[c3]); out.write(encoding[c4]); count = 2; break; case 75: // 'K' out.write(encoding[c1]); out.write(10); out.write(encoding[c2]); out.write(encoding[c3]); out.write(encoding[c4]); count = 3; break; case 76: // 'L' out.write(10); out.write(encoding[c1]); out.write(encoding[c2]); out.write(encoding[c3]); out.write(encoding[c4]); count = 4; break; default: out.write(encoding[c1]); out.write(encoding[c2]); out.write(encoding[c3]); out.write(encoding[c4]); count += 4; break; } } for(int i = 0; i < 3; i++) buffer[i] = i >= got - off ? 0 : buffer[off + i]; off = got - off; } else { off += got; } switch(off) { case 1: // '\001' out.write(encoding[get1(buffer, 0)]); out.write(encoding[get2(buffer, 0)]); out.write(61); out.write(61); break; case 2: // '\002' out.write(encoding[get1(buffer, 0)]); out.write(encoding[get2(buffer, 0)]); out.write(encoding[get3(buffer, 0)]); out.write(61); break; } } }
package io.ceph.rgw.client.model.admin; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.LocationTrait; import software.amazon.awssdk.utils.builder.Buildable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; /** * Created by zhuangshuo on 2020/8/4. */ public class Quota implements SdkPojo, Buildable { private static final SdkField<Boolean> ENABLED_FIELD = SdkField .builder(MarshallingType.BOOLEAN) .getter(getter(Quota::isEnabled)) .setter(setter(Quota::setEnabled)) .traits(LocationTrait.builder().location(MarshallLocation.PAYLOAD).locationName("enabled") .unmarshallLocationName("enabled").build()).build(); private static final SdkField<Boolean> CHECK_ON_RAW_FIELD = SdkField .builder(MarshallingType.BOOLEAN) .getter(getter(Quota::isCheckOnRaw)) .setter(setter(Quota::setCheckOnRaw)) .traits(LocationTrait.builder().location(MarshallLocation.PAYLOAD).locationName("check_on_raw") .unmarshallLocationName("check_on_raw").build()).build(); private static final SdkField<Integer> MAX_SIZE_FIELD = SdkField .builder(MarshallingType.INTEGER) .getter(getter(Quota::getMaxSize)) .setter(setter(Quota::setMaxSize)) .traits(LocationTrait.builder().location(MarshallLocation.PAYLOAD).locationName("max_size") .unmarshallLocationName("max_size").build()).build(); private static final SdkField<Integer> MAX_SIZE_KB_FIELD = SdkField .builder(MarshallingType.INTEGER) .getter(getter(Quota::getMaxSizeKb)) .setter(setter(Quota::setMaxSizeKb)) .traits(LocationTrait.builder().location(MarshallLocation.PAYLOAD).locationName("max_size_kb") .unmarshallLocationName("max_size_kb").build()).build(); private static final SdkField<Integer> MAX_OBJECTS_FIELD = SdkField .builder(MarshallingType.INTEGER) .getter(getter(Quota::getMaxObjects)) .setter(setter(Quota::setMaxObjects)) .traits(LocationTrait.builder().location(MarshallLocation.PAYLOAD).locationName("max_objects") .unmarshallLocationName("max_objects").build()).build(); private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList(ENABLED_FIELD, CHECK_ON_RAW_FIELD, MAX_SIZE_FIELD, MAX_SIZE_KB_FIELD, MAX_OBJECTS_FIELD)); private Boolean enabled; private Boolean checkOnRaw; private Integer maxSize; private Integer maxSizeKb; private Integer maxObjects; Quota() { } private static <T> Function<Object, T> getter(Function<Quota, T> g) { return obj -> g.apply((Quota) obj); } private static <T> BiConsumer<Object, T> setter(BiConsumer<Quota, T> s) { return (obj, val) -> s.accept((Quota) obj, val); } public Boolean isEnabled() { return enabled; } void setEnabled(Boolean enabled) { this.enabled = enabled; } // @JsonProperty("check_on_raw") public Boolean isCheckOnRaw() { return checkOnRaw; } void setCheckOnRaw(Boolean checkOnRaw) { this.checkOnRaw = checkOnRaw; } // @JsonProperty("max_size") public Integer getMaxSize() { return maxSize; } void setMaxSize(Integer maxSize) { this.maxSize = maxSize; } // @JsonProperty("max_size_kb") public Integer getMaxSizeKb() { return maxSizeKb; } void setMaxSizeKb(Integer maxSizeKb) { this.maxSizeKb = maxSizeKb; } // @JsonProperty("max_objects") public Integer getMaxObjects() { return maxObjects; } void setMaxObjects(Integer maxObjects) { this.maxObjects = maxObjects; } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } @Override public String toString() { return "Quota{" + "enabled=" + enabled + ", checkOnRaw=" + checkOnRaw + ", maxSize=" + maxSize + ", maxSizeKb=" + maxSizeKb + ", maxObjects=" + maxObjects + '}'; } @Override public Object build() { return this; } }
package com.avishai.MyShas; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.Map; import java.util.Set; /** * A class that represent a file object */ public class Keystore { private SharedPreferences SP; private String fileName; /** * A constructor to init the values * @param context - the context of the Activity that called the constructor * @param fileName - the name of the file * @param numOfPages - the number of the pages in the Masechet */ Keystore(Context context, String fileName, int numOfPages) { this.fileName = fileName; this.SP = context.getApplicationContext().getSharedPreferences(fileName, Context.MODE_PRIVATE); // to insert the pages at the first time if (!this.SP.contains("2")) { for (int i = 2; i <= numOfPages; ++i) { this.putBool(String.valueOf(i), false); } } } /** * Method to get the value for a given key * @param key - the key to get for it the value * @return - the boolean value */ Boolean getBool(String key) { return this.SP.getBoolean(key, false); } /** * Method to put in the file given value for a given key * @param key - the key to put for it the value * @param bool - the boolean value to insert */ final void putBool(String key, Boolean bool) { Editor editor = this.SP.edit(); editor.putBoolean(key, bool); editor.apply(); } /** * Method to clear the file (make all the pages as false) */ void clear(){ Editor editor = this.SP.edit(); editor.clear(); editor.apply(); } /** * Method to remove the file */ void remove(){ Editor editor = this.SP.edit(); editor.remove(this.fileName); editor.apply(); } /** * Method to get the numbers of given group of values (true / false) * @param learned - to determine whether to check learned / not learned pages * @return the sum of the requested pages */ int getNumOfGivenPages(Boolean learned) { int res = 0; Set<String> entry = this.SP.getAll().keySet(); for (String curr : entry) { if (this.SP.getBoolean(curr, learned) == learned) { ++res; } } return res; } }
package com.example.adnan.inventoryapp; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class FragmentProducts extends Fragment { sqlHandler sqlHandler; ListView listView; ArrayList<signatureProducts> list; public FragmentProducts() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_fragmentroducts, container, false); listView = (ListView) v.findViewById(R.id.listView); FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab); sqlHandler = new sqlHandler(getActivity()); list = new ArrayList<>(); refresh(); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Add Product"); builder.setMessage("Add you PRoduct Name, Quantity , and PRice!"); View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.product_alertview, null); final EditText peditName = (EditText) view1.findViewById(R.id.edit_pName); final EditText peditQuantity = (EditText) view1.findViewById(R.id.edit_pQuantity); final EditText peditPrice = (EditText) view1.findViewById(R.id.edit_pPrice); builder.setView(view1); builder.setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { signatureProducts products = new signatureProducts(peditName.getText().toString(), Integer.valueOf(peditQuantity.getText().toString()), Integer.valueOf(peditPrice.getText().toString())); sqlHandler.insertProduct(products); refresh(); } }); builder.create().show(); } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { int ids = list.get(position).getId(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Sales"); builder.setTitle("You want Sale this Product??"); builder.setPositiveButton("Sales", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); View vieww = LayoutInflater.from(getActivity()).inflate(R.layout.addsale_layout, null); final EditText editSale = (EditText) vieww.findViewById(R.id.add_sales); alert.setTitle("Enter Sale?"); alert.setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { int id = list.get(position).getId(); int noOfSales = list.get(position).getQuantity() - Integer.valueOf(editSale.getText().toString()); signatureProducts products = new signatureProducts(list.get(position).getName(), noOfSales, list.get(position).getId(), list.get(position).getPrice()); sqlHandler.updateValue(products); refresh(); signatureSales sales = new signatureSales(list.get(position).getName(), list.get(position).getPrice(), noOfSales, Integer.valueOf(editSale.getText().toString())); sqlHandler.insertSales(sales); DetailsFragment.refresh(); } catch (Exception ex) { ex.printStackTrace(); } } }); alert.setView(vieww); alert.create().show(); } }); builder.setNegativeButton("Delete Product", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int id = list.get(position).getId(); sqlHandler.deleteProduct(id, "products"); list.remove(position); refresh(); } }); builder.create().show(); } }); return v; } public void refresh() { list = sqlHandler.retrive(); adaptorProducts adaptorProducts = new adaptorProducts(getActivity(), list); listView.setAdapter(adaptorProducts); } }
package com.karya.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="bomtype001mb") public class BomType001MB { private static final long serialVersionUID = -723583058586873479L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "bomId") private int bomId; @Column(name="bomName") private String bomName; @Column(name="bomType") private String bomType; public int getBomId() { return bomId; } public void setBomId(int bomId) { this.bomId = bomId; } public String getBomName() { return bomName; } public void setBomName(String bomName) { this.bomName = bomName; } public String getBomType() { return bomType; } public void setBomType(String bomType) { this.bomType = bomType; } public static long getSerialversionuid() { return serialVersionUID; } }
package com.trump.auction.trade.vo; import com.trump.auction.trade.model.AuctionRuleModel; import com.trump.auction.trade.model.ProductInfo; import com.trump.auction.trade.model.ProductPic; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; /** * * 拍品信息VO * @author Administrator */ @Data public class AuctionProductInfoVo implements Serializable { private static final long serialVersionUID = -2153611927661069879L; /** * */ private Integer id; /** * */ private Integer productId; /** * 商品名称 */ private String productName; /** * 商品价格 */ private BigDecimal productPrice; /** * 上架数量 */ private Integer productNum; /** * 规则id */ private Integer ruleId; /** * 竞拍开始时间 */ private Date auctionStartTime; /** * 状态(1开拍中 2准备中 3定时) */ private Integer status; /** * 开始时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; /** * 操作者id */ private Integer userId; /** * 操作者ip */ private String userIp; /** * 拍品每期延迟时间 */ private Integer shelvesDelayTime; /** * 分类id */ private Integer classifyId; /** * */ private String classifyName; /** * 保留价 */ private BigDecimal floorPrice; /** * 浮动金额 */ private BigDecimal floatPrice; /** * 上架时间 */ private Date onShelfTime; /** * 下架时间 */ private Date underShelfTime; /** * 图片 */ List<ProductPic> productPics; List<AuctionProductPriceRuleVo> rules; ProductInfo productInfo; AuctionRuleModel auctionRuleModel; private String floatPrices; /** * 竞拍规则 */ private String auctionRule; }
/*insertbcomm*/ import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class insertbcomm extends HttpServlet { PreparedStatement ps; Connection c; public void init(ServletConfig config) { } public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { HttpSession session=req.getSession(); String rollnof,comment,sname,cate,query; int n=0; res.setContentType("text/html"); PrintWriter out=res.getWriter(); try { try { Class.forName("oracle.jdbc.driver.OracleDriver"); c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager"); ps=c.prepareStatement("insert into commentbpost values(?,?,TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS'),?,?)"); } catch(Exception e) { e.printStackTrace(); } rollnof=(String)session.getAttribute("rollno"); sname=(String)session.getAttribute("name"); comment=req.getParameter("comment"); n=Integer.parseInt(req.getParameter("val")); ps.setInt(1,n); ps.setString(2,comment); ps.setString(3,sname); ps.setString(4,rollnof); ps.executeUpdate(); //res.sendRedirect("http://localhost:8081/network/comments.html"); res.sendRedirect("/network/viewbooks"); c.close(); } catch(Exception e) { e.printStackTrace(); } } }
/* PROBLEM: Reverse a string in place. */ public class ReverseString { /* The easiest option is just to create a new string, then start from the end and add letters to the new string one at a time. However, this takes O(n) space and thus is not in place. Instead we could convert the string to char array, then swap the last with first, second to last with second, etc. but this still takes O(n) space UNLESS we make the char array the parameter. */ public static char[] reverse(char[] string) { for (int i = 0; i < string.length/2; i++) { char c = string[i]; string[i] = string[string.length-1-i]; string[string.length-1-i] = c; } return string; } public static void main(String[] args) { System.out.println(reverse("hello".toCharArray())); } }
package cn.com.xbed.common.source; /** * @Description:读写库的切换 * @author:Tom * @create 2017-03-06 15:07 **/ public class DataSourceSwitcher { /** * 主库,读写库,只一个 */ public static final String MASTER_DATA_SOURCE = "master"; /** * 从库,只读库,可有多个 */ public static final String[] SLAVE_DATA_SOURCE = {"slave"}; /** * 线程本地环境 */ private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); /** * 设置数据源 * @param customerType */ public static final synchronized void setCustomerType(String customerType) { contextHolder.set(customerType); } /** * 获取数据源 * @return */ public static String getCustomerType(){ return contextHolder.get(); } /** * 设置主库 */ public static void setMaster(){ setCustomerType(MASTER_DATA_SOURCE); } /** * 设置从库 */ public static void setSlave(){ setCustomerType(SLAVE_DATA_SOURCE[0]); } /** * 清除数据源 */ public static void clearCustomerType(){ contextHolder.remove(); } }
package cl.cehd.ocr.algorithm.processor; import cl.cehd.ocr.algorithm.entity.AccountDigit; import cl.cehd.ocr.algorithm.entity.DigitRepresentationDictionary; import cl.cehd.ocr.algorithm.entity.IndividualDigitIdentifier; import org.junit.Before; import org.junit.Test; import java.util.List; import static cl.cehd.ocr.kata.TestHelper.digitDataForTestPurpose; import static org.junit.Assert.assertEquals; public class IndividualDigitIdentifierTest { private IndividualDigitIdentifier individualDigitIdentifier; private List<AccountDigit> individualDigitData; @Before public void setUp() { individualDigitData = digitDataForTestPurpose().generateDigits(); DigitRepresentationDictionary digitRepresentationDictionary = new DigitRepresentationDictionary(); individualDigitIdentifier = new IndividualDigitIdentifier(digitRepresentationDictionary); } @Test public void givenAZeroRepresentationMustReturnValueZero() { AccountDigit zero = new AccountDigit(" _ ", "| |", "|_|"); String digitValue = individualDigitIdentifier.readDigitValue(zero); assertEquals("0", digitValue); } @Test public void givenAOneRepresentationMustReturnValueOne() { AccountDigit zeroRepresentation = individualDigitData.get(0); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("1", digitValue); } @Test public void givenATwoRepresentationMustReturnValueTwo() { AccountDigit zeroRepresentation = individualDigitData.get(1); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("2", digitValue); } @Test public void givenATwoRepresentationMustReturnValueThree() { AccountDigit zeroRepresentation = individualDigitData.get(2); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("3", digitValue); } @Test public void givenAFourRepresentationMustReturnValueFour() { AccountDigit zeroRepresentation = individualDigitData.get(3); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("4", digitValue); } @Test public void givenAFiveRepresentationMustReturnValueFive() { AccountDigit zeroRepresentation = individualDigitData.get(4); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("5", digitValue); } @Test public void givenASixRepresentationMustReturnValueSix() { AccountDigit zeroRepresentation = individualDigitData.get(5); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("6", digitValue); } @Test public void givenASixRepresentationMustReturnValueSeven() { AccountDigit zeroRepresentation = individualDigitData.get(6); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("7", digitValue); } @Test public void givenASixRepresentationMustReturnValueEight() { AccountDigit zeroRepresentation = individualDigitData.get(7); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("8", digitValue); } @Test public void givenASixRepresentationMustReturnValueNine() { AccountDigit zeroRepresentation = individualDigitData.get(8); String digitValue = individualDigitIdentifier.readDigitValue(zeroRepresentation); assertEquals("9", digitValue); } /*@Test(expected = UnsupportedOperationException.class) public void givenAnInvalidRepresentationMustReturnValueQuestion() { IndividualDigitData zeroRepresentation = new IndividualDigitData("", "", ""); String digitValue = individualDigitProcessor.readDigitValue(zeroRepresentation); assertEquals("?", digitValue); }*/ }
/* * Copyright 2017 Google Inc. All Rights Reserved. * * 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.surrus.galwaybus.ar; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.os.Bundle; import com.google.android.material.snackbar.BaseTransientBottomBar; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.Toast; import com.google.ar.core.Anchor; import com.google.ar.core.Camera; import com.google.ar.core.Config; import com.google.ar.core.Frame; import com.google.ar.core.HitResult; import com.google.ar.core.Plane; import com.google.ar.core.PointCloud; import com.google.ar.core.Session; import com.google.ar.core.Trackable; import com.google.ar.core.Trackable.TrackingState; import com.google.ar.core.exceptions.UnavailableApkTooOldException; import com.google.ar.core.exceptions.UnavailableArcoreNotInstalledException; import com.google.ar.core.exceptions.UnavailableSdkTooOldException; import com.surrus.galwaybus.R; import com.surrus.galwaybus.ar.rendering.BackgroundRenderer; import com.surrus.galwaybus.ar.rendering.ObjectRenderer; import com.surrus.galwaybus.ar.rendering.PlaneRenderer; import com.surrus.galwaybus.ar.rendering.PointCloudRenderer; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ArrayBlockingQueue; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * This is a simple example that shows how to create an augmented reality (AR) application using the * ARCore API. The application will display any detected planes and will allow the user to tap on a * plane to place a 3d model of the Android robot. */ public class HelloArActivity extends AppCompatActivity implements GLSurfaceView.Renderer { private static final String TAG = HelloArActivity.class.getSimpleName(); // Rendering. The Renderers are created here, and initialized when the GL surface is created. private GLSurfaceView mSurfaceView; private Session mSession; private GestureDetector mGestureDetector; private Snackbar mMessageSnackbar; private DisplayRotationHelper mDisplayRotationHelper; private final BackgroundRenderer mBackgroundRenderer = new BackgroundRenderer(); private final ObjectRenderer mVirtualObject = new ObjectRenderer(); private final ObjectRenderer mVirtualObjectShadow = new ObjectRenderer(); private final PlaneRenderer mPlaneRenderer = new PlaneRenderer(); private final PointCloudRenderer mPointCloud = new PointCloudRenderer(); // Temporary matrix allocated here to reduce number of allocations for each frame. private final float[] mAnchorMatrix = new float[16]; // Tap handling and UI. private final ArrayBlockingQueue<MotionEvent> mQueuedSingleTaps = new ArrayBlockingQueue<>(16); private final ArrayList<Anchor> mAnchors = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_helloar); mSurfaceView = findViewById(R.id.surfaceview); mDisplayRotationHelper = new DisplayRotationHelper(/*context=*/ this); // Set up tap listener. mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { onSingleTap(e); return true; } @Override public boolean onDown(MotionEvent e) { return true; } }); mSurfaceView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return mGestureDetector.onTouchEvent(event); } }); // Set up renderer. mSurfaceView.setPreserveEGLContextOnPause(true); mSurfaceView.setEGLContextClientVersion(2); mSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // Alpha used for plane blending. mSurfaceView.setRenderer(this); mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); Exception exception = null; String message = null; try { mSession = new Session(/* context= */ this); } catch (UnavailableArcoreNotInstalledException e) { message = "Please install ARCore"; exception = e; } catch (UnavailableApkTooOldException e) { message = "Please update ARCore"; exception = e; } catch (UnavailableSdkTooOldException e) { message = "Please update this app"; exception = e; } catch (Exception e) { message = "This device does not support AR"; exception = e; } if (message != null) { showSnackbarMessage(message, true); Log.e(TAG, "Exception creating session", exception); return; } // Create default config and check if supported. Config config = new Config(mSession); if (!mSession.isSupported(config)) { showSnackbarMessage("This device does not support AR", true); } mSession.configure(config); } @Override protected void onResume() { super.onResume(); // ARCore requires camera permissions to operate. If we did not yet obtain runtime // permission on Android M and above, now is a good time to ask the user for it. if (CameraPermissionHelper.hasCameraPermission(this)) { if (mSession != null) { showLoadingMessage(); // Note that order matters - see the note in onPause(), the reverse applies here. mSession.resume(); } mSurfaceView.onResume(); mDisplayRotationHelper.onResume(); } else { CameraPermissionHelper.requestCameraPermission(this); } } @Override public void onPause() { super.onPause(); // Note that the order matters - GLSurfaceView is paused first so that it does not try // to query the session. If Session is paused before GLSurfaceView, GLSurfaceView may // still call mSession.update() and get a SessionPausedException. mDisplayRotationHelper.onPause(); mSurfaceView.onPause(); if (mSession != null) { mSession.pause(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) { if (!CameraPermissionHelper.hasCameraPermission(this)) { Toast.makeText(this, "Camera permission is needed to run this application", Toast.LENGTH_LONG).show(); if (!CameraPermissionHelper.shouldShowRequestPermissionRationale(this)) { // Permission denied with checking "Do not ask again". CameraPermissionHelper.launchPermissionSettings(this); } finish(); } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { // Standard Android full-screen functionality. getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } private void onSingleTap(MotionEvent e) { // Queue tap if there is space. Tap is lost if queue is full. mQueuedSingleTaps.offer(e); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { GLES20.glClearColor(0.1f, 0.1f, 0.1f, 1.0f); // Create the texture and pass it to ARCore session to be filled during update(). mBackgroundRenderer.createOnGlThread(/*context=*/ this); if (mSession != null) { mSession.setCameraTextureName(mBackgroundRenderer.getTextureId()); } // Prepare the other rendering objects. try { mVirtualObject.createOnGlThread(/*context=*/this, "andy.obj", "andy.png"); mVirtualObject.setMaterialProperties(0.0f, 3.5f, 1.0f, 6.0f); mVirtualObjectShadow.createOnGlThread(/*context=*/this, "andy_shadow.obj", "andy_shadow.png"); mVirtualObjectShadow.setBlendMode(ObjectRenderer.BlendMode.Shadow); mVirtualObjectShadow.setMaterialProperties(1.0f, 0.0f, 0.0f, 1.0f); } catch (IOException e) { Log.e(TAG, "Failed to read obj file"); } try { mPlaneRenderer.createOnGlThread(/*context=*/this, "trigrid.png"); } catch (IOException e) { Log.e(TAG, "Failed to read plane texture"); } mPointCloud.createOnGlThread(/*context=*/this); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { mDisplayRotationHelper.onSurfaceChanged(width, height); GLES20.glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 gl) { // Clear screen to notify driver it should not load any pixels from previous frame. GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); if (mSession == null) { return; } // Notify ARCore session that the view size changed so that the perspective matrix and // the video background can be properly adjusted. mDisplayRotationHelper.updateSessionIfNeeded(mSession); try { // Obtain the current frame from ARSession. When the configuration is set to // UpdateMode.BLOCKING (it is by default), this will throttle the rendering to the // camera framerate. Frame frame = mSession.update(); Camera camera = frame.getCamera(); // Handle taps. Handling only one tap per frame, as taps are usually low frequency // compared to frame rate. MotionEvent tap = mQueuedSingleTaps.poll(); if (tap != null && camera.getTrackingState() == TrackingState.TRACKING) { for (HitResult hit : frame.hitTest(tap)) { // Check if any plane was hit, and if it was hit inside the plane polygon Trackable trackable = hit.getTrackable(); if (trackable instanceof Plane && ((Plane) trackable).isPoseInPolygon(hit.getHitPose())) { // Cap the number of objects created. This avoids overloading both the // rendering system and ARCore. if (mAnchors.size() >= 20) { mAnchors.get(0).detach(); mAnchors.remove(0); } // Adding an Anchor tells ARCore that it should track this position in // space. This anchor is created on the Plane to place the 3d model // in the correct position relative both to the world and to the plane. mAnchors.add(hit.createAnchor()); // Hits are sorted by depth. Consider only closest hit on a plane. break; } } } // Draw background. mBackgroundRenderer.draw(frame); // If not tracking, don't draw 3d objects. if (camera.getTrackingState() == TrackingState.PAUSED) { return; } // Get projection matrix. float[] projmtx = new float[16]; camera.getProjectionMatrix(projmtx, 0, 0.1f, 100.0f); // Get camera matrix and draw. float[] viewmtx = new float[16]; camera.getViewMatrix(viewmtx, 0); // Compute lighting from average intensity of the image. final float lightIntensity = frame.getLightEstimate().getPixelIntensity(); // Visualize tracked points. PointCloud pointCloud = frame.acquirePointCloud(); mPointCloud.update(pointCloud); mPointCloud.draw(viewmtx, projmtx); // Application is responsible for releasing the point cloud resources after // using it. pointCloud.release(); // Check if we detected at least one plane. If so, hide the loading message. if (mMessageSnackbar != null) { for (Plane plane : mSession.getAllTrackables(Plane.class)) { if (plane.getType() == Plane.Type.HORIZONTAL_UPWARD_FACING && plane.getTrackingState() == TrackingState.TRACKING) { hideLoadingMessage(); break; } } } // Visualize planes. mPlaneRenderer.drawPlanes( mSession.getAllTrackables(Plane.class), camera.getDisplayOrientedPose(), projmtx); // Visualize anchors created by touch. float scaleFactor = 1.0f; for (Anchor anchor : mAnchors) { if (anchor.getTrackingState() != TrackingState.TRACKING) { continue; } // Get the current pose of an Anchor in world space. The Anchor pose is updated // during calls to session.update() as ARCore refines its estimate of the world. anchor.getPose().toMatrix(mAnchorMatrix, 0); // Update and draw the model and its shadow. mVirtualObject.updateModelMatrix(mAnchorMatrix, scaleFactor); mVirtualObjectShadow.updateModelMatrix(mAnchorMatrix, scaleFactor); mVirtualObject.draw(viewmtx, projmtx, lightIntensity); mVirtualObjectShadow.draw(viewmtx, projmtx, lightIntensity); } } catch (Throwable t) { // Avoid crashing the application due to unhandled exceptions. Log.e(TAG, "Exception on the OpenGL thread", t); } } private void showSnackbarMessage(String message, boolean finishOnDismiss) { mMessageSnackbar = Snackbar.make( HelloArActivity.this.findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE); mMessageSnackbar.getView().setBackgroundColor(0xbf323232); if (finishOnDismiss) { mMessageSnackbar.setAction( "Dismiss", new View.OnClickListener() { @Override public void onClick(View v) { mMessageSnackbar.dismiss(); } }); mMessageSnackbar.addCallback( new BaseTransientBottomBar.BaseCallback<Snackbar>() { @Override public void onDismissed(Snackbar transientBottomBar, int event) { super.onDismissed(transientBottomBar, event); finish(); } }); } mMessageSnackbar.show(); } private void showLoadingMessage() { runOnUiThread(new Runnable() { @Override public void run() { showSnackbarMessage("Searching for surfaces...", false); } }); } private void hideLoadingMessage() { runOnUiThread(new Runnable() { @Override public void run() { if (mMessageSnackbar != null) { mMessageSnackbar.dismiss(); } mMessageSnackbar = null; } }); } }
/* * 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 fahrstuhlsimulator; import java.util.ArrayList; /** * * @author mex */ public class Etage implements tick { protected int etagenNummer; protected ArrayList<Person> etagenPersonen; protected ArrayList<Person> wartezimmerPersonen; public Etage(int etagenNummer) { //System.out.println("Ich bin Etage: " + etagenNummer); this.etagenNummer=etagenNummer; this.etagenPersonen = new ArrayList<Person>(); this.wartezimmerPersonen = new ArrayList<Person>(); } public int getEtagenNummer(){ return this.etagenNummer; } public int getAnzahlDerPersonenImWartezimmer(){ return this.wartezimmerPersonen.size(); } public int getAnzahlDerPersonInDerEtage(){ return this.etagenPersonen.size(); } /** * Fügt die übergebene Person der Liste etagenPersonen hinzu * @param person */ public void bewegePersonInWartezimmer(Person person){ this.etagenPersonen.add(person); } /** * Fügt die übergebene Person der Liste wartezimmerPersonen hinzu * @param person */ public void bewegePersonInEtage(Person person){ this.wartezimmerPersonen.add(person); } /** * Personen, deren Aufenthaltsdauer in einer Etage vorbei ist, * werden aus dieser entfernt, löschen ihren Aufenthalt und * werden in dem Wartezimmer der jeweiligen Etage zugefügt. * Die anderen verringern ihre Aufenthaltsdauer. */ public void aktualisierePersonen(){ for (int i=0; i < etagenPersonen.size(); i++) { if (etagenPersonen.get(i).getAktuellenAufenthalt().getAufenthaltsdauer() == 0) { etagenPersonen.get(i).loescheAktuellenAufenthalt(); wartezimmerPersonen.add(etagenPersonen.get(i)); etagenPersonen.remove(i); i++; continue; } else { etagenPersonen.get(i).getAktuellenAufenthalt().verkleinereAufenthaltsdauer(); } } } public boolean istFahrstuhlBenoetigt(){ return !wartezimmerPersonen.isEmpty(); } public void bewegePersonenInEtage(ArrayList<Person> personen){ this.etagenPersonen.addAll(personen); } public Person lassePersonInFahrstuhlEinsteigen(){ return wartezimmerPersonen.remove(0); } public void tick() { System.out.println("##### Etage "+ this.etagenNummer +":"); System.out.println("----- im Wartezimmer: " + this.wartezimmerPersonen.size()); System.out.println("----- in der Etage: " + this.etagenPersonen.size()); this.aktualisierePersonen(); } }
package myProject.second; import java.awt.Graphics; import java.awt.image.BufferedImage; public class TileLevel1 { public static TileLevel1[] tiles = new TileLevel1[24]; /* public static Tile roadTile = new roadTile(0); public static Tile grassTile = new grassTile(1); public static Tile footPathTile = new footPathTile(2);*/ public static TileLevel1 roadTile = new roadTileLevel1(0); public static TileLevel1 grassTile = new grassTileLevel1(1); public static TileLevel1 footPathTile = new footPathTileLevel1(2); public BufferedImage texture; public static final int tileWidth = 64, tileHeight = 64; public TileLevel1(BufferedImage texture,int id) { this.texture = texture; tiles[id] = this; } public void render(Graphics g,int x,int y) { g.drawImage(texture, x,y, null); } }
package com.nick.java.game.runner; import com.nick.java.game.items.Constants; import com.nick.java.game.items.Control; import com.nick.java.game.items.Box; import javax.swing.*; import java.applet.Applet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.net.MalformedURLException; import java.net.URL; /* <APPLET CODE="start" HEIGHT="500" WIDTH="800"> </APPLET> */ public class StartTicTacToe extends Applet implements MouseListener,ActionListener { //creating font of text Font century = new Font("Century",Font.BOLD,20); Font kristen = new Font("Kristen ITC",Font.BOLD,30); //info box JLabel board = new JLabel(); //creating squares private Box s[]=new Box[9]; //creating current position private int user,computer=-1; //setting the priority of square private static final int pri[] ={4,0,2,6,8,1,3,5,7}; //creating wining condition private static final int win[][] = { {0,1,2},{3,4,5},{6,7,8}, {0,3,6},{1,4,7},{2,5,8}, {0,4,8},{2,4,6} }; private static final int win1[][] = { {4,1,3},{4,0,2},{4,1,5}, {4,0,6},{0,2,6,8,1,3,5,7},{4,2,8}, {4,3,7},{4,6,8},{4,5,7} }; private int temp[]; //setting symbol of players private static final String s1 ="X"; //for user private static final String s2 ="O"; //for computer private String st; //creating number of palyesr private int player; //creating counter private int counter; //count no of win & draw private int cwin,uwin,draw; Control con; URL baseUrl; //intiating the applet................................. public void init() { con = new Control(this); setLayout(null); setBackground(Color.black); for(int i=0;i<9;i++) { s[i]= new Box(); s[i].setSize(100,100); add(s[i]); if(i%2!=0) s[i].setBackground(Color.yellow); s[i].addMouseListener(this); } s[0].setLocation(50,50); s[1].setLocation(150,50); s[2].setLocation(250,50); s[3].setLocation(50,150); s[4].setLocation(150,150); s[5].setLocation(250,150); s[6].setLocation(50,250); s[7].setLocation(150,250); s[8].setLocation(250,250); board.setBounds(50,400,300,50); board.setForeground(Color.yellow); board.setFont(kristen); add(board); con.setLocation(500,0); add(con); setPlayer(con.counter2+1); //clear(); this.setSize(1000,500); //create URL try { baseUrl = new URL("file:"+ Constants.resourceFolder+"/audio/"); } catch (MalformedURLException e) { e.printStackTrace(); } } public void setPlayer(int p) { player=p; } //public void method /* * starting private methods.................. * */ //call when game is finished private void finish() { for(int i=0;i<9;i++) { s[i].removeMouseListener(this); } } //call when start the game public void clear() { for(int i=0;i<9;i++) { s[i].addMouseListener(this); s[i].setStatus(0); s[i].setText(null); board.setText(""); } if(counter%2==0&&player==1) { turn(); counter=0; } if(counter%2==0&&player==2) st=s2; counter++; } //computer normal turn private void normalTurn(int sum) { for(int i=0;i<8;i++) { int b1 =s[win[i][0]].getStatus(); int b2 =s[win[i][1]].getStatus(); int b3 =s[win[i][2]].getStatus(); if(b1+b2+b3==sum) { if(b1==0) computer=win[i][0]; else if(b2==0) computer=win[i][1]; else if(b3==0) computer=win[i][2]; break; } } } //computer advanced turn private void advancedTurn() { for(int k=0;k<9;k++) { if(user==k) { temp=win1[k]; } } for(int i=0;i<temp.length;i++) { if(s[temp[i]].getStatus()==0) { for(int j=0;j<8;j++) { int x1=s[win[j][0]].getStatus(); int x2=s[win[j][1]].getStatus(); int x3=s[win[j][2]].getStatus(); if(s[win[j][0]]==s[temp[i]]&&((x2==0&&x3==-1)|(x3==0&&x2==-1))) { computer=temp[i]; break; } else if(s[win[j][1]]==s[temp[i]]&&((x1==0&&x3==-1)|(x1==-1&&x3==0))) { computer=temp[i]; break; } else if(s[win[j][2]]==s[temp[i]]&&((x2==0&&x1==-1)|(x2==-1&&x1==0))) { computer=temp[i]; break; } } } } } //computer default turn private void defaultTurn() { for(int i=0;i<9;i++) { if(s[pri[i]].getStatus()==0) { computer=pri[i]; break; } } } //calling all computer turns private void turn() { //cheking when computer going to win if(computer==-1&&(con.counter1==1||con.counter1==2)) normalTurn(-2); //checking when user going to win if(computer==-1&&(con.counter1==1||con.counter1==2)) normalTurn(2); //checking according to user if(computer==-1&&con.counter1==2) advancedTurn(); //play default turn if(computer==-1) defaultTurn(); //finally display the copmuter turn if(computer!=-1) { s[computer].setText(s2); s[computer].setStatus(-1); computer=-1; } check(); } //check the game private void check() { //checking darw condition int c=0; for(int k=0;k<9;k++) { if(s[k].getStatus()!=0) c++; if(c==9) { board.setText("Game is Draw"); play(baseUrl,"lader.au"); } } //checking wining condition int x=0; for(int i=0;i<8;i++) { x=0; for(int j=0;j<3;j++) { x=s[win[i][j]].getStatus()+x; } if(x==3) { if(player==1) board.setText("User Win"); else board.setText("User1 Win"); finish(); play(baseUrl,"yahoo2.au"); break; } else if(x==-3) { if(player==1) board.setText("Computer Win"); else board.setText("User2 Win"); finish(); play(baseUrl,"yahoo2.au"); break; } } } /* * * Starting Listener methods */ public void mouseClicked(MouseEvent me) { play(baseUrl,"click2.au"); Object o = me.getSource(); if(player==1) st=s1; else { if(st==s1) st=s2; else st=s1; } for(int i=0;i<9;i++) { if(o==s[i]&&s[i].getStatus()==0) { if(player==2) { s[i].setText(st); s[i].removeMouseListener(this); if(st==s1) s[i].setStatus(1); else s[i].setStatus(-1); check(); } else { user=i; s[i].setText(st); s[i].removeMouseListener(this); s[i].setStatus(1); check(); if(board.getText().equals("Computer Win")||board.getText().equals("User Win")) { finish(); }else { turn(); } break; } } } } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void actionPerformed(ActionEvent ae) { } }
package Lec_04_NestedConditionalStatements; import java.util.Scanner; public class Pro_04_04_NewHouse { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Въведете вида на цветята: "); String typeFlower = scanner.nextLine(); System.out.print("Въведете броя на цветята: "); int numberFlowers = Integer.parseInt(scanner.nextLine()); System.out.print("Въведете бюджета с който се разполага: "); int budget = Integer.parseInt(scanner.nextLine()); // "Roses", "Dahlias", "Tulips", "Narcissus", "Gladiolus" double sumForFlowers = 0.0; if ("Roses".equals(typeFlower)){ sumForFlowers = numberFlowers * 5.00; if (numberFlowers > 80){ sumForFlowers *= 0.90; } } else if ("Dahlias".equals(typeFlower)){ sumForFlowers = numberFlowers * 3.80; if (numberFlowers > 90){ sumForFlowers *= 0.85; } } else if ("Tulips".equals(typeFlower)){ sumForFlowers = numberFlowers * 2.80; if (numberFlowers > 80){ sumForFlowers *= 0.85; } } else if ("Narcissus".equals(typeFlower)){ sumForFlowers = numberFlowers * 3.00; if (numberFlowers < 120){ sumForFlowers *= 1.15; } } else if ("Gladiolus".equals(typeFlower)){ sumForFlowers = numberFlowers * 2.50; if (numberFlowers < 80){ sumForFlowers *= 1.20; } } double differense = Math.abs(budget - sumForFlowers); if (budget >= sumForFlowers){ System.out.printf("Hey, you have a great garden with %d %s and %.2f leva left.", numberFlowers, typeFlower, differense); } else { System.out.printf("Not enough money, you need %.2f leva more.", differense); } } }
package org.aksw.autosparql.tbsl.algorithm.util; import org.aksw.autosparql.commons.index.Indices; import org.aksw.autosparql.tbsl.algorithm.search.BugfixedSolrIndex; import org.aksw.autosparql.tbsl.algorithm.search.DbpediaFilter; import org.aksw.autosparql.tbsl.algorithm.search.FilteredIndex; import org.dllearner.common.index.HierarchicalIndex; import org.dllearner.common.index.Index; /** @author konrad * Capsules the necessary settings for the AKSW solr server settings */ public enum SolrServer { INSTANCE; public Indices getIndices() {return dbpediaIndices;} static public final String SOLR_SERVER_URI_EN = "http://linkedspending.aksw.org/solr/en_"; static public final String SOLR_SERVER_URI_EN_DBPEDIA_RESOURCES = SOLR_SERVER_URI_EN+"dbpedia_resources"; static public final String SOLR_SERVER_URI_EN_DBPEDIA_CLASSES = SOLR_SERVER_URI_EN+"dbpedia_classes"; static public final String SOLR_SERVER_URI_EN_DBPEDIA_DATA_PROPERTIES = SOLR_SERVER_URI_EN+"dbpedia_data_properties"; static public final String SOLR_SERVER_URI_EN_DBPEDIA_OBJECT_PROPERTIES = SOLR_SERVER_URI_EN+"dbpedia_object_properties"; // static final String BOA_SERVER_URI_EN = "http://[2001:638:902:2010:0:168:35:138]:8080/solr/boa"; public final Index resourcesIndex; public final Index classesIndex; public final Index dataPropertiesIndex; public final Index objectPropertiesIndex; public final Indices dbpediaIndices; // // boa index already integrated // private SolrServerAksw() // { // resourcesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN+"dbpedia_resources"); // classesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN+"dbpedia_classes"); // dataPropertiesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN+"dbpedia_data_properties"); // objectPropertiesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN+"dbpedia_object_properties"); // for(BugfixedSolrIndex index: new BugfixedSolrIndex[] {resourcesIndex,classesIndex,objectPropertiesIndex,dataPropertiesIndex}) // {index.setPrimarySearchField("label");} // dbpediaIndices = new Indices(resourcesIndex,classesIndex,objectPropertiesIndex,dataPropertiesIndex); // } // separate boa index private SolrServer() { BugfixedSolrIndex resourcesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN_DBPEDIA_RESOURCES); BugfixedSolrIndex classesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN_DBPEDIA_CLASSES); BugfixedSolrIndex dataPropertiesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN_DBPEDIA_DATA_PROPERTIES); BugfixedSolrIndex objectPropertiesIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN_DBPEDIA_OBJECT_PROPERTIES); for(BugfixedSolrIndex index: new BugfixedSolrIndex[] {resourcesIndex,classesIndex,objectPropertiesIndex,dataPropertiesIndex}) {index.setPrimarySearchField("label");} BugfixedSolrIndex boaIndex = new BugfixedSolrIndex(SOLR_SERVER_URI_EN+"boa","nlr-no-var"); boaIndex.setSortField("boa-score"); // boaIndex.getResources("test"); this.resourcesIndex = new FilteredIndex(resourcesIndex, DbpediaFilter.INSTANCE); this.classesIndex = new FilteredIndex(classesIndex, DbpediaFilter.INSTANCE); this.dataPropertiesIndex= new FilteredIndex(new HierarchicalIndex(dataPropertiesIndex,boaIndex),DbpediaFilter.INSTANCE); this.objectPropertiesIndex = new FilteredIndex(new HierarchicalIndex(objectPropertiesIndex,boaIndex),DbpediaFilter.INSTANCE); dbpediaIndices = new Indices(this.resourcesIndex,this.classesIndex,this.objectPropertiesIndex,this.dataPropertiesIndex); } }
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { private static int maximumHourGlass(int[][] arr) { int top=0,mid=0,bottom=0,max=-99999; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { top = arr[i][j]+arr[i][j+1]+arr[i][j+2]; mid = arr[i+1][j+1]; bottom = arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]; if(max<(top+mid+bottom)) { max = top+mid+bottom; } } } return max; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int arr[][] = new int[6][6]; for(int arr_i=0; arr_i < 6; arr_i++){ for(int arr_j=0; arr_j < 6; arr_j++){ arr[arr_i][arr_j] = in.nextInt(); } } System.out.println(maximumHourGlass(arr)); } }