text
stringlengths
10
2.72M
package com.tencent.tencentmap.mapsdk.a; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Build.VERSION; import android.os.Process; import android.telephony.TelephonyManager; import java.lang.reflect.InvocationTargetException; public class t { public static String a = "TencentMapSDK"; private static String b; private static String c; private static String d; private static String e; private static String f; private static String g; private static String h; public static void a(Context context) { String b; if (b == null) { b = b(context); b = b; b = a(b); } if (c == null) { b = c(context); c = b; c = a(b); } if (d == null) { b = Build.MODEL; d = b; d = a(b); } if (e == null) { e = VERSION.RELEASE; } if (f == null) { b = d(context); f = b; f = a(b); } if (g == null) { b = context.getPackageName(); g = b; g = a(b); } if (h == null) { b = e(context); h = b; h = a(b); } } public static String a() { return b; } public static String b() { return c; } public static String c() { return d; } public static String d() { return e; } public static String e() { return f; } public static String f() { return g; } public static String g() { return h; } private static String b(Context context) { String str = ""; if (VERSION.SDK_INT < 21) { return "armeabi-v7a"; } if (VERSION.SDK_INT >= 21 && VERSION.SDK_INT < 23) { String str2; try { Object invoke = ClassLoader.class.getDeclaredMethod("findLibrary", new Class[]{String.class}).invoke(context.getClassLoader(), new Object[]{"art"}); if (invoke != null) { str2 = ((String) invoke).contains("lib64") ? Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; if (str2 != null) { return Build.SUPPORTED_ABIS[0]; } return str2; } } catch (NoSuchMethodException e) { str2 = str; } catch (IllegalAccessException e2) { str2 = str; } catch (InvocationTargetException e3) { str2 = str; } catch (NullPointerException e4) { } str2 = str; if (str2 != null) { return str2; } return Build.SUPPORTED_ABIS[0]; } else if (VERSION.SDK_INT < 23) { return str; } else { if (Process.is64Bit()) { return Build.SUPPORTED_64_BIT_ABIS[0]; } return Build.SUPPORTED_32_BIT_ABIS[0]; } } private static String c(Context context) { if (context == null) { return ""; } TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService("phone"); if (telephonyManager == null) { return ""; } if (VERSION.SDK_INT <= 22) { return telephonyManager.getDeviceId(); } if (context.checkSelfPermission("android.permission.READ_PHONE_STATE") != 0) { return "no permission"; } return telephonyManager.getDeviceId(); } private static String d(Context context) { if (context == null) { return ""; } PackageManager packageManager = context.getPackageManager(); ApplicationInfo applicationInfo = null; try { applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 128); } catch (NameNotFoundException e) { } return applicationInfo.loadLabel(packageManager).toString(); } private static String e(Context context) { if (context == null) { return ""; } ApplicationInfo applicationInfo = null; try { applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 128); } catch (NameNotFoundException e) { } if (applicationInfo == null) { return ""; } if (applicationInfo.metaData == null) { return ""; } return applicationInfo.metaData.getString(a); } private static String a(String str) { if (str == null) { return ""; } return str.replace("&", "").replace("#", "").replace("?", ""); } }
package game.controllers; import desktop_resources.GUI; import game.Dice; import game.Player; public class JailController { /** *metode der holder styr på spilleren i fængsel *tjekker først hvor lang tid de har været i fængsel *giver så valget mellem at slå 2 ens eller betale *hvis de ikke kommer ud opdateres deres TimeJailed */ public void handle(Player player, Dice dice) { if(player.getTimeJailed() >= 3){ //Først tjekker den om spilleren har været jailed i 3 runder. Hvis ja så bliver hans jailed sat til false player.setJailed(false); player.setTimeJailed(0); GUI.showMessage("You have served your time in jail, and you have been released"); player.setPosition(10); //GUI isn't 0 indexed so we add 1 GUI.setCar(player.getPosition()+1, player.getName()); } else{ //hvis hans TimeJailed ikke er 3 eller større kører den videre til næste statement if (GUI.getUserButtonPressed(player.getName() + ", You are in jail, roll two equal dice to get out of jail, or pay 3000", "Roll", "Pay") .equals("Roll")) //Valget kommer frem på GUI'en: Betal 3000 eller prøv at rolle 2 ens terninger { dice.roll(); if(dice.getEquals()){ //Hvis han vælger at rolle og får 2 ens terninger løslades han. player.setJailed(false); GUI.showMessage("You rolled two equal dice, and therefore the guards are inclined to release you"); player.setPosition(10); //GUI isn't 0 indexed so we add 1 GUI.setCar(player.getPosition()+1, player.getName()); } else{ //hvis han vælger at rolle og ikke får 2 ens forbliver han jailed og hans TimeJailed opdateres med +1 GUI.showMessage("You failed to roll two equal die, and therefore you are still jailed"); player.setTimeJailed(player.getTimeJailed() + 1); } } else{ //Hvis han vælger at betale 3000 trækkes pengene fra hans account og han løslades player.getAccount().withdraw(3000); GUI.setBalance(player.getName(), player.getAccount().getBalance()); player.setJailed(false); GUI.showMessage("Your grandmother paid the bail, and you gave her the money back, you are a free man"); player.setPosition(10); //GUI isn't 0 indexed so we add 1 GUI.setCar(player.getPosition()+1, player.getName()); } } } /** *Metode der bruges hvis en spiller har rollet 2 ens terninger fra runder i træk. *hans jailed = true og han flyttes til jail feltet */ public void goToJail(Player player) { player.setJailed(true); GUI.removeAllCars(player.getName()); player.setPosition(10); // GUI isn't 0 indexed so we add 1 GUI.setCar(player.getPosition() + 1, player.getName()); GUI.showMessage("You rolled two equal dice 3 times in a row. Go to jail."); } }
package com.tfjybj.integral.constant; /** * @program: integralV3.0-sprint1.0 * @description: service错误消息 * @author: 赵雷 * @create: 2019-10-05 09:57 **/ public class ErrorMessageConstant { public static final String AddPoints_Point_Less="该用户总积分不足"; public static final String AddPoints_GivingRecord_Fail="存入Redis被加分人的接收记录失败"; public static final String AddPoints_GiviedRecord_Fail="存入Redis加分人送分记录失败"; public static final String AddPoints_Params_Exception="加分参数异常"; public static final String MinusPoints_GiviedRecord_Fail="存入Redis加分人减分记录失败"; public static final String MinusPoints_Params_Exception="减分参数异常"; }
package Controllers; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Models.ForgotPassword; import dao.ForgotPasswordDao; /** * Servlet implementation class ForgetPasswordController */ @WebServlet("/ForgetPasswordController") public class ForgetPasswordController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ForgetPasswordController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ ForgotPasswordDao fdao = new ForgotPasswordDao(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub ForgotPassword u = new ForgotPassword(); u.setUsername(request.getParameter("username")); u.setPassword(request.getParameter("password")); if (fdao.forget(u)) { request.getSession().setAttribute("notification", "Updated successfully !"); request.getRequestDispatcher("ForgetPassword.jsp").forward(request, response); } else { request.getSession().setAttribute("notification", "Update unsuccessfull"); request.getRequestDispatcher("ForgetPassword.jsp").forward(request, response); } } }
package com.hotmail.at.jablonski.michal.shoppinglist.ui.details.listAdapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.CheckBox; import android.widget.TextView; import com.hotmail.at.jablonski.michal.shoppinglist.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public abstract class ShoppingListAdapter extends RecyclerView.Adapter<ShoppingListAdapter.ViewHolder> { private final boolean isArchived; private List<ShoppingItem> shoppingListItems; private int lastPosition = -1; public ShoppingListAdapter(List<ShoppingItem> shoppingListItems, boolean isArchived) { this.shoppingListItems = shoppingListItems; this.isArchived = isArchived; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_shopping_list, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { ShoppingItem item = shoppingListItems.get(position); holder.checkBoxIsBought.setChecked(item.isBought()); holder.textViewIngredientName.setText(item.getItemName()); if (isArchived) { holder.checkBoxIsBought.setEnabled(false); holder.delete.setVisibility(View.GONE); } else setCheckListener(item, holder); animateHolder(position, holder); } private void setCheckListener(ShoppingItem item, ViewHolder holder) { holder.checkBoxIsBought.setOnCheckedChangeListener((buttonView, isChecked) -> onCheckedItem(isChecked, item)); holder.delete.setOnClickListener(v -> onDeleteClicked(item)); } private void animateHolder(int position, ViewHolder viewHolder) { if (position > lastPosition) { Animation animation = AnimationUtils .loadAnimation(viewHolder.getContext(), R.anim.recycler_anim); viewHolder.itemView.startAnimation(animation); lastPosition = position; } } @Override public int getItemCount() { return shoppingListItems.size(); } static class ViewHolder extends RecyclerView.ViewHolder { ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public Context getContext() { return itemView.getContext(); } @BindView(R.id.isBought) CheckBox checkBoxIsBought; @BindView(R.id.item_name) TextView textViewIngredientName; @BindView(R.id.layout_delete_item) View delete; } public void setShoppingList(List<ShoppingItem> shoppingList) { this.shoppingListItems = shoppingList; } public List<ShoppingItem> getShoppingListItems() { return shoppingListItems; } protected abstract void onCheckedItem(boolean checked, ShoppingItem item); protected abstract void onDeleteClicked(ShoppingItem item); }
package cn.timebusker.web; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import cn.timebusker.service.ArithmeticService; @RestController public class IndexController { private final static Logger logger = LoggerFactory.getLogger(IndexController.class); @Autowired private ArithmeticService arithmeticService; @SuppressWarnings("static-access") @RequestMapping(value = { "/" }, method = RequestMethod.GET) public void index() { long start = System.currentTimeMillis(); try { logger.info("--------------------------------------------\n"); logger.info("每个任务执行的时间是:" + arithmeticService.DoTime + "(毫秒)"); Future<Long> task = arithmeticService.subByAsync(); arithmeticService.subByVoid(); long sync = arithmeticService.subBySync(); while (true) { if (task.isDone()) { long async = task.get(); logger.info("异步任务执行的时间是:" + async + "(毫秒)"); // logger.info("注解任务执行的时间是: -- (毫秒)"); logger.info("同步任务执行的时间是:" + sync + "(毫秒)"); break; } } logger.info("--------------------------------------------\n"); } catch (Exception e) { e.printStackTrace(); } long end = System.currentTimeMillis(); logger.info("\t........请求响应时间为:" + (end - start) + "(毫秒)"); } /** * 自定义实现线程异步 */ @RequestMapping(value = { "/mine", "/m*" }, method = RequestMethod.GET) public void mineAsync() { for (int i = 0; i < 100; i++) { try { arithmeticService.doMineAsync(i); } catch (Exception e) { e.printStackTrace(); } } } }
// assignment 9 // pair p134 // Singh, Bhavneet // singhb // Wang, Shiyu // shiyu import java.util.Comparator; //This class represents a comparator for Strings class StringComparator implements Comparator<String> { /* Template: * * Fields: * None * * Methods: * ...this.compare(String, String)... -- int * * Methods for Fields: * No fields * */ // compares two strings lexographically public int compare(String first, String second) { return first.compareTo(second); } }
package com.fang.example.spring.di; import com.fang.example.spring.di.util.BeanEntry; import com.fang.example.spring.di.util.ConfigGenerator; import com.fang.example.spring.di.util.EntryGenerator; import org.springframework.context.support.FileSystemXmlApplicationContext; /** * Created by andy on 4/2/16. */ public class DITest1 { public static void main(String[]args) throws Exception { String classPath = System.getProperty("java.class.path"); System.out.println("classpath=" + classPath); EntryGenerator.addEntry(ConfigGenerator.class, BeanEntry.class); EntryGenerator.addEntry("quest", RecuseDamselQuest.class, BeanEntry.class); EntryGenerator.addEntry("knight", BraveKnight.class, BeanEntry.class, RecuseDamselQuest.class); ConfigGenerator.createSpringFile(System.getProperty("user.dir"), "knight.xml"); FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("knight.xml"); Knight knight = (Knight) context.getBean("knight"); knight.embarkOnquest(); } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.trading.chart.drawings; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import com.qtplaf.library.trading.chart.parameters.BarPlotParameters; import com.qtplaf.library.trading.chart.plotter.PlotterContext; import com.qtplaf.library.trading.data.Data; /** * A bar drawing. * * @author Miquel Sas */ public class Bar extends DataDrawing { /** Plot parameters. */ private BarPlotParameters parameters; /** Indexes to retrieve data. */ private int[] indexes; /** * Constructor assigning the values. * * @param index The data index. * @param data The data. * @param indexes The indexes to retrieve values. * @param parameters Plot parameters. */ public Bar(int index, Data data, int[] indexes, BarPlotParameters parameters) { super(index, data); this.indexes = indexes; this.parameters = parameters; setName("Bar"); } /** * Returns the bar plot parameters. * * @return The bar plot parameters. */ public BarPlotParameters getParameters() { return parameters; } /** * Check if this bar or candlestick is bullish. * * @return A boolean indicating if this bar or candlestick is bullish. */ public boolean isBullish() { return Data.isBullish(getData()); } /** * Check if this bar or candlestick is bearish. * * @return A boolean indicating if this bar or candlestick is bearish. */ public boolean isBearish() { return Data.isBearish(getData()); } /** * Returns the bar shape. * * @param context The plotter context. * @return The bar shape. */ @Override public Shape getShape(PlotterContext context) { // The values to plot. Data data = getData(); double open = data.getValue(indexes[0]); double high = data.getValue(indexes[1]); double low = data.getValue(indexes[2]); double close = data.getValue(indexes[3]); // The X coordinate to start painting. int x = context.getCoordinateX(getIndex()); // And the Y coordinate for each value. int openY = context.getCoordinateY(open); int highY = context.getCoordinateY(high); int lowY = context.getCoordinateY(low); int closeY = context.getCoordinateY(close); // The X coordinate of the vertical line, either the candle. int barWidth = context.getDataItemWidth(); int verticalLineX = context.getDrawingCenterCoordinateX(x); GeneralPath shape = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 3); // The vertical bar line. shape.moveTo(verticalLineX, highY); shape.lineTo(verticalLineX, lowY); // Open and close horizontal lines if the bar width is greater than 1. if (barWidth > 1) { // Open horizontal line. shape.moveTo(x, openY); shape.lineTo(verticalLineX - 1, openY); // Close horizontal line shape.moveTo(verticalLineX + 1, closeY); shape.lineTo(x + barWidth - 1, closeY); } return shape; } /** * Draw the candlestick. * * @param g2 The graphics object. * @param context The plotter context. */ @Override public void draw(Graphics2D g2, PlotterContext context) { // Save color and stroke. Color saveColor = g2.getColor(); Stroke saveStroke = g2.getStroke(); // Set the stroke and color. g2.setStroke(getParameters().getStroke()); g2.setColor(getParameters().getColor()); // Draw g2.draw(getShape(context)); // Restore color and stroke. g2.setColor(saveColor); g2.setStroke(saveStroke); } }
package UnionFInd; import java.util.Scanner; //Weighted quick union with path compression // Hay n elementos en una lista con su indice, cuando se conectan dos elementos el indice del arbol más pequeño de uno, definido en otra lista) apunta al siguiente, creando arboles con ramas no tan alejadas de la raiz // Inicializar involucra hacer un arreglo de (1,...,n) por lo que la iniciación es O(n) // Al unir solo cambia un indice, pero para unir la cabeza con el arbol más pequeño se puede considerar los nodos modelados con la función de Ackerman anteriores O(A) // Al checar si estan concetados se tienen que checar las cabezas, O(A) // Initialize O(n) // Union O(A) // Connected O(A) public class IWQuickUF { private int[] id; private int[] sz; // Se inicializa el arreglo de n posiciones con indices y otro de tamaño con 0s // O(n) public IWQuickUF(int N) { id = new int[N]; sz = new int[N]; for (int i = 0; i < N; i++) { id[i] = i; } } // Se busca la cabeza del arbol // Si la posición y el index no son el mismo, va a la posición de la posición a // la que apunta y mueve el elemento un nivel para aplanar el árbol // O(1) -> O(A) private int root(int i) { while (i != id[i]); id[i] = id[id[i]]; i = id[i]; return i; } // Se buscan ambas cabezas y se conectan cuando la cabeza más pequeña apunta a // la otra // O(1), pero considerar la complejidad de root public void union(int p, int q) { int i = root(p); int j = root(q); if (i == j) return; if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } } // Se comparan las cabezas, si son las mismas regresa verdadero // O(1), pero considerar la complejidad de root public boolean connected(int p, int q) { return (root(p) == root(q)); } // Comprueba su funcionamiento al definir cuantos elementos son y cuantas // uniones se quieren hacer public static void main(String[] args) { Scanner scan = new Scanner(System.in); int N = scan.nextInt(); int veces = scan.nextInt(); IWQuickUF uf = new IWQuickUF(N); for (int i = 0; i < veces; i++) { int p = scan.nextInt(); int q = scan.nextInt(); if (!uf.connected(p, q)) { uf.union(p, q); System.out.println(p + " " + q); } } scan.close(); } }
package setServer; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import setGame.Game; public class GameRoom implements Comparable<GameRoom> { // Used for server-side house keeping // Transient means gson will exclude this field // which is good (it was creating a stack overflow error) public transient ConcurrentHashMap<String, SetMultiThread> threadsInRoom = new ConcurrentHashMap<String, SetMultiThread>(); private String room_name; private transient Game curGame; public boolean gameStarted = false; public Date timeCreated; public static int roomCapacity = 30; public ConcurrentHashMap<String, User> usersInRoom = new ConcurrentHashMap<String, User>(); public User getWinner() { Iterator itUsers = usersInRoom.keySet().iterator(); User winner = usersInRoom.get(itUsers.next()); itUsers = usersInRoom.keySet().iterator(); while(itUsers.hasNext()) { String key = (String) itUsers.next(); User curUser = usersInRoom.get(key); if (curUser.totalScore > winner.totalScore) { winner = curUser; } } return winner; } // Starts a game in the currnt room. Cards are dealt to all users in the room public Game startGame() { gameStarted = true; curGame = new Game(); curGame.start(); return curGame; } public Game getCurGame() { return curGame; } // Create and join a game room public GameRoom (String name, SetMultiThread thread) { timeCreated = new Date(); room_name = name; join(thread); SetServer.gameRooms.put(room_name, this); } // Create a game room // Only used for the lobby. public GameRoom (String name) { timeCreated = new Date(); room_name = name; SetServer.gameRooms.put(room_name, this); } // Join a game room public void join(SetMultiThread thread) { if (thread.currentRoom != null) { thread.currentRoom.leave(thread); } thread.currentRoom = this; threadsInRoom.put(thread.getName(), thread); usersInRoom.put(thread.currentUser.getName(), thread.currentUser); } // Leave a game room public void leave(SetMultiThread thread) { threadsInRoom.remove(thread.getName()); usersInRoom.remove(thread.currentUser.getName()); if (threadsInRoom.isEmpty() & !getName().equals(SetServer.lobby.getName())) { SetServer.gameRooms.remove(getName()); } } // Setting up an array for use with the front end room buttons public static ArrayList<GameRoom> getRoomsArray() { ArrayList<GameRoom> roomsArray = new ArrayList<GameRoom>(); Iterator<String> itRooms = SetServer.gameRooms.keySet().iterator(); //Filter out the rooms while (itRooms.hasNext()) { String key = (String) itRooms.next(); GameRoom curRoom = SetServer.gameRooms.get(key); if (curRoom.getName().equals("lobby")) { continue; } roomsArray.add(SetServer.gameRooms.get(key)); } //Sort the rooms by date... Collections.sort(roomsArray); return roomsArray; } // Get room's name public String getName() { return room_name; } // Used to sort the tables on the GUI -- most recently created table will show up first. public int compareTo(GameRoom game) { int lastCmp = game.timeCreated.compareTo(timeCreated); return lastCmp; } public String toString() { return getName(); } }
package dao; import entity.Category; import java.util.List; public interface CategoryDao { List<Category> getAllCategory(); Category read(long categoryId); void saveOrUpdate(Category category); void delete(long id); }
/** * Copyright 2007 Jens Dietrich 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 nz.org.take.compiler.reference; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import nz.org.take.AggregationFunction; import nz.org.take.Aggregations; import nz.org.take.Constant; import nz.org.take.Predicate; import nz.org.take.PrimitiveTypeUtils; import nz.org.take.Query; import nz.org.take.Term; import nz.org.take.Variable; import nz.org.take.compiler.CompilerException; /** * Abstract superclass for template based function generators. * @author <a href="http://www-ist.massey.ac.nz/JBDietrich/">Jens Dietrich</a> */ public abstract class AbstractTemplatedBasedAggregationFunctionGenerator implements AggregationFunctionGenerator { public abstract String getTemplateName() ; public Query createAggregationFunction(PrintWriter out,AggregationFunction f, CompilerUtils owner)throws CompilerException { String templateName = getTemplateName(); Template template = TemplateManager.getInstance().getTemplate(templateName); Predicate predicate = f.getQuery().getPredicate(); // build the query and the variable list List<String> queryParams = new ArrayList<String>(); StringBuffer methodParams = new StringBuffer(); String aggregationVariable = null; boolean[] io = new boolean[predicate.getSlotTypes().length]; for (int i=0;i<io.length;i++) { io[i] = i!=f.getVariableSlot(); Term t = f.getQuery().getTerms()[i]; if (io[i]) { if (t instanceof Variable) { queryParams.add("arg"+i); if (methodParams.length()>0) { methodParams.append(','); } methodParams.append(t.getType().getName()); methodParams.append(' '); methodParams.append("arg"); methodParams.append(i); } else if (t instanceof Constant) { queryParams.add(owner.getRef(owner.getNameGenerator().getConstantRegistryClassName(),(Constant)t)); } // complex terms are not yet supported } else { Slot slot = owner.buildSlot(predicate,i); aggregationVariable = slot.getVar(); } } QueryRef query = new QueryRef(predicate,io,queryParams); Class returnType = null; Class convertedType = PrimitiveTypeUtils.getType(f.getReturnType()); if (convertedType!=null) returnType = convertedType; // query invocation StringWriter sout = new StringWriter(); owner.printInvocation(new PrintWriter(sout),query,false,false); sout.flush(); // bind template variables VelocityContext context = new VelocityContext(); String methodName = owner.getMethodName(f); context.put("query", query); context.put("methodname",methodName); context.put("methodparameters",methodParams); context.put("resulttype",returnType); context.put("templatename",templateName); context.put("invocation",sout.getBuffer().toString()); context.put("varslot",aggregationVariable); context.put("resultsettype",owner.getClassName(predicate)); context.put("function",f.getName()); try { template.merge(context, out); } catch (Exception x) { throw new CompilerException("Problem merging compilation template",x); } return query; } public abstract Aggregations getSupportedAggregation() ; }
/** * */ package com.ricex.cartracker.androidrequester.request; import com.ricex.cartracker.androidrequester.request.exception.RequestException; /** * @author Mitchell Caisse * */ public interface Request<T> { /** Executes the request synchronously and returns the results of the request * * @return The results of the request * @throws RequestException When an issue occurred while executing the request */ public T execute() throws RequestException; /** Executes the request synchronously and calls the callback with the results or error * * @param callback The callback to call when the request is finished executing */ public void executeAsync(RequestCallback<T> callback); }
package org.tc; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; /** * 请求https, 忽略证书 */ public class HttpsClient { public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { String url = "https://kyfw.12306.cn/otn/"; try (CloseableHttpClient httpClient = createHttpClient()) { HttpGet httpGet = new HttpGet(url); try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { HttpEntity entity = httpResponse.getEntity(); String result = EntityUtils.toString(entity); EntityUtils.consume(entity); System.out.printf(result); } } } private static CloseableHttpClient createHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(null, (chain, authType) -> true) .build(); SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null, new NoopHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(sslSf).build(); } }
package mapUtils; import gate.*; import gate.util.GateException; import org.springframework.util.Assert; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; public class CreateMapToModify { private static final String USER_PROJECT_DIRECTORY = System.getProperty("user.dir"); private static final String USER_HOME_DIRECTORY = System.getProperty("user.home"); private static final String POSITIVE = "POSITIVE"; private static final String POS = "POS"; private static final String NEGATIVE = "NEGATIVE"; private static final String NEG = "NEG"; private static final String NEU = "NEU"; @SuppressWarnings("deprecation") public static void main(String[] args) { try { if(Gate.getGateHome() == null) { Gate.setGateHome(new File(USER_HOME_DIRECTORY + "/GATE_Developer_8.0")); //Gate.setGateHome(new File("C:\\Users\\u124275\\Desktop\\gate-8.0-build4825-BIN")); //Gate.setGateHome(new File("D:\\Program Files\\GATE_Developer_8.0")); } if(Gate.getPluginsHome() == null) { Gate.setPluginsHome(new File(USER_HOME_DIRECTORY + "/GATE_Developer_8.0/plugins")); //Gate.setPluginsHome(new File("C:\\Users\\u124275\\Desktop\\gate-8.0-build4825-BIN\\plugins")); //Gate.setPluginsHome(new File("D:\\Program Files\\GATE_Developer_8.0\\plugins")); } Gate.init(); String encoding = "UTF-8"; File inDir = new File("./data/analysed2"); File[] flist = inDir.listFiles(); String floc; Document d; Annotation tweet; AnnotationSet tweets; String app="???"; FeatureMap fm; Map<Object,Object> mp; Map<Object,Object> mpUsr; ArrayList<Double> coordinates; Double lati; Double longi; String usrName; String id; String creation; String text; int num_locs; int num_orgs; int num_urls; int num_pers; String newTextHeat = ""; String newTextCircle = ""; String color; color = "#FF00FF"; String posColor = "#39d639"; String negColor = "#c1140b"; String neuColor = "#d9e01f"; StringBuilder textToWriteHeat = new StringBuilder(); StringBuilder textToWriteCircle = new StringBuilder(); String sentiLabel = null; int numOfGeoFound = 0; assert flist != null; for (File file : flist) { newTextHeat = ""; newTextCircle = ""; floc = file.getAbsolutePath(); System.out.println(floc); d = Factory.newDocument(new URL("file:///" + floc), encoding); // Document tweets = d.getAnnotations("Original markups").get("Tweet"); tweet = tweets.iterator().next(); fm = tweet.getFeatures(); mp = (Map<Object, Object>) fm.get("geo"); mpUsr = (Map<Object, Object>) fm.get("user"); id = (String) fm.get("id"); creation = (String) fm.get("created_at"); usrName = (String) mpUsr.get("screen_name"); text = d.getContent().toString(); if (mp != null) { coordinates = (ArrayList<Double>) mp.get("coordinates"); lati = coordinates.get(0); longi = coordinates.get(1); numOfGeoFound++; System.out.println(numOfGeoFound + " of " + flist.length); num_locs = getNumberOfLocation(d); num_orgs = getNumberOrganization(d); num_pers = getNumberPerson(d); num_urls = getNumberUrl(d); try { sentiLabel = getSentiment(d); }catch (Exception e){ e.printStackTrace(); } //---- HEAT MAP ---- newTextHeat = "new google.maps.LatLng(" + lati + "," + longi + "),"; //---- CRCL MAP ---- StringBuilder newtext = new StringBuilder(); text = text.replace("\n", " ").replace("'", " "); for (String token : text.split(" ")) { if (token.contains("http")) { newtext.append("<a href=\"").append(token).append("\" target=\"_blank\"> link </a>"); } else newtext.append(token).append(" "); } Assert.notNull(sentiLabel); switch (sentiLabel) { case POS: color = posColor; break; case NEG: color = negColor; break; case NEU: color = neuColor; break; default: break; } newTextCircle = " id" + id + ": {center: {lat: " + lati + ", lng: " + longi + "}," + "color: '" + color + "'," + "user: '" + usrName + " " + id + " ·+'," + "application: '" + app + "'," + "time: '" + creation + "'," + "text: '(SENT: " + sentiLabel + ", Locations: " + num_locs + ", Organizations: " + num_orgs + ", Persons: " + num_pers + ", Urls: " + num_urls + ", NewText: " + newtext + "'," + "},"; } textToWriteHeat.append(newTextHeat).append("\n"); textToWriteCircle.append(newTextCircle).append("\n"); } String fs = System.getProperty("file.separator"); String inputFileHeat = "maps"+fs+ "heat-map-madrid.html"; String inputFileCircle = "maps"+fs+ "circle-map-madrid.html"; //other if here to decide which kind of map to create MapsUtils.createNewMap(inputFileHeat, textToWriteHeat.toString()); MapsUtils.createNewMap(inputFileCircle, textToWriteCircle.toString()); } catch (GateException | MalformedURLException ex) { ex.printStackTrace(); } } private static int getNumberUrl(Document document) { return document.getAnnotations().get("URL").size(); } private static int getNumberOrganization(Document document) { return document.getAnnotations().get("Organization").size(); } private static int getNumberPerson(Document document) { return document.getAnnotations().get("Person").size(); } private static int getNumberOfLocation(Document document) { return document.getAnnotations().get("Location").size(); } private static String getSentiment(Document document) throws Exception{ AnnotationSet sentimentsSets = document.getNamedAnnotationSets().get("Sentiment"); Annotation lookup; FeatureMap fm; Iterator<Annotation> ite= sentimentsSets.iterator(); String label; int pos = 0; int neg = 0; while(ite.hasNext()) { lookup = ite.next(); fm = lookup.getFeatures(); label = fm.get("majorType").toString(); // compute sentiment value if (label.equals(POSITIVE)) { pos = pos + 1; } else if (label.equals(NEGATIVE)) { neg = neg + 1; } else { throw new Exception("Unexpected label."); } } int sentimentNumber = pos - neg; // compute sentiment label according to senti value if (sentimentNumber < 0){ return NEG; } else if (sentimentNumber > 0){ return POS; } else { return NEU; } } }
package com.zihui.cwoa.system.service; import com.zihui.cwoa.system.dao.sys_user_roleMapper; import com.zihui.cwoa.system.pojo.sys_user_role; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class sys_user_roleService { @Resource private sys_user_roleMapper userRoleMapper; public int deleteByPrimaryKey(Integer id){ return userRoleMapper.deleteByPrimaryKey(id); }; public int insertSelective(sys_user_role record){ return userRoleMapper.insertSelective(record); }; public sys_user_role selectByPrimaryKey(Integer id){ return userRoleMapper.selectByPrimaryKey(id); }; public int updateByPrimaryKeySelective(sys_user_role record){ return userRoleMapper.updateByPrimaryKeySelective(record); }; public int insertUserAndRole(Integer userId,Integer roleId){ return userRoleMapper.insertUserAndRole(userId,roleId); }; public int deleteUserRole(Integer userId,Integer roleId){ return userRoleMapper.deleteUserRole(userId,roleId); }; }
package com.tencent.mm.plugin.setting.ui.setting; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.setting.model.h; class SettingsModifyUserAuthUI$2 implements OnCancelListener { final /* synthetic */ SettingsModifyUserAuthUI mSY; final /* synthetic */ h mSZ; SettingsModifyUserAuthUI$2(SettingsModifyUserAuthUI settingsModifyUserAuthUI, h hVar) { this.mSY = settingsModifyUserAuthUI; this.mSZ = hVar; } public final void onCancel(DialogInterface dialogInterface) { g.DF().c(this.mSZ); } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class SWEA_10888_음식배달 { private static StringBuilder sb = new StringBuilder(); private static int N,ans, ans2; private static List<Pair> house; private static List<Pair> chain; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int T = Integer.parseInt(br.readLine()); for (int t = 1; t <= T; t++) { N = Integer.parseInt(br.readLine()); house = new ArrayList<>(); chain = new ArrayList<>(); for (int r = 0; r < N; r++) { st = new StringTokenizer(br.readLine()); for (int c = 0; c < N; c++) { int tmp = Integer.parseInt(st.nextToken()); if(tmp == 1) house.add(new Pair(r,c,0)); else if(tmp> 1) chain.add(new Pair(r,c,tmp)); } } ans2 = Integer.MAX_VALUE; subset(); sb.append("#").append(t +" ").append(ans2).append("\n"); } System.out.println(sb); } private static void find(List<Pair> list) { ans = 0; boolean[] visited = new boolean[chain.size()]; for (int i = 0; i < house.size(); i++) { Pair h = house.get(i); int cnt = Integer.MAX_VALUE; for (int j = 0; j < list.size(); j++) { Pair c = list.get(j); int tmp = Math.abs(h.r -c.r) + Math.abs(h.c -c.c); cnt = Math.min(cnt, Math.abs(h.r -c.r) + Math.abs(h.c -c.c)); } ans+=cnt; } for (int i = 0; i < list.size(); i++) { ans+= list.get(i).cost; } } public static void subset() { for (int i = 1; i < 1<< chain.size(); i++) { List<Pair> list = new ArrayList<>(); for (int j = 0; j < chain.size(); j++) { if((i & (1<<j))>0) list.add(chain.get(j)); } find(list); ans2 = Math.min(ans2, ans); } } public static class Pair{ int r,c,cost; @Override public String toString() { return "Pair [r=" + r + ", c=" + c + ", cost=" + cost + "]"; } public Pair(int r, int c, int cost) { super(); this.r = r; this.c = c; this.cost = cost; } } }
package com.example.algorithm; /** * 作者:Created by 武泓吉 on 2020/4/28. */ public class SortAlgorithm { /** * 冒泡排序 从小到大 */ public int[] bubbleSort(int[] a){ for (int i=0;i<a.length-1;i++) { for (int j=0;j<a.length-1-i;j++) { if (a[j]>a[j+1]) { int tem=a[j]; a[j]=a[j+1]; a[j+1]=tem; } } } return a; } }
package org.chail.orc.output; import org.chail.orc.OrcField; import org.chail.orc.utils.OrcUtils; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaFactory; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.*; import java.util.List; /** * @author yangc */ public class OrcOutput extends BaseStep implements StepInterface { String filePath = ""; MyOrcRecordWriter writer = null; private OrcOutputMeta meta; private OrcUtils hdfsUtils = null; private RowMetaInterface rowMeta; public OrcOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } @Override public boolean init(StepMetaInterface smi, StepDataInterface sdi) { try { meta = (OrcOutputMeta) smi; filePath = meta.getFilePath(); init(); } catch (Exception e) { logError("初始化错误,字段信息为空",e); return false; } return super.init(smi, sdi); } @Override public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { Object[] currentRow = getRow(); if (currentRow == null) { setOutputDone(); return false; } try { if (first) { logBasic("ORC-OUT START:" + filePath); rowMeta = getRowMeta(meta.getSchemaList()); first = false; } RowMetaAndData row = new RowMetaAndData(rowMeta, currentRow); writer.write(row); putRow(rowMeta, row.getData()); } catch (Exception e) { logError("error", e); setErrors(1); stopAll(); return false; } return true; } public void init() throws Exception { if (filePath == null) { throw new KettleException("No output files defined"); } hdfsUtils = new OrcUtils(filePath); MyOrcOutputFormat data = new MyOrcOutputFormat(hdfsUtils, filePath); data.setTDHOrc(meta.isTDHOrc()); data.deleteOutFile(filePath, true); data.setCompression(meta.getCompression()); writer = data.createRecordWriter(meta.getSchemaList(),meta.getUserMetadata()); } /** * 获取元数据 * * @param orcOutputField * @return * @throws Exception */ private RowMetaInterface getRowMeta(List<OrcField> orcOutputField) throws Exception { List<OrcField> refiled=!meta.isTDHOrc() ? orcOutputField : TDHOrcFileds.createOrcOutputField(orcOutputField); RowMetaInterface outputRMI = new RowMeta(); RowMetaInterface rowMetaInterface = getInputRowMeta().clone(); for (int i = 0; i < refiled.size(); i++) { int inputRowIndex = rowMetaInterface.indexOfValue(refiled.get(i).getPentahoFieldName()); if (inputRowIndex == -1) { throw new KettleException("Field name [" + refiled.get(i).getPentahoFieldName() + " ] couldn't be found in the input stream!"); } else { ValueMetaInterface vmi = ValueMetaFactory .cloneValueMeta(getInputRowMeta().getValueMeta(inputRowIndex)); outputRMI.addValueMeta(i, vmi); } } return outputRMI; } @Override public void dispose(StepMetaInterface smi, StepDataInterface sdi) { try { if (hdfsUtils != null) { hdfsUtils.closeCloseableStream(writer); } } catch (Exception e) { logError("close error!", e); } super.dispose(smi,sdi); } }
package com.sunzequn.sdfs.socket.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * Created by Sloriac on 2016/12/18. * */ public class ServerThread extends Thread { private SockServer sockServer; private ServerSocket serverSocket; public ServerThread(SockServer sockServer, ServerSocket serverSocket) { this.sockServer = sockServer; this.serverSocket = serverSocket; } @Override public void run() { while (true) { try { Socket socket = serverSocket.accept(); new Thread(new SockServerHandler(socket, sockServer)).start(); } catch (IOException e) { e.printStackTrace(); } } } }
package monopoly.model.deck.card; import monopoly.model.board.Board; import monopoly.model.field.Property; import monopoly.model.player.Player; import monopoly.model.player.State; import monopoly.model.player.changer.PlayerChanger; import org.junit.Test; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class ChanceCardTest { @Test public void Effect () { Player player0 = mock(Player.class); Player player1 = mock(Player.class); Player player2 = mock(Player.class); Player player3 = mock(Player.class); PlayerChanger playerChanger = mock(PlayerChanger.class); Board board = mock(Board.class); Property property1 = mock(Property.class); Property property2 = mock(Property.class); Random random = mock(Random.class); when(random.nextInt(anyInt())).thenReturn(6); when(playerChanger.currentPlayer()).thenReturn(player0); when(playerChanger.getPlayer(0)).thenReturn(player0); when(playerChanger.getPlayer(1)).thenReturn(player1); when(playerChanger.getPlayer(2)).thenReturn(player2); when(playerChanger.getPlayer(3)).thenReturn(player3); when(player0.getMoney()).thenReturn(100); when(player1.getMoney()).thenReturn(100); when(player2.getMoney()).thenReturn(100); when(player3.getMoney()).thenReturn(100); when(player0.getState()).thenReturn(State.InGame); when(player1.getState()).thenReturn(State.InGame); when(player2.getState()).thenReturn(State.InGame); when(player3.getState()).thenReturn(State.InGame); when(player0.getPosition()).thenReturn(10); when(player1.getPosition()).thenReturn(20); when(player2.getPosition()).thenReturn(30); when(player3.getPosition()).thenReturn(40); when(player3.getName()).thenReturn("TestPlayer"); when(property1.getOwner()).thenReturn(player0); when(board.getFieldAt(25)).thenReturn(property1); when(property2.getOwner()).thenReturn(player3); when(board.getFieldAt(12)).thenReturn(property2); ChanceCard chanceCard = new ChanceCard(1, playerChanger, board, random); chanceCard.Effect(); verify(player0, times(1)).setPosition(0); verify(player0, times(1)).increaseMoney(200); assertEquals("Advance to Start!", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player2); when(playerChanger.currentPlayerIndex()).thenReturn(2); chanceCard = new ChanceCard(2, playerChanger, board, random); chanceCard.Effect(); verify(player2, times(1)).setPosition(24); verify(player2, times(1)).increaseMoney(200); assertEquals("Advance to Illinois Ave.", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player3); when(playerChanger.currentPlayerIndex()).thenReturn(3); chanceCard = new ChanceCard(3, playerChanger, board, random); chanceCard.Effect(); verify(player3, times(1)).setPosition(12); assertEquals("Advance token to nearest Utility. If unowned, you may buy it from the Bank. If owned, throw dice and pay owner a total ten times the amount thrown.", chanceCard.getText()); when(playerChanger.currentPlayer()).thenReturn(player2); when(playerChanger.currentPlayerIndex()).thenReturn(2); chanceCard = new ChanceCard(3, playerChanger, board, random); chanceCard.Effect(); verify(player2, times(1)).setPosition(12); verify(player3, times(1)).increaseMoney(anyInt()); verify(player2, times(1)).reduceMoney(anyInt()); assertEquals("Advance token to nearest Utility. If unowned, you may buy it from the Bank. If owned, throw dice and pay owner a total ten times the amount thrown.The Electric Company is owned and you rolled 7. You pay 70$ to TestPlayer.", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player1); when(playerChanger.currentPlayerIndex()).thenReturn(1); chanceCard = new ChanceCard(4, playerChanger, board, random); chanceCard.Effect(); verify(player1, times(1)).setPosition(25); assertEquals("Advance token to the nearest Railroad and pay owner twice the rental to which he/she {he} is otherwise entitled. If Railroad is unowned, you may buy it from the Bank.", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player3); when(playerChanger.currentPlayerIndex()).thenReturn(3); chanceCard = new ChanceCard(6, playerChanger, board, random); chanceCard.Effect(); verify(player3, times(1)).increaseMoney(50); assertEquals("Bank pays you dividend of $50.", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player0); when(playerChanger.currentPlayerIndex()).thenReturn(0); chanceCard = new ChanceCard(7, playerChanger, board, random); chanceCard.Effect(); verify(player0, times(1)).addFreeFromJailCard(chanceCard); assertEquals("Get out of Jail Free – This card may be kept until needed.", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player1); when(playerChanger.currentPlayerIndex()).thenReturn(1); chanceCard = new ChanceCard(8, playerChanger, board, random); chanceCard.Effect(); verify(player1, times(1)).setPosition(17); assertEquals("Go Back 3 Spaces", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player2); when(playerChanger.currentPlayerIndex()).thenReturn(2); chanceCard = new ChanceCard(9, playerChanger, board, random); chanceCard.Effect(); verify(player2, times(1)).setPosition(-1); verify(player2, times(1)).setState(State.InJail); assertEquals("Go directly to Jail – Do not pass Go, do not collect $200", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player3); when(playerChanger.currentPlayerIndex()).thenReturn(3); chanceCard = new ChanceCard(10, playerChanger, board, random); chanceCard.Effect(); verify(player3, times(1)).reduceMoney(0); assertEquals("Make general repairs on all your property – For each house pay $25 – For each hotel $100", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player0); when(playerChanger.currentPlayerIndex()).thenReturn(0); chanceCard = new ChanceCard(11, playerChanger, board, random); chanceCard.Effect(); verify(player0, times(1)).reduceMoney(15); assertEquals("Pay poor tax of $15", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player0); when(playerChanger.currentPlayerIndex()).thenReturn(0); chanceCard = new ChanceCard(12, playerChanger, board, random); chanceCard.Effect(); verify(player0, times(1)).setPosition(5); verify(player0, times(2)).increaseMoney(200); assertEquals("Take a trip to Reading Railroad", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player3); when(playerChanger.currentPlayerIndex()).thenReturn(3); chanceCard = new ChanceCard(13, playerChanger, board, random); chanceCard.Effect(); verify(player3, times(1)).setPosition(39); verify(player3, times(1)).increaseMoney(200); assertEquals("Take a walk on the Boardwalk", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player1); when(playerChanger.currentPlayerIndex()).thenReturn(1); chanceCard = new ChanceCard(14, playerChanger, board, random); chanceCard.Effect(); verify(player1, times(3)).reduceMoney(50); verify(playerChanger, times(1)).increasePlayerMoney(0, 50); verify(playerChanger, times(1)).increasePlayerMoney(2, 50); verify(playerChanger, times(1)).increasePlayerMoney(3, 50); assertEquals("You have been elected Chairman of the Board – Pay each player $50", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player2); when(playerChanger.currentPlayerIndex()).thenReturn(2); chanceCard = new ChanceCard(15, playerChanger, board, random); chanceCard.Effect(); verify(player2, times(1)).increaseMoney(150); assertEquals("Your building loan matures – Collect $150", chanceCard.getText()); //---------------------------------------------------------------------- when(playerChanger.currentPlayer()).thenReturn(player3); when(playerChanger.currentPlayerIndex()).thenReturn(3); chanceCard = new ChanceCard(16, playerChanger, board, random); chanceCard.Effect(); verify(player3, times(1)).increaseMoney(100); assertEquals("You have won a crossword competition - Collect $100", chanceCard.getText()); } }
package com.thatman.testservice.service.impl; import com.thatman.testservice.Entity.User; import com.thatman.testservice.client.TestServiceTwoClient; import com.thatman.testservice.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TestServiceImpl implements TestService { @Autowired TestServiceTwoClient testServiceTwoClient; @Override public User getUser() { User user=new User(); System.out.println("------------------->>"+user.getUserName()); System.out.println("------------------->>"+user.getUserPassword()); return testServiceTwoClient.getUser(); } }
package com.tencent.mm.plugin.messenger.foundation.a.a; import com.tencent.mm.storage.ar; public interface c { ar Gx(String str); boolean m(long j, String str); }
package com.phplogin.sidag.myapplication; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by Siddhant on 10/26/2015. */ public class TimeStamp { int year; int month; int day; int time; public TimeStamp(String timestamp){ String[] date_time = timestamp.split(" "); String[] date = date_time[0].split("-"); this.year = Integer.parseInt(date[0]); this.month = Integer.parseInt(date[1]); this.day = Integer.parseInt(date[2]); String[] tim = date_time[1].split(":"); this.time = Integer.parseInt(tim[0])*60*60 + Integer.parseInt(tim[1])*60 + Integer.parseInt(tim[2]); } public boolean newerThan(TimeStamp time_stamp){ return getTotalSeconds() >= time_stamp.getTotalSeconds(); } public int getTotalSeconds(){ return year*365*24*60*60 + month*30*24*60*60 + day*24*60*60; } public String toString(){ int hour = time/3600; int minute = time%3600/60; int seconds = time%3600%60; return Integer.toString(year) + "-" + Integer.toString(month) + "-" + Integer.toString(day) + " " + Integer.toString(hour) + ":" + Integer.toString(minute) + ":" + Integer.toString(seconds); } public void updateTimestamp(){ Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); String timestamp = sdf.format(c.getTime()); String[] date_time = timestamp.split(" "); String[] date = date_time[0].split("-"); this.year = Integer.parseInt(date[0]); this.month = Integer.parseInt(date[1]); this.day = Integer.parseInt(date[2]); String[] tim = date_time[1].split(":"); this.time = Integer.parseInt(tim[0])*60*60 + Integer.parseInt(tim[1])*60 + Integer.parseInt(tim[2]); } }
package com.tencent.mm.plugin.game.wepkg.utils; import com.tencent.mm.g.a.ou; import com.tencent.mm.kernel.g; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; class c$1 extends c<ou> { final /* synthetic */ c kgq; c$1(c cVar) { this.kgq = cVar; this.sFo = ou.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { x.i("MicroMsg.Wepkg.WepkgListener", "sendEntranceStateListener isInFindEntrance:%b", new Object[]{Boolean.valueOf(((ou) bVar).bZO.bQt)}); if (((ou) bVar).bZO.bQt && bi.bG(Long.valueOf(bi.c((Long) g.Ei().DT().get(a.sXS, Long.valueOf(0)))).longValue()) > 60) { g.Ei().DT().a(a.sXS, Long.valueOf(bi.VE())); c.a(this.kgq, 2); } return false; } }
package codex.presentation; import codex.component.editor.GeneralEditor; import codex.component.render.GeneralRenderer; import codex.editor.IEditor; import codex.type.Bool; import codex.type.IComplexType; import javax.swing.*; import javax.swing.table.TableModel; import java.awt.*; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Виджет таблицы селекторов (презентации и диалога). */ public final class SelectorTable extends JTable implements IEditableTable { private final List<String> editableProps = new LinkedList<>(); public SelectorTable(TableModel model) { super(model); setRowHeight(IEditor.FONT_VALUE.getSize() * 2); setShowVerticalLines(false); setIntercellSpacing(new Dimension(0,0)); setPreferredScrollableViewportSize(new Dimension(getPreferredSize().width, 200)); setFillsViewportHeight(true); getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "none"); GeneralRenderer renderer = new GeneralRenderer<>(); setDefaultRenderer(Bool.class, renderer); setDefaultRenderer(IComplexType.class, renderer); getTableHeader().setDefaultRenderer(renderer); setDefaultEditor(Bool.class, new GeneralEditor()); setDefaultEditor(IComplexType.class, new GeneralEditor()); } @Override public void setPropertiesEditable(String... propNames) { if (propNames != null) { editableProps.addAll(Arrays.asList(propNames)); } } @Override public void setPropertyEditable(String propName) { editableProps.add(propName); } @Override public boolean isCellEditable(int row, int column) { if (getModel() instanceof ISelectorTableModel) { return editableProps.contains(((ISelectorTableModel) getModel()).getPropertyForColumn(column)); } else { return false; } } }
package com.bierocratie.model.accounting; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * Created with IntelliJ IDEA. * User: pir * Date: 23/10/14 * Time: 12:43 * To change this template use File | Settings | File Templates. */ @Entity @Table(name = "category") public class Category implements Serializable { /** * */ private static final long serialVersionUID = -3768194549364378014L; @Id @GeneratedValue private Long id; @NotNull private String name = "-"; private double percentageDueByTheCompany = 1; private Tva defaultTva; public Category() { } public Category(String name, Tva tva) { this.name = name; this.defaultTva = tva; } public Category(Tva tva) { this.defaultTva = tva; } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Category)) return false; Category category = (Category) o; if (!name.equals(category.name)) return false; return true; } @Override public int hashCode() { return name.hashCode(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPercentageDueByTheCompany() { return percentageDueByTheCompany; } public void setPercentageDueByTheCompany(double percentageDueByTheCompany) { this.percentageDueByTheCompany = percentageDueByTheCompany; } public Tva getDefaultTva() { return defaultTva; } public void setDefaultTva(Tva defaultTva) { this.defaultTva = defaultTva; } }
/** * * Question - Next Number * Created by Yu Zheng on 10/1/2015 * * idea: just check the next number one by one, if the number of 1 for this number * is equal to the original number, print it out. * */ public class Solution04 { // compute the number of 1 public static int count_one(int x){ int cnt = 0; for(int i=0; i<32; ++i){ if(x & 1) ++cnt; x >>= 1; } return cnt; } // get the next smallest public int getnext(int x) { int max_ini = ~(1 << 31); int num = count_one(x); if(num == 0 || x == -1) return -1; while(true) { x++; if(count_one(x) != num && x < max_ini) break; } if(count_one(x) == num) return x; return -1; } // get the previous largest public int getpre(int x) { int min_ini = 1 << 31; int num = count_one(x); if(num == 0 || x == -1) return -1; while(true) { x--; if (count_one(x) != num && x > min_ini) break; } if(count_one(x) == num) return x; return -1; } }
package com.example.bottomnav; import android.os.Parcel; import android.os.Parcelable; public class SmurfsModel implements Parcelable { private String name; private String summary; private int photo; public SmurfsModel(){} protected SmurfsModel(Parcel in){ name = in.readString(); summary = in.readString(); photo = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(summary); dest.writeInt(photo); } @Override public int describeContents() { return 0; } public static final Creator<SmurfsModel> CREATOR = new Creator<SmurfsModel>() { @Override public SmurfsModel createFromParcel(Parcel in) { return new SmurfsModel(in); } @Override public SmurfsModel[] newArray(int size) { return new SmurfsModel[size]; } }; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public int getPhoto() { return photo; } public void setPhoto(int photo) { this.photo = photo; } }
package com.vietmedia365.voaapp.db; /** * Created by pat109 on 11/15/2014. */ public class DBUtils { }
package com.zznode.opentnms.isearch.routeAlgorithm.utils; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; public class PropertiesHander { private static PropertiesConfiguration configuration = null; private static final String CONFIG_FILE = "ors-switch.properties"; private PropertiesHander() {} private static PropertiesConfiguration getIntance() { if (configuration == null) { try { configuration = new PropertiesConfiguration(CONFIG_FILE); } catch (ConfigurationException e) { e.printStackTrace(); } FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); // 文件自动重加载延时设置为30秒,只有当文件修改之后才会重新加载(根据文件最后修改时间判断) strategy.setRefreshDelay(30000); configuration.setReloadingStrategy(strategy); configuration.isAutoSave(); } return configuration; } public static String getProperty(String propertyName, String defaultValue) { return getIntance().getString(propertyName, defaultValue); } public static String getProperty(String propertyName) { return getIntance().getString(propertyName); } public static void setProperty(String propertyName,String value) throws ConfigurationException { getIntance().setProperty(propertyName, value); configuration.save(); } public static String[] getPropertylist(String propertyName) { return getIntance().getStringArray(propertyName); } }
package com.beiyelin.sms.service.impl; import com.beiyelin.commonsql.jpa.BaseDomainCRUDServiceImpl; import com.beiyelin.sms.entity.SmsLog; import com.beiyelin.sms.service.SmsLogService; import org.springframework.stereotype.Service; /** * @Description: * @Author: newmann * @Date: Created in 22:35 2018-02-11 */ @Service("smsLogService") public class SmsLogServiceImpl extends BaseDomainCRUDServiceImpl<SmsLog> implements SmsLogService { }
package thsst.calvis.configuration.model.engine; import thsst.calvis.configuration.controller.HandleConfigFunctions; import thsst.calvis.configuration.model.errorlogging.ErrorLogger; import thsst.calvis.configuration.model.errorlogging.ErrorMessage; import thsst.calvis.configuration.model.errorlogging.ErrorMessageList; import thsst.calvis.configuration.model.errorlogging.Types; import thsst.calvis.configuration.model.exceptions.DataTypeMismatchException; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.*; public class RegisterList { public static final int NAME = 0; public static final int SOURCE = 1; public static final int SIZE = 2; public static final int TYPE = 3; public static final int START = 4; public static final int END = 5; public static String instructionPointerName = "EIP"; public static int instructionPointerSize = 32; public static String stackPointerName = "ESP"; public static int stackPointerSize = 32; public static int MAX_SIZE = 32; //default is 32 bit registers private TreeMap<String, Register> map; private ArrayList<String[]> lookup; private EFlags flags; private Mxscr mxscr; private X87Handler x87; private ErrorLogger errorLogger = new ErrorLogger(new ArrayList<>()); private TreeMap<String, TreeMap<String, Register> > childMap; public RegisterList(String csvFile, int maxSize) { Comparator<String> orderedComparator = (s1, s2) -> Integer.compare(indexOf(s1), indexOf(s2)); this.map = new TreeMap<>(orderedComparator); this.lookup = new ArrayList<>(); MAX_SIZE = maxSize; this.childMap = new TreeMap<>(orderedComparator); this.flags = new EFlags(); this.mxscr = new Mxscr(); this.x87 = new X87Handler(this); BufferedReader br = null; String line = ""; int lineCounter = 0; ArrayList<String[]> lookUpCopy = new ArrayList<>(); ArrayList<ErrorMessage> errorMessages = new ArrayList<>(); try { br = new BufferedReader(new FileReader(csvFile)); while ( (line = br.readLine()) != null ) { boolean isSkipped = false; String[] reg = HandleConfigFunctions.split(line, ','); for ( int i = 0; i < reg.length; i++ ) { reg[i] = reg[i].trim(); } lookUpCopy.add(reg); ArrayList<String> missingParametersRegister = HandleConfigFunctions.checkIfMissing(reg); ArrayList<String> invalidParametersRegister = HandleConfigFunctions.checkForInvalidInput(reg); if ( missingParametersRegister.size() > 0 ) { isSkipped = true; errorMessages.add(new ErrorMessage( Types.registerShouldNotBeEmpty, missingParametersRegister, Integer.toString(lineCounter))); } if ( invalidParametersRegister.size() > 0 && lineCounter != 0 ) { isSkipped = true; errorMessages.add(new ErrorMessage( Types.registerShouldNotBeInvalid, invalidParametersRegister, Integer.toString(lineCounter))); } // we need to get the max register size listed in the csv file if ( !isSkipped ) { int regSize = 0; // don't get the table headers if ( lineCounter != 0 ) { regSize = Integer.parseInt(reg[SIZE]); int startIndex = Integer.parseInt(reg[START]); int endIndex = Integer.parseInt(reg[END]); if ( (startIndex == 0 && endIndex + 1 != regSize) || (startIndex > 0 && endIndex - startIndex + 1 != regSize) ) { errorMessages.add(new ErrorMessage( Types.registerInvalidSizeFormat, HandleConfigFunctions.generateArrayListString(reg[NAME]), Integer.toString(lineCounter))); // reg = HandleConfigFunctions.adjustAnArray(reg, 1); // reg[reg.length - 1] = "0"; } endIndex = ((endIndex + 1) / 4) - 1; startIndex = startIndex / 4; // reverse order of indices int dividedBy = 0; //RegisterList.MAX_SIZE / 4; if ( reg[NAME].equals(reg[SOURCE]) ) { dividedBy = Integer.parseInt(reg[SIZE]) / 4; } else { dividedBy = getBitSize(reg[SOURCE]) / 4; } endIndex = (dividedBy - 1) - endIndex; startIndex = (dividedBy - 1) - startIndex; reg[START] = String.valueOf(endIndex); reg[END] = String.valueOf(startIndex); reg[NAME] = reg[NAME].toUpperCase(); // add csv row to lookup table // + " " + reg[3] + " " + reg[4] + " " + reg[5]); this.lookup.add(reg); } // if a register is the source register itself if ( reg[NAME].equals(reg[SOURCE]) ) { switch ( reg[TYPE] ) { case "1": // fall through case "2": // fall through case "4": // fall through case "6": // fall through Register g = new Register(reg[NAME], regSize); this.map.put(reg[NAME], g); break; case "5": FpuRegister st0 = new FpuRegister(reg[NAME], 0); this.map.put(reg[NAME], st0); break; case "7": X87Register fpu = null; if ( reg[NAME].equals("STATUS") ) { fpu = new X87StatusRegister(); this.x87.setStatus((X87StatusRegister) fpu); } else if ( reg[NAME].equals("TAG") ) { fpu = new X87TagRegister(); this.x87.setTag((X87TagRegister) fpu); } else if ( reg[NAME].equals("CONTROL") ) { fpu = new X87ControlRegister(); this.x87.setControl((X87ControlRegister) fpu); } this.map.put(reg[NAME], fpu); break; case "3": // Instruction Pointer Register h = new Register(reg[NAME], regSize); instructionPointerName = reg[NAME]; instructionPointerSize = regSize; this.map.put(reg[NAME], h); break; case "8": // Stack Pointer StackPointerRegister spr = new StackPointerRegister(reg[NAME], regSize); stackPointerName = reg[NAME]; stackPointerSize = regSize; this.map.put(reg[NAME], spr); break; default: errorMessages.add( new ErrorMessage(Types.invalidRegister, HandleConfigFunctions.generateArrayListString(reg[TYPE]), Integer.toString(lineCounter + 1))); break; } } else { Register baby; switch ( reg[TYPE] ) { case "3": // Instruction Pointer baby = new Register(reg[NAME], regSize); break; case "8": // Stack Pointer baby = new StackPointerRegister(reg[NAME], regSize); break; default: baby = new Register(reg[NAME], regSize); } if ( childMap.get(reg[SOURCE]) == null ) { TreeMap<String, Register> group = new TreeMap<>(orderedComparator); group.put(reg[NAME], baby); this.childMap.put(reg[SOURCE], group); } else { TreeMap<String, Register> group = childMap.get(reg[SOURCE]); group.put(reg[NAME], baby); this.childMap.replace(reg[SOURCE], group); } } } lineCounter++; } lookUpCopy.remove(0); // should check for register thsst.calvis.configuration errors... int index = 0; for ( String[] lookupEntry : lookUpCopy ) { // if all source (mother) registers are existent if ( !this.map.containsKey(lookupEntry[1]) ) { // int lineNumber = index; // if(isEmptyError) // lineNumber = index + 1; errorMessages.add(new ErrorMessage( Types.doesNotExist, HandleConfigFunctions.generateArrayListString(lookupEntry[1]), Integer.toString(index + 1))); } index++; } // this.setRegisterContent(); // put value into the Register Map } catch ( Exception e ) { e.printStackTrace(); } finally { if ( br != null ) { try { br.close(); } catch ( IOException e ) { e.printStackTrace(); } } } ErrorMessageList registerErrorList = new ErrorMessageList(Types.registerFile, errorMessages); errorLogger.add(registerErrorList); } public Iterator<String[]> getRegisterList() { return this.lookup.iterator(); } public ArrayList<String[]> getRegisterLookup() { return this.lookup; } public Iterator<String> getRegisterKeys() { List registerKeys = new ArrayList<>(); Iterator<String[]> iterator = getRegisterList(); while ( iterator.hasNext() ) { String regName = iterator.next()[0]; registerKeys.add(regName); } return registerKeys.iterator(); } public EFlags getEFlags() { return this.flags; } public Mxscr getMxscr() { return this.mxscr; } public boolean isExisting(String registerName) { return (find(registerName) != null); } public int getBitSize(String registerName) { return getBitSize(new Token(Token.REG, registerName)); } public int getBitSize(Token a) { String key = a.getValue(); String size; size = find(key)[SIZE]; return Integer.parseInt(size); } public int getHexSize(String registerName) { return getBitSize(registerName) / 4; } public int getHexSize(Token a) { return getBitSize(a) / 4; } public String get(String registerName) { return get(new Token(Token.REG, registerName)); } public String get(Token a) { ArrayList<ErrorMessage> errorMessages = new ArrayList<>(); // find the mother/source register String key = a.getValue(); String[] register = find(key); // get the mother register if ( isExisting(key) ) { Register mother = this.map.get(register[SOURCE]); int startIndex = Integer.parseInt(register[START]); int endIndex = Integer.parseInt(register[END]); // return the indicated child register value if ( mother.getName().matches("ST[0-7]") ) { return mother.getValue(); } else { return mother.getValue().substring(startIndex, endIndex + 1); } } else { errorMessages.add(new ErrorMessage(Types.doesNotExist, HandleConfigFunctions.generateArrayListString(key), "")); errorLogger.get(0).add(errorMessages); } return null; } public void set(Token registerToken, String hexString) throws DataTypeMismatchException { set(registerToken.getValue(), hexString); } public void set(String key, String hexString) throws DataTypeMismatchException { String[] register = find(key); ArrayList<ErrorMessage> errorMessages = new ArrayList<>(); // get the mother register Register mother = this.map.get(register[SOURCE]); int startIndex = Integer.parseInt(register[START]); int endIndex = Integer.parseInt(register[END]); String sourceName = mother.getName(); if ( sourceName.matches("ST[0-7]") ) { mother.setValue(hexString); this.x87().setStackValue(sourceName.charAt(2) + "", hexString); } else { //check for mismatch between parameter hexString and child register value String child = mother.getValue().substring(startIndex, endIndex + 1); if ( child.length() >= hexString.length() ) { int differenceInLength = child.length() - hexString.length(); for ( int i = 0; i < differenceInLength; i++ ) { hexString = "0" + hexString; } String newValue = mother.getValue(); char[] val = newValue.toCharArray(); for ( int i = startIndex; i <= endIndex; i++ ) { val[i] = hexString.charAt(i - startIndex); } newValue = new String(val); newValue = newValue.toUpperCase(); mother.setValue(newValue); TreeMap<String, Register> treeMap = childMap.get(register[SOURCE]); if ( treeMap != null ) { for( Map.Entry<String, Register> entry : treeMap.entrySet() ) { String childRegisterName = entry.getKey(); Register value = entry.getValue(); String[] childRegister = find(childRegisterName); int childStartIndex = Integer.parseInt(childRegister[START]); int childEndIndex = Integer.parseInt(childRegister[END]); String newChildValue = mother.getValue().substring(childStartIndex, childEndIndex + 1); value.setValue(newChildValue); } } } else { if ( hexString.equals("") ) { errorMessages.add(new ErrorMessage(Types.writeRegisterFailed, new ArrayList<>(), "")); } else { errorMessages.add(new ErrorMessage(Types.dataTypeMismatch, HandleConfigFunctions.generateArrayListString(register[0], child, hexString), "")); throw new DataTypeMismatchException(register[0] + ":" + child, hexString); } errorLogger.get(0).add(errorMessages); } } } public String getInstructionPointer() { return get(instructionPointerName); } public void setInstructionPointer(String value) throws DataTypeMismatchException { set(instructionPointerName, value); } public String getStackPointer() { String registerStackValue = get(stackPointerName); if(registerStackValue.length() > 8) { return registerStackValue.substring(8); } else{ return registerStackValue; } } public void setStackPointer(String value) throws DataTypeMismatchException { String officialValue = value; set(stackPointerName, officialValue); } public void clear() { for ( String s : this.map.keySet() ) { this.map.get(s).initializeValue(); } flags.initializeValue(); mxscr.initializeValue(); x87.clear(); // initialize childMap for ( String s : this.childMap.keySet() ) { for ( String t : this.childMap.get(s).keySet() ) { this.childMap.get(s).get(t).initializeValue(); } } } public String[] find(String registerName) { for ( String[] x : this.lookup ) { if ( x[0].equalsIgnoreCase(registerName) ) { return x; } } return null; } public int indexOf(String registerName) { for ( int i = 0; i < this.lookup.size(); i++ ) { if ( registerName.equals(this.lookup.get(i)[RegisterList.NAME]) ) { return i; } } return -1; } public Map getRegisterMap() { return this.map; } public Map getChildRegisterMap(String regName) { return this.childMap.get(regName); } public ErrorLogger getErrorLogger() { if ( errorLogger.get(0).getSizeofErrorMessages() == 0 ) { return new ErrorLogger(new ArrayList<>()); } else { return errorLogger; } } public Integer[] getAvailableSizes() { Set<Integer> available = new HashSet<>(); Iterator iterator = getRegisterKeys(); while ( iterator.hasNext() ) { String registerName = (String) iterator.next(); available.add(getBitSize(registerName)); } Integer[] list = new Integer[available.size()]; return available.toArray(list); } public X87Handler x87() { return this.x87; } public void setRegisterContent() { try { set("EAX", "DDBBCCAA"); set("EBX", "FFFF1111"); set("ECX", "00000005"); set("EDX", "56F38E84"); set("ESP", "FF006655"); set("ESI", "00000001"); set("EDI", "88774433"); set("EBP", "00000008"); set("MM0", "FFFF901256781234"); set("MM1", "1234567856781234"); set("MM2", "FFCA90BB58926789"); set("MM3", "9934566711111286"); set("MM4", "0055006600770088"); set("MM5", "111122228888FFFF"); set("MM6", "0000000000000001"); set("MM7", "0000000000000002"); set("XMM0", "ABCEDF123456789000000000123AF43"); set("XMM1", "1234567890ABCDEF123EBDCA0123AF43"); set("XMM2", "11111111111111110000000000000000"); set("XMM3", "1234567890AB90931FFF45210123ABCD"); set("XMM4", "1FFF45210123ABCD1234567890AB9094"); set("XMM5", "1234567845210123123EBDCA0123AF43"); set("XMM6", "ABCDEF01452101230000000045210123"); set("XMM7", "CDEF123E1234567890AB9093CDEF123E"); } catch ( Exception e ) { e.printStackTrace(); } } }
package com.tencent.xweb; import android.content.Context; import com.tencent.xweb.c.b.b; public final class c { private static c vzW; static b vzX; public static synchronized c ij(Context context) { c cVar; synchronized (c.class) { if (vzW == null) { vzW = new c(context.getApplicationContext()); } cVar = vzW; } return cVar; } public static synchronized c cIk() { c cVar; synchronized (c.class) { if (vzW == null) { throw new IllegalStateException("CookieSyncManager::createInstance() needs to be called before CookieSyncManager::getInstance()"); } cVar = vzW; } return cVar; } private c(Context context) { if (vzX != null) { vzX.init(context); } } public static void sync() { if (vzX != null) { vzX.sync(); } } }
package collection.visualizer.layout.nodes; import bus.uigen.shapes.ALineModel; import bus.uigen.shapes.Shape; public class ALinearRoot extends AnAbstractLinearElement implements LinearElement { public ALinearRoot(Shape _s, Object _o, ALineModel _l, ALineModel _l2) { super(_s, _o, _l, _l2); } public void focusPosition(){ focusPosition(this); } @Override public void focusPosition(LinearElement node) { super.focusPosition(node); if (node.getVector().size() > 0) { super.positionVerticalLine(this); } } }
package com.cms.common.utils; /** * @author lansb 静态环境变量 */ public class Environment { public static final String ADMIN_USER_CODE = "admin";//开发专用账号 public static final String LOGIN_NO_PRIV = "-100";//登录后可访问 public static final String ADMIN_PRIV = "-200";//admin专属权限,开发组专用 public static final String NO_PRIV = "-300";//无需登录即可反问,比如LED public static final String ENCODING = "UTF-8"; public static final String URL_SQL_MAP = "SYS_URL_SQL_VIEW"; public static final String SESSION_USER_LOGIN_INFO = "SESSION_USER_LOGIN_INFO";//登录信息 public static final String CTRL_NUMPERPAGE = "numPerPage";//每页数量 public static final String DEFAULT_NUMPERPAGE = "20";//默认每页数量 public static final String CTRL_PAGENUM = "pageNum";//当前页数 public static final String DEFAULT_PAGENUM = "1"; public static final String CTRL_QUERYCOUNT = "query_count"; public static final String CTRL_PAGESTART = "page_start"; public static final String CTRL_PAGEEND = "page_end"; public static final String CTRL_PAGENUMSHOWN = "pageNumShown"; public static final String DEFAULT_PAGENUMSHOWN = "20"; public static final String LOGIN_INFO = "LOGIN_INFO_OBJECT"; public static final String QUERY_SESSFUL = "查询成功"; public static final String SAVE_SESSFUL = "操作成功"; public static final String SAVE_FAULAIE = "操作失败"; public static final String LOAD_SESSFUL = "加载成功"; public static final String DEL_SESSFUL = "删除成功"; public static final String USER_CODE = "$_CRU_USER_CODE_$";//租户ID public static final String UUID = "$_UUID_$";//UUID public static final String USER_NAME = "$_CRU_USER_NAME_$";//用户账号 public static final String USER_ID = "$_CRU_USER_ID_$";//用户ID public static final String REAL_NAME = "$_CRU_REAL_NAME_$";//用户ID public static final String FILE_FILE_INPUTNAME = "_FILE_"; public static final String FILE_FILENAME = "_UP_FILE_NAME_"; public static final String FILE_ATT_ID = "_ATT_ID_"; public static final String FILE_ATT_IS_DEL = "_ATT_IS_DEL_"; public static final String PUBLIC_SYS_CODE_MARK="base";//公用url标识 /** * 图片保存路径 */ public final static String IMAGE_SAVE_PATH="pic"; /** * 全国的区域编码 */ public static final String ALL_AREA_CODE = "D000000"; /** * 默认密码 */ public static final String DEFALUT_PWD="123456"; }
package com.tinnova.exercicio3; public class CalculoFatorial { private CalculoFatorial() { // não instanciar } /** * Método para calcular o fatorial * * @param Long fatorial * @return Long fatorial */ public static Long calculoFatorial(Long fatorial) { Long numeroInicial = 1L; for (int i = 1; i <= fatorial ; i++) { numeroInicial *= i; } return numeroInicial; } }
package fonepay.task.ODSBE.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import java.util.Arrays; @Configuration public class CORSConfig { @Bean CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // setAllowCredentials(true) is important, otherwise: // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. configuration.setAllowCredentials(true); // setAllowedHeaders is important! Without it, OPTIONS preflight request // will fail with 403 Invalid CORS request configuration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type", "Accept", "Authorization", "Origin, Accept", "X-Requested-With", "Access-Control-Request-Origin", "Access-Control-Request-Headers")); configuration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Access-Control-Allow-Credentials")); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
package com.dishcuss.foodie.hub.Models; import io.realm.RealmObject; /** * Created by Naeem Ibrahim on 8/4/2016. */ public class FoodsCategory extends RealmObject { int id; String categoryName; public FoodsCategory() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } }
package littleservantmod.api.profession.behavior; import littleservantmod.api.IServant; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.translation.I18n; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public abstract class BehaviorBase implements IBehavior { @SideOnly(Side.CLIENT) protected TextureAtlasSprite icon; protected ResourceLocation resourceLocation; protected String unlocalizedName; @Override public void initAI(IServant servant) { } @SideOnly(Side.CLIENT) public BehaviorBase setIcon(TextureAtlasSprite icon) { this.icon = icon; return this; } @Override @SideOnly(Side.CLIENT) public TextureAtlasSprite getIcon(IServant servant) { if (icon == null) { //Missing return net.minecraft.client.Minecraft.getMinecraft().getTextureMapBlocks().getMissingSprite(); } return icon; } public BehaviorBase setUnlocalizedName(String unlocalizedName) { this.unlocalizedName = unlocalizedName; return this; } public String getUnlocalizedName() { return "behavior." + this.unlocalizedName; } public String getUnlocalizedName(IServant servant) { return "behavior." + this.unlocalizedName; } @Override public String getBehaviorDisplayName(IServant servant) { return I18n.translateToLocal(this.getUnlocalizedName(servant) + ".name").trim(); } @Override public ResourceLocation getRegistryName() { return this.resourceLocation; } public BehaviorBase setRegistryName(ResourceLocation resourceLocation) { this.resourceLocation = resourceLocation; return this; } @Override public void startBehavior(IServant servant) { }; }
package com.werth; import java.io.*; import java.util.*; // Suppose we have some input data describing a graph of relationships between parents and children over multiple generations. The data is formatted as a list of (parent, child) pairs, where each individual is assigned a unique positive integer identifier. // // For example, in this diagram, 3 is a child of 1 and 2, and 5 is a child of 4: // // 1 2 4 15 // \ / / | \ / // 3 5 8 9 // \ / \ \ // 6 7 11 // // // Sample input/output (pseudodata): // // parentChildPairs = [ // (1, 3), (2, 3), (3, 6), (5, 6), (15, 9), // (5, 7), (4, 5), (4, 8), (4, 9), (9, 11) // ] // // // Write a function that takes this data as input and returns two collections: one containing all individuals with zero known parents, and one containing all individuals with exactly one known parent. // // // Output may be in any order: // // findNodesWithZeroAndOneParents(parentChildPairs) => [ // [1, 2, 4, 15], // Individuals with zero parents // [5, 7, 8, 11] // Individuals with exactly one parent // ] // // n: number of pairs in the input // taking in 2d array // always a parent as first elements, child as second elements // if they have a parent they will appear as second elements // return 2d array of [ [no parents], [parents] ] // map[3]: [1,2] [6]: [3, 5] [9]: [15, 4] if key, they have a parent // ArrayList parents = [2nd Elements] // ArrayList noparents = [1st Elements] remove any values that are in the second from 1st array // map[ele] = 1 // for loop // int ele1, int ele2 // { 3: [1, 2] , 6: [3] } public class ParentsChildren { public static void main(String[] argv) { int[][] parentChildPairs = new int[][] { {1, 3}, {2, 3}, {3, 6}, {5, 6}, {15, 9}, {5, 7}, {4, 5}, {4, 8}, {4, 9}, {9, 11} }; nodeWithAndWithoutParents(parentChildPairs); } public static int[][] nodeWithAndWithoutParents(int[][] pairs) { List<Integer> parents = new ArrayList<>(); List<Integer> noParents = new ArrayList<>(); for(int i = 0; i < pairs.length; i++) { noParents.add(pairs[i][0]); parents.add(pairs[i][1]); } for(int i = 0; i < parents.size(); i++) { if(noParents.contains(parents.get(i))) { noParents.remove(i); } } System.out.println(parents); System.out.println(noParents); return null; } }
package reporting; import java.util.UUID; import java.util.ArrayList; import shipping.ShippingService; /** * The Class ReportingSystem. class used to create different reports based on data stored at shipping Service side */ public abstract class ReportingSystem { /** The shipping services used. */ ArrayList<ShippingService> services; /** * Gets the services. * * @return the services */ public ArrayList<ShippingService> getServices() { return services; } /** * Sets the services. * * @param services the new services */ public void setServices(ArrayList<ShippingService> services) { this.services = services; } /** * Gets the report appropriate for the retailer with ID retailer ID. * * @param retailerId the retailer id * the report will be displayed to the user. * */ public abstract void getReport(UUID retailerId); }
import java.awt.Point; import java.util.ArrayList; import java.util.List; public interface ConvexHullAlgorithm { List<GeoRef> execute(List<GeoRef> points); }
package com.ytt.springcoredemo.dao.mapper.base; import com.ytt.springcoredemo.dao.mapper.core.CoreMapper; import com.ytt.springcoredemo.model.po.User; import org.apache.ibatis.annotations.Mapper; /** * @Author: aaron * @Descriotion: * @Date: 22:38 2019/7/27 * @Modiflid By: */ //@Mapper public interface UserMapper extends CoreMapper<User,Long> { }
package testdata; public class ConfigData { public static String ENVIRONMENT="CLOUD"; public static String url="https://mingletrial06-portal.mingledev.infor.com/AUTOMOBQA_TST"; public static String PASSWORD="Password1!"; public static String USER1="mingleqatest11@gmail.com"; public static String USER2="mingleqatest12@gmail.com"; public static String USER3="mingleqatest15@gmail.com"; public static String USER4="mingleqatest16@gmail.com"; public static String srchuser1="test11"; public static String srchuser2="test12"; public static String srchuser3="test15"; public static String taguser="QAAuto Test12"; public static String taguser1="QAAuto Test11"; //:::::::::::CloudQRCode:::::::::::::: /*public static String Addprofile="Add Profile"; public static String Txt_ProfileName="Android_Cloud"; public static String Txt_ClientID="AUTODEMOQA1_TST~ilztbCn8TQBrg2AkUuRtv45HJXjsr3BKuFPO0fHt0ds"; public static String Txt_ClientSecret="LAeUcQ9AcTDQQbBMt2DyPDKAc6csKWpnTjfhW5eWwZHmh1BGRte54uBFibGK6PHG5QISUFm7lByyuC0CA7p81Q"; public static String Txt_IonApiHostAdress="https://mingletrial10-ionapi.mingledev.infor.com"; public static String Txt_SecurityAuthorizationServerAddress="https://mingletrial10-sso.mingledev.infor.com/AUTODEMOQA1_TST/as/"; public static String Txt_AuthorizationEndpoint="authorization.oauth2"; public static String Txt_TokenEndpoint="token.oauth2"; public static String Txt_RevocationEndpoint="revoke_token.oauth2"; public static String Txt_TenantID="AUTODEMOQA1_TST"; public static String Txt_EnvironmentVariable="D1463690483"; public static String scrll_text_testconction="Test Connection";*/ //Trial06: public static String Addprofile="Add Profile"; public static String Txt_ProfileName="Android_Cloud"; public static String Txt_ClientID="AUTOMOBQA_TST~L8IjL1Deuy-8anIHvrYbsZhLM7c2IbZNSSt-0Zq1MSY"; public static String Txt_ClientSecret="L5FrVfa1BSuRawJoAlQ6fIXjU2Pe35xx6AmwDDA6EvXgFu9DkPRHExBORnxKfHmN1ZRt8qSO-GIInSeBA83pZQ"; public static String Txt_IonApiHostAdress="https://mingletrial06-ionapi.mingledev.infor.com"; public static String Txt_SecurityAuthorizationServerAddress="https://mingletrial06-sso.mingledev.infor.com/AUTOMOBQA_TST/as/"; public static String Txt_AuthorizationEndpoint="authorization.oauth2"; public static String Txt_TokenEndpoint="token.oauth2"; public static String Txt_RevocationEndpoint="revoke_token.oauth2"; public static String Txt_TenantID="AUTOMOBQA_TST"; public static String Txt_EnvironmentVariable="Y1447454991"; public static String scrll_text_testconction="Test Connection"; }
package com.project.database.controller; import com.project.database.dto.bigunets.BigunetsReport; import com.project.database.dto.bigunets.info.BigunetsInfo; import com.project.database.dto.bigunets.shortInfo.BigunetsShortInfo; import com.project.database.exception.StatementNotExist; import com.project.database.serviceHibernate.BigunetsServiceH; import com.project.database.serviceHibernate.ParserServiceH; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; @RestController @RequestMapping("/api") @RequiredArgsConstructor public class BigunetsController { private final BigunetsServiceH bigunetsService; private final ParserServiceH parserService; @GetMapping("/biguntsi") public Page<BigunetsShortInfo> getAll( @RequestParam(name = "subjectName", required = false) String subjectName, @RequestParam(name = "tutorName", required = false) String tutorName, @RequestParam(name = "group", required = false) String groupName, @RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "numberPerPage", defaultValue = "20") int numberPerPage ) { return bigunetsService.findAllBiguntsy( tutorName, subjectName, groupName, page, numberPerPage); } @GetMapping("/bigunets/{id}") public ResponseEntity<BigunetsInfo> getStatementInfo(@PathVariable("id") int id) { try { return ResponseEntity.ok(bigunetsService.findBigunetsById(id)); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } } @PostMapping("/bigunets/process") public ResponseEntity<BigunetsReport> processStatementFile( @RequestParam("file") MultipartFile file ) { BigunetsReport bigunetsReport; try { bigunetsReport = bigunetsService.processBigunets(file); System.out.println(bigunetsReport); } catch (FileAlreadyExistsException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.CONFLICT).build(); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } return ResponseEntity.ok(bigunetsReport); } @PostMapping("/bigunets/save") public ResponseEntity<Integer> saveBigunets( @RequestBody BigunetsReport bigunetsReport ) { Integer bigunetsId; try { parserService.insertBigunets(bigunetsReport.getBigunetsInfo()); bigunetsId = bigunetsReport.getBigunetsInfo().getBigunetsHeader().getBigunNo(); } catch (StatementNotExist e) { return ResponseEntity.status(HttpStatus.CONFLICT).build(); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } return ResponseEntity.ok(bigunetsId); } }
package jbyco.optimization.jump; import jbyco.lib.Utils; import jbyco.optimization.Statistics; import jbyco.optimization.common.ActionLoader; import jbyco.optimization.common.MethodTransformer; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TableSwitchInsnNode; import java.util.ArrayList; import java.util.Collection; /** * An transformer to load and apply the tableswitch actions. */ public class TableSwitchTransformer extends MethodTransformer implements ActionLoader<TableSwitchAction> { Statistics stats; JumpCollector collector; Collection<TableSwitchAction> actions = new ArrayList<>(); public TableSwitchTransformer(MethodTransformer mt, JumpCollector collector, Statistics stats) { super(mt); this.collector = collector; this.stats = stats; } public void loadActions(Class<?> ...libraries) { for (TableSwitchAction action : Utils.loadInstancesFromLibraries(TableSwitchAction.class, libraries)) { loadAction(action); } } public void loadActions(TableSwitchAction ...actions) { for (TableSwitchAction action : actions) { loadAction(action); } } public void loadAction(TableSwitchAction action) { actions.add(action); } @Override public boolean transform(MethodNode mn) { InsnList list = mn.instructions; boolean change = false; for (TableSwitchInsnNode node : collector.tableSwitches) { for (TableSwitchAction action : actions) { // do action change = action.replace(list, node, collector.addresses); // update statistics if (change && stats != null) { stats.addOptimization(action.getName()); } // stop if (change) { break; } } // stop if (change) { break; } } return change | super.transform(mn); } }
package com.tencent.mm.plugin.fav.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; class FavoriteIndexUI$11 implements OnClickListener { final /* synthetic */ FavoriteIndexUI jbh; FavoriteIndexUI$11(FavoriteIndexUI favoriteIndexUI) { this.jbh = favoriteIndexUI; } public final void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); this.jbh.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS")); } }
package net.minecraft.item; import javax.annotation.Nullable; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityHanging; import net.minecraft.entity.item.EntityItemFrame; import net.minecraft.entity.item.EntityPainting; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ItemHangingEntity extends Item { private final Class<? extends EntityHanging> hangingEntityClass; public ItemHangingEntity(Class<? extends EntityHanging> entityClass) { this.hangingEntityClass = entityClass; setCreativeTab(CreativeTabs.DECORATIONS); } public EnumActionResult onItemUse(EntityPlayer stack, World playerIn, BlockPos worldIn, EnumHand pos, EnumFacing hand, float facing, float hitX, float hitY) { ItemStack itemstack = stack.getHeldItem(pos); BlockPos blockpos = worldIn.offset(hand); if (hand != EnumFacing.DOWN && hand != EnumFacing.UP && stack.canPlayerEdit(blockpos, hand, itemstack)) { EntityHanging entityhanging = createEntity(playerIn, blockpos, hand); if (entityhanging != null && entityhanging.onValidSurface()) { if (!playerIn.isRemote) { entityhanging.playPlaceSound(); playerIn.spawnEntityInWorld((Entity)entityhanging); } itemstack.func_190918_g(1); } return EnumActionResult.SUCCESS; } return EnumActionResult.FAIL; } @Nullable private EntityHanging createEntity(World worldIn, BlockPos pos, EnumFacing clickedSide) { if (this.hangingEntityClass == EntityPainting.class) return (EntityHanging)new EntityPainting(worldIn, pos, clickedSide); return (this.hangingEntityClass == EntityItemFrame.class) ? (EntityHanging)new EntityItemFrame(worldIn, pos, clickedSide) : null; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\ItemHangingEntity.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.grability.test.dlmontano.grabilitytest.dao.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.grability.test.dlmontano.grabilitytest.database.GrabilityTestSQLiteHelper; import com.grability.test.dlmontano.grabilitytest.interfaces.AppImageDataSource; import com.grability.test.dlmontano.grabilitytest.model.AppImage; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Diego Montano on 07/06/2016. */ public class AppImageDatabaseSource implements AppImageDataSource { private static String LOG_TAG = "AIDS"; private Context context; private GrabilityTestSQLiteHelper grabilityTestDbHelper; private SQLiteDatabase grabilityDatabase; private static final String databaseName = GrabilityTestSQLiteHelper .getGivenDatabaseName(); private static final String appImagesTableName = GrabilityTestSQLiteHelper .getTableAppImages(); private static final String idColumnName = GrabilityTestSQLiteHelper.getColumnId(); private static final String appIdColumnName = GrabilityTestSQLiteHelper .getColumnAppId(); private static final String labelColumnName = GrabilityTestSQLiteHelper .getColumnLabel(); private static final String heightColumnName = GrabilityTestSQLiteHelper .getColumnHeight(); private static final String imageDataColumnName = GrabilityTestSQLiteHelper .getColumnImageData(); private static final String sourceUrlColumnName = GrabilityTestSQLiteHelper .getColumnSourceUrl(); private String[] allColumns = GrabilityTestSQLiteHelper.getAppImagesTableColumns(); private String[] insertColumns = GrabilityTestSQLiteHelper.getAppImagesTableInsertColumns(); private String[] idColumn = GrabilityTestSQLiteHelper.getTableIdColumn(); public AppImageDatabaseSource(Context context) { Log.d(LOG_TAG, "Creating " + LOG_TAG + " instance."); this.context = context; grabilityTestDbHelper = new GrabilityTestSQLiteHelper(context); } @Override public void open() { Log.i(LOG_TAG + "->open", "Obtaining writeable database."); grabilityDatabase = grabilityTestDbHelper.getWritableDatabase(); Log.d(LOG_TAG + "->open", "Writeable database obtained."); } @Override public void close() { Log.i(LOG_TAG + "->close", "Closing database."); grabilityTestDbHelper.close(); Log.d(LOG_TAG + "->close", "Database closed."); } @Override public String determineDataSourcePath() { Log.i(LOG_TAG + "->dDSP", "Returning database path."); File dbDirectory = new File(context.getFilesDir(), "databases"); String dbPath = null; if (!dbDirectory.isDirectory() && dbDirectory.mkdirs()) { File dbFile = new File(dbDirectory, databaseName); dbPath = dbFile.getAbsolutePath(); } else { File dbFile = new File(dbDirectory, databaseName); dbPath = dbFile.getAbsolutePath(); } Log.d(LOG_TAG + "->dDSP", "Database path: " + dbPath + "."); return dbPath; } @Override public boolean doesSourceContentExist(String sourceContentName, boolean open) { Log.i(LOG_TAG + "->dSCE", "Checking if table exists."); boolean result = false; Cursor cursor = grabilityDatabase.rawQuery( "select DISTINCT tbl_name from sqlite_master where tbl_name = '" + sourceContentName + "'", null); if (cursor != null) { if (cursor.getCount() > 0) { Log.d(LOG_TAG + "->dSCE", "Table exists."); result = true; } cursor.close(); } return result; } @Override public boolean doesDefaultSourceContentExist() { boolean result = false; if (grabilityDatabase != null) { result = doesSourceContentExist(appImagesTableName, grabilityDatabase.isOpen()); } return result; } @Override public boolean defaultSourceContentHasAppImages() { boolean result = false; if (grabilityDatabase != null) { result = sourceContentHasAppImages(appImagesTableName, grabilityDatabase.isOpen()); } return result; } @Override public boolean sourceContentHasAppImages(String sourceContentName, boolean open) { Log.i(LOG_TAG + "->sCHAI", "Checking if table " + sourceContentName + " has AppImages."); boolean result = false; if (getAppImagesCount() > 0) { Log.d(LOG_TAG, "Table " + sourceContentName + " has AppImages."); result = true; } else { Log.d(LOG_TAG, "Table " + sourceContentName + " does not have AppImages."); } return result; } @Override public int getAppImagesCount() { int count = 0; Cursor cursor = grabilityDatabase.query(appImagesTableName, idColumn, null, null, null, null, null); count = cursor.getCount(); cursor.close(); return count; } @Override public Map<Long, AppImage> getAllAppImages() { Log.i(LOG_TAG + "->gAAI", "Getting all AppImages."); Map<Long, AppImage> appImages = new HashMap<Long, AppImage>(); Cursor cursor = grabilityDatabase.query(appImagesTableName, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { AppImage appImage = transformCursorToAppImage(cursor); appImages.put(appImage.getId(), appImage); cursor.moveToNext(); } // make sure to close the cursor cursor.close(); return appImages; } @Override public List<AppImage> getAppImagesByAppId(long appId) { Log.i(LOG_TAG + "->gAIBAI", "Getting AppImages by AppId."); String selection = appIdColumnName + " = ?"; String[] selectionArgs = { "" + appId }; Cursor cursor = grabilityDatabase.query(appImagesTableName, allColumns, selection, selectionArgs, null, null, null); cursor.moveToFirst(); List<AppImage> categories = new ArrayList<AppImage>(); AppImage appImage = null; while (!cursor.isAfterLast()) { appImage = transformCursorToAppImage(cursor); categories.add(appImage); cursor.moveToNext(); } // make sure to close the cursor cursor.close(); return categories; } @Override public boolean addAppImage(AppImage appImage) { Log.i(LOG_TAG + "->aAI", "Adding AppImage."); boolean result = false; ContentValues values = new ContentValues(); values.put(appIdColumnName, appImage.getAppId()); values.put(labelColumnName, appImage.getLabel()); values.put(heightColumnName, appImage.getHeight()); values.put(imageDataColumnName, appImage.getImageData()); values.put(sourceUrlColumnName, appImage.getLabel()); long insertResult = grabilityDatabase.insert(appImagesTableName, null, values); if (insertResult != -1) { Log.d(LOG_TAG + "->aAI", "AppImage added."); result = true; } return result; } @Override public boolean updateAppImage(AppImage appImage) { Log.i(LOG_TAG + "->uAI", "Updating AppImage."); boolean result = false; String[] args = { "" + appImage.getId() }; ContentValues values = new ContentValues(); values.put(appIdColumnName, appImage.getAppId()); values.put(labelColumnName, appImage.getLabel()); values.put(heightColumnName, appImage.getHeight()); values.put(imageDataColumnName, appImage.getImageData()); values.put(sourceUrlColumnName, appImage.getLabel()); long updateResult = grabilityDatabase.update(appImagesTableName, values, idColumnName + " = ?", args); if (updateResult != -1) { Log.d(LOG_TAG + "->uAI", "AppImage updated."); result = true; } return result; } @Override public boolean deleteAppImage(AppImage appImage) { Log.i(LOG_TAG + "->dAI", "Deleting AppImage."); boolean result = false; String[] args = { "" + appImage.getId() }; long deleteResult = grabilityDatabase.delete(appImagesTableName, idColumnName + " = ?", args); if (deleteResult != 0) { Log.d(LOG_TAG + "->dAI", "AppImage deleted."); result = true; } return result; } private AppImage transformCursorToAppImage(Cursor cursor) { Log.i(LOG_TAG + "->tCTAI", "Transforming Cursor to AppImage."); AppImage appImage = new AppImage(); appImage.setId(cursor.getLong(0)); appImage.setAppId(cursor.getLong(1)); appImage.setLabel(cursor.getString(2)); appImage.setHeight(cursor.getInt(3)); appImage.setImageData(cursor.getBlob(4)); appImage.setSourceUrl(cursor.getString(5)); Log.d(LOG_TAG + "->tCTAI", "Cursor transformed to AppImage."); Log.i(LOG_TAG + "->tCTAI", "Returning AppImage."); return appImage; } }
package sample.Emulator; public class SPI { public static Port Port = new Port(); }
package polarpelican.units; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import polarpelican.mapmaker.Map; /** * The UnitMap contains all of the units associated with a particular level, * as well as functions to manipulate and access them. * @author Sean Kelly */ public class UnitMap { private LinkedList<Team> teams; private UnitFactory uf; private Map myMap; public UnitMap(String mapFile, Map m) { teams = new LinkedList<Team>(); uf = new UnitFactory(); myMap = m; try { parseFile(mapFile); } catch (IOException ex) { Logger.getLogger(UnitMap.class.getName()).log(Level.SEVERE, null, ex); } } /** * This function is called when one wants to add a new <code>Team</code> to * the teams on the field. * @param newTeam The team to add to the <code>UnitMap</code> */ public void addTeam(Team newTeam) { teams.add(newTeam); } /** * This function is used to clear all teams and units from the UnitMap. */ public void clear() { teams.clear(); } /** * This function is used to get the team of a particular unit. If the unit * is not on any team, a NotOnTeamException is thrown. * @param unit The unit to find the team of. * @return The team the unit is on. * @throws NotOnTeamException If the given unit is not on a team. */ public Team getTeamOf(UnitContext unit) throws NotOnTeamException { Iterator<Team> itr = teams.iterator(); boolean found = false; Team curr = null; while(itr.hasNext() && !found) { curr = itr.next(); found = curr.isOnTeamAndAlive(unit); } if (!found) throw new NotOnTeamException(unit); return curr; } /** * This function returns a team based on the name of a team. It throws * an exception if the team does not exist. * @param name The name of the team to search for. * @return The team that was found. * @throws NotOnTeamException Thrown if a team by that name does not exist * in this map. */ public Team getTeamByName(String name) throws NotOnTeamException { Iterator<Team> itr = teams.iterator(); boolean found = false; Team curr = null; while(itr.hasNext() && !found) { curr = itr.next(); found = curr.getName().equals(name); } if (!found) throw new NotOnTeamException(name); return curr; } private void parseFile(String inFile) throws IOException { Scanner scanner = null; try { scanner = new Scanner(new File(inFile)); } catch (FileNotFoundException ex) { Logger.getLogger(UnitMap.class.getName()).log(Level.SEVERE, null, ex); } String json = new String(); while(scanner.hasNext()) json += scanner.nextLine(); JSONObject obj = (JSONObject)JSONValue.parse(json); JSONArray unitFiles = (JSONArray)((JSONObject)obj).get("unittypes"); for(int i=0; i<unitFiles.size(); i++) { UnitDefinition unitDef = UnitDefinition.parseFile((String)unitFiles.get(i)+".json"); try { uf.addDefinition(unitDef.typeName, unitDef); } catch (IOException ex) { Logger.getLogger(UnitMap.class.getName()).log(Level.SEVERE, null, ex); } } JSONArray jTeams = (JSONArray)((JSONObject)obj).get("teams"); Team currTeam; JSONArray unitArr; JSONObject teamObject; JSONObject indUnit; UnitContext unit; int xLoc; int yLoc; for(int i=0; i<jTeams.size(); i++) { //Create the team teamObject = (JSONObject)jTeams.get(i); currTeam = new Team((String)teamObject.get("team"), Stance.valueOf((String)teamObject.get("stance"))); //dig into the team and get the unit array out unitArr = (JSONArray)teamObject.get("units"); for(int j=0; j<unitArr.size(); j++) { //get an indivdual from the json indUnit = (JSONObject)unitArr.get(j); unit = new UnitContext((String)indUnit.get("type"), uf); //This is stupid but I couldn't find a way around it //@todo fix this stupid code xLoc = Integer.valueOf(indUnit.get("xloc").toString()); yLoc = Integer.valueOf(indUnit.get("yloc").toString()); //add the unit to the tile myMap.getTile(xLoc, yLoc).addOcuppier(unit); //add the unit to the unit map currTeam.addUnit(unit); } addTeam(currTeam); } } }
package nb.service; import nb.domain.*; import nb.queryDomain.BidDetails; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.List; public interface ReportService { File makeDodatok(List<Asset> assetList, List<Credit> creditList, String startDate, String endDate) throws IOException; String makeOgoloshennya(Long bidId) throws IOException; String fillCrdTab(List<Credit> creditList) throws IOException; File fillSoldedCrdTab(List<Credit> creditList) throws IOException; File fillCreditsReestr(List<Lot> lotList) throws IOException; File fillAssTab() throws IOException; File getTempFile(MultipartFile multipartFile) throws IOException; File makePaymentsReport(List<Pay> payList, String start, String end) throws IOException; File makeBidsSumReport(List<LotHistory> lotList, List<BidDetails> aggregatedLotList) throws IOException; }
package com.thewalletlist.addressbook; import java.io.*; import java.util.ArrayList; import android.util.Log; import android.content.Context; import org.json.*; public class AddressBook implements Serializable { private static String FILENAME = "addressbook"; private ArrayList<AddressEntry> mAddressBook = new ArrayList(); public AddressBook() { return; // results in an empty array } public AddressBook(JSONArray a) { try { for (int i = 0; i < a.length(); i++) { AddressEntry addy = new AddressEntry(a.getJSONObject(i)); mAddressBook.add(addy); } } catch (JSONException e) { Log.e(C.LOG, "AddressBook(): " + e.toString()); } } public ArrayList<AddressEntry> getAsList() { return mAddressBook; } public int count() { return mAddressBook.size(); } public AddressEntry getById(String id) { for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.idEquals(id)) { return a; } } return null; } public AddressEntry getByLabel(String label) { for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.getLabel().equals(label)) { return a; } } return null; } public int getIndexByLabel(String label) { for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.getLabel().equals(label)) { return i; } } return -1; } public int getIndexById(String id) { for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.idEquals(id)) { return i; } } return -1; } // overwrites if the id matches an existing entry public void addOrUpdate(AddressEntry entry) { boolean found = false; for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.idEquals(entry.getId())) { mAddressBook.set(i, entry); found = true; } } if (!found) { mAddressBook.add(entry); } } public void deleteByLabel(String label) { for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.getLabel().equals(label)) { mAddressBook.remove(i); } } } public void delete(AddressEntry address) { for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry a = mAddressBook.get(i); if (a.getLabel().equals(address.getLabel())) { mAddressBook.remove(i); } } } public static boolean hasAddressBook(Context c) { String[] files = c.fileList(); for (int i = 0; i < files.length; i++) { if (files[i].equals(FILENAME)) { return true; } } return false; } public static AddressBook load(Context c) { if (hasAddressBook(c)) { Log.d(C.LOG, "looks like we have local data"); try { FileInputStream fis = c.openFileInput(FILENAME); String s = Util.convertStreamToString(fis); JSONArray a = new JSONArray(s); return new AddressBook(a); } catch (Exception e) { Log.e(C.LOG, "AddressBook.load: " + e.toString()); // should only happen on upgrades, when types are incompatible. return new AddressBook(); } } else { Log.d(C.LOG, "empty address book"); return new AddressBook(); } } public void save(Context c) { JSONArray a = toJSON(); String saveme = a.toString(); FileOutputStream fos = null; try { fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(saveme.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (fos != null) { fos.flush(); fos.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } public JSONArray toJSON() { JSONArray arr = new JSONArray(); for (int i = 0; i < mAddressBook.size(); i++) { AddressEntry addy = mAddressBook.get(i); arr.put(addy.toJSON()); } return arr; } }
public interface PassengersAuto { default void transportPassengers(){ System.out.println("transport Passengers"); }; }
package ba.bitcamp.LabS09D02; /** * * @author nermingraca * */ public class StudentTest { public static void main(String[] args) { Student first = new Student("Neldin", 1, 8.2); Student second = new Student("Mustafa", 11, 7.2); Student third = new Student("Hikmet", 1, 8.2); Student fourth = new Student("Edib", 13, 7.2); System.out.println(first.compareTo(second)); Student[] classroom = new Student[] {first, second, third, fourth}; selectionSort(classroom); for (int i = 0; i < classroom.length; i++) { System.out.println(classroom[i].toString()); } } /** * Method Selection Sort sorts array * @param arr */ private static void selectionSort(Student[] arr) { for (int i = arr.length-1; i > 0; i--) { int max = 0; for (int j = 1; j <=i; j++) { if (arr[j].compareTo(arr[max]) > 0) { max = j; } } Student temp = new Student(); temp = arr[max]; arr[max] = arr[i]; arr[i] = temp; } } }
package com.pangpang6.hadoop.zookeeper; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; /** * Created by jiangjiguang on 2018/2/12. */ public class ZKConstructAA implements Watcher { @Override public void process(WatchedEvent watchedEvent) { } }
package org.trivee.fb2pdf; @SuppressWarnings("serial") public class FB2toPDFException extends Exception { public FB2toPDFException(String message) { super(message); } }
package carnival.gusac.com.gusaccarnival40; /** * Created by Messi10 on 31-Jan-15. */ /*This class provides an abstraction for an event's title,description and its image. These properties are set using a custom list view adapter(MyEventAdapter). */ public class EventInfo { String title; String description; int image; //Set the respective properties in the constructor EventInfo(String title, String description, int image) { this.title = title; this.description = description; this.image = image; } }
package my.battleships.GameField; import my.battleships.ConsoleHelper; import my.battleships.Exeptions.ShipSetupException; import my.battleships.Exeptions.WrongCoordinatesException; import my.battleships.Players.FiringResult; import my.battleships.ships.*; import java.util.LinkedList; import java.util.List; import java.util.Observable; public class GameField extends Observable{ private final List<AbstractShip> ships; private final Cell[][] field; private boolean atLeastOneShipAlive; public GameField() { ships = new LinkedList<AbstractShip>(); field = new Cell[10][10]; for (int i = 0; i < 10 ; i++) for (int j = 0; j < 10 ; j++) field [i][j] = new Cell(); atLeastOneShipAlive = true; } public void addShip(AbstractShip shipForAdd) throws ShipSetupException { if (checkShipConfluence(shipForAdd) && checkDimensionBetweenTwoShips(shipForAdd)){ ships.add(shipForAdd); for (Deck currentDeck : shipForAdd.getShipDecks()) field[currentDeck.getCoordinates().x][currentDeck.getCoordinates().y] = currentDeck; } else throw new ShipSetupException(); } //must be checked every deck in every ship witch setup in Game field with every deck of new ship //by the formula Euclidean distance private boolean checkDimensionBetweenTwoShips(AbstractShip checkedShip){ for(AbstractShip currentShip : ships) for(Deck currentDeck : currentShip.getShipDecks()) for (Deck checkedDeck : checkedShip.getShipDecks()) if(Math.sqrt( Math.pow(checkedDeck.getCoordinates().x - currentDeck.getCoordinates().x, 2) + Math.pow(checkedDeck.getCoordinates().y - currentDeck.getCoordinates().y, 2) ) < 2) return false; return true; } public boolean isAtLeastOneShipAlive() { return atLeastOneShipAlive; } private boolean checkShipConfluence(AbstractShip checkedShip){ for(Deck currentDeck : checkedShip.getShipDecks()) if (field[currentDeck.getCoordinates().x][currentDeck.getCoordinates().y] instanceof Deck) return false; return true; } private void checkShipsLife (){ atLeastOneShipAlive = false; for(AbstractShip currentShip : ships) atLeastOneShipAlive = atLeastOneShipAlive | currentShip.isShipAlive(); } public FiringResult checkFireResult(Coordinates coordinates){ return checkFireResult(coordinates.x, coordinates.y); } public FiringResult checkFireResult(int x, int y){ if(!(field[x][y] instanceof Deck)) return FiringResult.MISS; else { if (((Deck)field[x][y]).getParentShip().getType() == ShipTypes.MINE) return FiringResult.MINE; else if(((Deck)field[x][y]).getParentShip().isShipAlive()) return FiringResult.HURT; else return FiringResult.DROWNED; } } public Cell getFieldCell(Coordinates coordinates) { return getFieldCell(coordinates.x, coordinates.y); } public Cell getFieldCell(int x, int y) { return field[y][x]; } public List<AbstractShip> getShips() { return ships; } public FiringResult hit(Coordinates coordinates) throws WrongCoordinatesException { return hit(coordinates.x, coordinates.y); } public FiringResult hit(int x, int y) throws WrongCoordinatesException { boolean isHitWasSuccessful = field[x][y].hit(); if (isHitWasSuccessful){ checkShipsLife(); return checkFireResult(x, y); } else throw new WrongCoordinatesException(); } public int shipsCount(){ return ships.size(); } public void cheats (){ for(AbstractShip ship : ships) for(Deck deck : ship.getShipDecks()) if (deck.isAlive())deck.setHide(!deck.isHide()); } public boolean isRightMineSacrifice (Coordinates coordinates) throws WrongCoordinatesException { if(field[coordinates.x][coordinates.y] instanceof Deck && field[coordinates.x][coordinates.y].isAlive() && ((Deck)field[coordinates.x][coordinates.y]).getParentShip().getType() != ShipTypes.MINE) return true; else throw new WrongCoordinatesException(); } public static class Coordinates{ private int x; private int y; public Coordinates(int x, int y){ this.x = x; this.y = y; } //it need for setup new ships with horizontal and vertical direction public Coordinates moveX(int dx) throws ShipSetupException { int newX = x + dx; if(newX < 0 || newX > 9 ) throw new ShipSetupException(); return new Coordinates(newX, y); } public Coordinates moveY(int dy) throws ShipSetupException { int newY = y + dy; if(newY < 0 || newY > 9) throw new ShipSetupException(); return new Coordinates(x, newY); } public static Coordinates coordinatesParser(String stringCoordinates) throws WrongCoordinatesException { if (!stringCoordinates.matches(("(^[a-j]\\d$)|(^[a-j]\\d[v]$)"))) throw new WrongCoordinatesException(); int x = (ConsoleHelper.letters.indexOf(stringCoordinates.charAt(0))-1)/2; int y = Character.getNumericValue(stringCoordinates.charAt(1)); return new Coordinates(x, y); } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Coordinates)) return false; Coordinates that = (Coordinates) o; if (x != that.x) return false; return y == that.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } @Override public String toString() { return "" + ConsoleHelper.letters.charAt(x * 2 + 1) + y; } } }
package Controller; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import view.Fenetre; public class Controller { public Controller(Fenetre fenetre) { fenetre.getView().addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { fenetre.handleMouseClick(e.getPoint()); } @Override public void mouseReleased(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} }); } }
abstract class Kort implements Comparable<Kort>, Cloneable { protected String firstName; protected String lastName; private int pinkode; private static int kortnummer; private static int kort = 0; private static boolean sperretKort = false; public Kort(String firstName, String lastName, int pinkode){ this.firstName = firstName; this.lastName = lastName; this.pinkode = pinkode; kortnummer = kort++; } public abstract boolean sjekkPin(int pinkodet); public Kort clone(){ try { return (Kort) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new RuntimeException(); } } public int compareTo(Kort k){ if (lastName.compareTo(k.lastName) > 0) return 1; else if (lastName.compareTo(k.lastName) < 0) return -1; else if (firstName.compareTo(k.firstName) > 0) return 1; else if (firstName.compareTo(k.firstName) < 0) return -1; else return 0; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getPinkode() { return pinkode; } public static int getKortnummer() { return kortnummer; } public static int getKort() { return kort; } public static boolean isSperretKort() { return sperretKort; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setPinkode(int pinkode) { this.pinkode = pinkode; } public static void setKortnummer(int kortnummer) { Kort.kortnummer = kortnummer; } public static void setKort(int kort) { Kort.kort = kort; } public static void setSperretKort(boolean sperretKort) { Kort.sperretKort = sperretKort; } public String toString(){ String temp; if (isSperretKort()) temp = "gyldig"; else temp = "ugyldig"; return "First name: " + firstName + ", last name: " + lastName + ", pinkode: " + pinkode + ", kortnummer: " + kortnummer + ". Kortet er " + temp + "."; } }
package me.dao; import me.entity.UserEntity; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserDao { //@Select("select * from user") List<UserEntity> selectList(@Param("name") String xm ,@Param("ids") List<Long> ids); }
import java.util.Scanner; class Address{ String city, state, country; int zip; public Address(String city, String state, int zip, String country){ this.city = city; this.state = state; this.zip = zip; this.country = country; } public void setCity(String city){ this.city = city; } public void setState(String state){ this.state = state; } public void setZip(int zip){ this.zip = zip; } public void setCountry(String country){ this.country = country; } public String getCity(){ return city; } public String getState(){ return state; } public int getZip(){ return zip; } public String getCountry(){ return country; } @Override public String toString(){ return getCity()+" "+getState()+" "+getZip()+" "+getCountry()+""; } } class Customer{ int customerId; String customerName, password, email; Address a; public Customer(){ } public Customer(int customerId, String customerName, String password, Address a, String email){ this.customerId = customerId; this.customerName = customerName; this.password = password; this.a = a; this.email = email; } public void setCustomerName(String customerName){ this.customerName = customerName; } public void setPassword(String password){ this.password = password; } public void setpassword(String password){ this.password = password; } public void setEmail(String email){ this.email = email; } public void setAddress(Address address){ this.a = a; } public void setCustomerId(int customerId){ this.customerId = customerId; } public String getCustomerName(){ return customerName; } public String getPassword(){ return password; } public String getEmail(){ return email; } public Address getAddress(){ return a; } public int getCustomerId(){ return customerId; } @Override public String toString(){ return getCustomerId()+" "+getCustomerName()+" "+getPassword()+" "+getEmail()+"\n"+a.city+" "+a.state+" "+a.zip+" "+a.country; } } public class Source { public static void main( String[] args ) { Scanner sc = new Scanner(System.in); int customerId = sc.nextInt(); String customerName = sc.next(); String password = sc.next(); String email = sc.next(); String city = sc.next(); String state = sc.next(); int zip = sc.nextInt(); String country = sc.next(); Address a= new Address(city, state, zip, country); a.setCity(city); a.setState(state); a.setZip(zip); a.setCountry(country); Customer c = new Customer(customerId, customerName, password, a, email); System.out.println(c); // System.out.println(customerId+"-"+customerName+"-"+password+"-"+email+"-"+city+"-"+state+"-"+zip+"-"+country); } }
package com.artcraft.mavr.mechdroid; import android.service.wallpaper.WallpaperService; /** * Created by mavr on 11/15/14. */ public class liveWallpaper extends WallpaperService { protected class liveWallpaperEngine extends Engine { } @Override public Engine onCreateEngine() { return new liveWallpaperEngine(); } }
package com.ana.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; public class Section implements Serializable { @SerializedName("Text") @Expose private String text; @SerializedName("Id") @Expose private String id; @SerializedName("SectionType") @Expose private String sectionType; @SerializedName("DelayInMs") @Expose private Integer delayInMs; @SerializedName("Hidden") @Expose private Boolean hidden; @SerializedName("CoordinatesSet") @Expose private List<CoordinatesSet> coordinatesSet = null; @SerializedName("X") @Expose private X x; @SerializedName("Y") @Expose private Y y; @SerializedName("Caption") @Expose private String caption; @SerializedName("GraphType") @Expose private String graphType; @SerializedName("Url") @Expose private String url; @SerializedName("Title") @Expose private String title; @SerializedName("DurationInSeconds") @Expose private Integer durationInSeconds; @SerializedName("Format") @Expose private String format; @SerializedName("EncodingType") @Expose private String encodingType; @SerializedName("Downloadable") @Expose private Boolean downloadable; @SerializedName("Buffer") @Expose private Boolean buffer; @SerializedName("AnimateEmotion") @Expose private Boolean animateEmotion; @SerializedName("IsAuthenticationRequired") @Expose private Boolean isAuthenticationRequired; @SerializedName("Username") @Expose private String username; @SerializedName("Password") @Expose private String password; @SerializedName("PreFetch") @Expose private Boolean preFetch; @SerializedName("AltText") @Expose private String altText; @SerializedName("HeightInPixels") @Expose private Integer heightInPixels; @SerializedName("WidthInPixels") @Expose private Integer widthInPixels; @SerializedName("SizeInKb") @Expose private Double sizeInKb; @SerializedName("DurationInSec") @Expose private Integer durationInSec; @SerializedName("Length") @Expose private Integer otpLength; @SerializedName("DisplayOpenInBrowserButton") @Expose private boolean displayOpenInBrowserButton; @SerializedName("IsLoading") @Expose private boolean isLoading; @SerializedName("ShowDdate") @Expose private boolean showDate; @SerializedName("DateTime") @Expose private String dateTime; private int cardPos; private boolean replace = true; private Node cardModel; public Integer getOtpLength() { return otpLength; } public void setOtpLength(Integer otpLength) { this.otpLength = otpLength; } public Node getCardModel() { return cardModel; } public void setCardModel(Node cardModel) { this.cardModel = cardModel; } private boolean isAnimApplied = false; public boolean isAnimApplied() { return isAnimApplied; } public void setIsAnimApplied(boolean isAnimApplied) { this.isAnimApplied = isAnimApplied; } public String getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } public boolean isShowDate() { return showDate; } public int getCardPos() { return cardPos; } public void setCardPos(int cardPos) { this.cardPos = cardPos; } public void setShowDate(boolean showDate) { this.showDate = showDate; } public boolean isLoading() { return isLoading; } public void setLoading(boolean loading) { isLoading = loading; } public boolean isDisplayOpenInBrowserButton() { return displayOpenInBrowserButton; } public void setDisplayOpenInBrowserButton(boolean displayOpenInBrowserButton) { this.displayOpenInBrowserButton = displayOpenInBrowserButton; } private boolean isFromRia = true; private boolean isFollowUp = true; public boolean isFromRia() { return isFromRia; } public boolean isFollowUp() { return isFollowUp; } public void setFollowUp(boolean followUp) { isFollowUp = followUp; } public void setAnimApplied(boolean animApplied) { isAnimApplied = animApplied; } public void setFromRia(boolean fromRia) { isFromRia = fromRia; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSectionType() { return sectionType; } public void setSectionType(String sectionType) { this.sectionType = sectionType; } public Integer getDelayInMs() { return delayInMs; } public void setDelayInMs(Integer delayInMs) { this.delayInMs = delayInMs; } public Boolean getHidden() { return hidden; } public void setHidden(Boolean hidden) { this.hidden = hidden; } public List<CoordinatesSet> getCoordinatesSet() { return coordinatesSet; } public void setCoordinatesSet(List<CoordinatesSet> coordinatesSet) { this.coordinatesSet = coordinatesSet; } public X getX() { return x; } public void setX(X x) { this.x = x; } public Y getY() { return y; } public void setY(Y y) { this.y = y; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getGraphType() { return graphType; } public void setGraphType(String graphType) { this.graphType = graphType; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getDurationInSeconds() { return durationInSeconds; } public void setDurationInSeconds(Integer durationInSeconds) { this.durationInSeconds = durationInSeconds; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String getEncodingType() { return encodingType; } public void setEncodingType(String encodingType) { this.encodingType = encodingType; } public Boolean getDownloadable() { return downloadable; } public void setDownloadable(Boolean downloadable) { this.downloadable = downloadable; } public Boolean getBuffer() { return buffer; } public void setBuffer(Boolean buffer) { this.buffer = buffer; } public Boolean getAnimateEmotion() { return animateEmotion; } public void setAnimateEmotion(Boolean animateEmotion) { this.animateEmotion = animateEmotion; } public Boolean getAuthenticationRequired() { return isAuthenticationRequired; } public void setAuthenticationRequired(Boolean authenticationRequired) { isAuthenticationRequired = authenticationRequired; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean getPreFetch() { return preFetch; } public void setPreFetch(Boolean preFetch) { this.preFetch = preFetch; } public String getAltText() { return altText; } public void setAltText(String altText) { this.altText = altText; } public Integer getHeightInPixels() { return heightInPixels; } public void setHeightInPixels(Integer heightInPixels) { this.heightInPixels = heightInPixels; } public Integer getWidthInPixels() { return widthInPixels; } public void setWidthInPixels(Integer widthInPixels) { this.widthInPixels = widthInPixels; } public Double getSizeInKb() { return sizeInKb; } public void setSizeInKb(Double sizeInKb) { this.sizeInKb = sizeInKb; } public Integer getDurationInSec() { return durationInSec; } public void setDurationInSec(Integer durationInSec) { this.durationInSec = durationInSec; } public boolean isReplace() { return replace; } public void setReplace(boolean replace) { this.replace = replace; } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.database; import com.qtplaf.library.app.Session; /** * Provides field metadata as fields of the fields properties. * * @author Miquel Sas */ public class FieldProperties { /** Property alias: INDEX. */ public static final String INDEX = "INDEX"; /** Property alias: GROUP. */ public static final String GROUP = "GROUP"; /** Property alias: GROUP_INDEX. */ public static final String GROUP_INDEX = "GROUP_INDEX"; /** Property alias: NAME. */ public static final String NAME = "NAME"; /** Property alias: ALIAS. */ public static final String ALIAS = "ALIAS"; /** Property alias: HEADER. */ public static final String HEADER = "HEADER"; /** Property alias: TITLE. */ public static final String TITLE = "TITLE"; /** Property alias: TYPE. */ public static final String TYPE = "TYPE"; /** Property alias: LENGTH. */ public static final String LENGTH = "LENGTH"; /** Property alias: DECIMALS. */ public static final String DECIMALS = "DECIMALS"; /** Property alias: ASC. */ public static final String ASCENDING = "ASC"; /** * The working session. */ private Session session; /** * The properties field list. */ private FieldList fieldList; /** * Constructor. * * @param session The working session. */ public FieldProperties(Session session) { super(); this.session = session; } /** * Returns the properties field list. * * @return The properties field list. */ public FieldList getFieldList() { if (fieldList == null) { fieldList = new FieldList(); fieldList.addField(getFieldGroupIndex()); fieldList.addField(getFieldIndex()); fieldList.addField(getFieldGroup()); fieldList.addField(getFieldName()); fieldList.addField(getFieldAlias()); fieldList.addField(getFieldHeader()); fieldList.addField(getFieldTitle()); fieldList.addField(getFieldType()); fieldList.addField(getFieldLength()); fieldList.addField(getFieldDecimals()); fieldList.addField(getFieldAscending()); } return fieldList; } /** * Returns the properties record. * * @return The properties record. */ public Record getProperties() { return new Record(getFieldList()); } /** * Returns the field corresponding to the property <i>GroupIndex</i>. * * @return The field. */ public Field getFieldGroupIndex() { Field field = new Field(); field.setName(GROUP_INDEX); field.setAlias(GROUP_INDEX); field.setTitle(session.getString("fieldGroupIndex")); field.setLabel(session.getString("fieldGroupIndex")); field.setHeader(session.getString("fieldGroupIndex")); field.setType(Types.INTEGER); field.setPrimaryKey(true); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Index</i>. * * @return The field. */ public Field getFieldIndex() { Field field = new Field(); field.setName(INDEX); field.setAlias(INDEX); field.setTitle(session.getString("fieldIndex")); field.setLabel(session.getString("fieldIndex")); field.setHeader(session.getString("fieldIndex")); field.setType(Types.INTEGER); field.setPrimaryKey(true); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Group</i>. * * @return The field. */ public Field getFieldGroup() { Field field = new Field(); field.setName(GROUP); field.setAlias(GROUP); field.setTitle(session.getString("fieldGroup")); field.setLabel(session.getString("fieldGroup")); field.setHeader(session.getString("fieldGroup")); field.setType(Types.STRING); field.setLength(60); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Name</i>. * * @return The field. */ public Field getFieldName() { Field field = new Field(); field.setName(NAME); field.setAlias(NAME); field.setTitle(session.getString("fieldName")); field.setLabel(session.getString("fieldName")); field.setHeader(session.getString("fieldName")); field.setType(Types.STRING); field.setLength(30); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Alias</i>. * * @return The field. */ public Field getFieldAlias() { Field field = new Field(); field.setName(ALIAS); field.setAlias(ALIAS); field.setTitle(session.getString("fieldAlias")); field.setLabel(session.getString("fieldAlias")); field.setHeader(session.getString("fieldAlias")); field.setType(Types.STRING); field.setLength(30); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Header</i>. * * @return The field. */ public Field getFieldHeader() { Field field = new Field(); field.setName(HEADER); field.setAlias(HEADER); field.setTitle(session.getString("fieldHeader")); field.setLabel(session.getString("fieldHeader")); field.setHeader(session.getString("fieldHeader")); field.setType(Types.STRING); field.setLength(60); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Title</i>. * * @return The field. */ public Field getFieldTitle() { Field field = new Field(); field.setName(TITLE); field.setAlias(TITLE); field.setTitle(session.getString("fieldTitle")); field.setLabel(session.getString("fieldTitle")); field.setHeader(session.getString("fieldTitle")); field.setType(Types.STRING); field.setLength(60); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Type</i>. * * @return The field. */ public Field getFieldType() { Field field = new Field(); field.setName(TYPE); field.setAlias(TYPE); field.setTitle(session.getString("fieldType")); field.setLabel(session.getString("fieldType")); field.setHeader(session.getString("fieldType")); field.setType(Types.STRING); field.setLength(20); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Length</i>. * * @return The field. */ public Field getFieldLength() { Field field = new Field(); field.setName(LENGTH); field.setAlias(LENGTH); field.setTitle(session.getString("fieldLength")); field.setLabel(session.getString("fieldLength")); field.setHeader(session.getString("fieldLength")); field.setType(Types.INTEGER); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Decimals</i>. * * @return The field. */ public Field getFieldDecimals() { Field field = new Field(); field.setName(DECIMALS); field.setAlias(DECIMALS); field.setTitle(session.getString("fieldDecimals")); field.setLabel(session.getString("fieldDecimals")); field.setHeader(session.getString("fieldDecimals")); field.setType(Types.INTEGER); field.setFixedWidth(false); return field; } /** * Returns the field corresponding to the property <i>Ascending/Descending</i>. * * @return The field. */ public Field getFieldAscending() { Field field = new Field(); field.setName(ASCENDING); field.setAlias(ASCENDING); field.setTitle(session.getString("fieldAsc")); field.setLabel(session.getString("fieldAsc")); field.setHeader(session.getString("fieldAsc")); field.setType(Types.STRING); field.addPossibleValue(new Value(session.getString("tokenAsc"))); field.addPossibleValue(new Value(session.getString("tokenDesc"))); field.setFixedWidth(false); return field; } /** * Fill the properties record with field data. * * @param field Source field. * @param index The index in the list. * @param ascending The ascending flag, not included by default in the field. * @return properties The properties record. */ public Record getProperties(Field field, int index, boolean ascending) { Record properties = getProperties(); properties.setValue(INDEX, index); properties.setValue(GROUP, getFieldGroupTitle(field.getFieldGroup())); properties.setValue(GROUP_INDEX, getFieldGroupIndex(field.getFieldGroup())); properties.setValue(NAME, field.getName()); properties.setValue(ALIAS, field.getAlias()); properties.setValue(HEADER, field.getHeader()); properties.setValue(TITLE, field.getTitle()); properties.setValue(TYPE, field.getType().name()); properties.setValue(LENGTH, field.getLength()); properties.setValue(DECIMALS, field.getDecimals()); // Special property String strAscending = session.getString(ascending ? "tokenAsc" : "tokenDesc"); properties.setValue(ASCENDING, strAscending); // Set the source field that gave values to this properties. properties.getProperties().setObject("Source", field); // Nullify length and decimals if appropriate. if (!field.isNumber()) { properties.getValue(DECIMALS).setNull(); } if (field.getLength() <= 0) { properties.getValue(LENGTH).setNull(); } // Store group and subgroup as objects. properties.getProperties().setObject(GROUP, field.getFieldGroup()); return properties; } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public int getPropertyGroupIndex(Record properties) { return properties.getValue(GROUP_INDEX).getInteger(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public int getPropertyIndex(Record properties) { return properties.getValue(INDEX).getInteger(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public String getPropertyGroup(Record properties) { return properties.getValue(GROUP).getString(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public String getPropertyName(Record properties) { return properties.getValue(NAME).getString(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public String getPropertyAlias(Record properties) { return properties.getValue(ALIAS).getString(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public String getPropertyHeader(Record properties) { return properties.getValue(HEADER).getString(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public String getPropertyTitle(Record properties) { return properties.getValue(TITLE).getString(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public Types getPropertyType(Record properties) { return Types.parseType(properties.getValue(TYPE).getString()); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public int getPropertyLength(Record properties) { return properties.getValue(LENGTH).getInteger(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public int getPropertyDecimals(Record properties) { return properties.getValue(DECIMALS).getInteger(); } /** * Returns the field property. * * @param properties The properties record. * @return The property value. */ public boolean getPropertyAscending(Record properties) { return properties.getValue(ASCENDING).equals(session.getString("tokenAsc")); } /** * Returns the source field that gave values to the properties. * * @param properties The properties. * @return The source field. */ public Field getPropertiesSourceField(Record properties) { return (Field) properties.getProperties().getObject("Source"); } /** * Returns a valid string for the field group. * * @param fieldGroup The field group. * @return The title string. */ private String getFieldGroupTitle(FieldGroup fieldGroup) { if (fieldGroup == null) { return ""; } if (fieldGroup.getName() == null) { throw new IllegalStateException(); } if (fieldGroup.getTitle() == null) { return fieldGroup.getName(); } return fieldGroup.getTitle(); } /** * Returns a valid index for the field group. * * @param fieldGroup The field group. * @return A valid index (NumberUtils.MAX_INTEGER if the group is null) */ private int getFieldGroupIndex(FieldGroup fieldGroup) { if (fieldGroup == null) { return FieldGroup.emptyFieldGroup.getIndex(); } return fieldGroup.getIndex(); } }
/*package ViewController; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.*; import java.io.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.imageio.ImageIO; import java.util.ArrayList; import ViewController.PokerCardPanel; import AppDelegate.Dealer; import AppDelegate.Player; import CardModel.Card; import Main.GameInstance; public class HoldemGUI extends JFrame { // music control private JButton musicPlayer; private JButton play; private static boolean playMusic; private static Clip clip; // game private JPanel holeCardPanel; private Dealer game; private String getOutput; public static void main(String [] args) throws Exception { playMusic = true; // setup window JFrame UIWindow = new HoldemGUI(); UIWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); UIWindow.setVisible(true); UIWindow.setSize(1024, 768); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); UIWindow.setLocation(screenSize.width/2 - UIWindow.getSize().width/2, screenSize.height/2 - UIWindow.getSize().height/2); UIWindow.setResizable(false); UIWindow.setTitle("Arizona Hold 'em"); // setup background music AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("src/music.wav")); clip = AudioSystem.getClip(); clip.open(inputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); //Thread.sleep(-1);//10000); // looping as long as this thread is alive } public HoldemGUI() { setLayout(new GridLayout(2, 2, 4, 4)); //setLayout(new BorderLayout()); //setLayout(new FlowLayout()); //setContentPane(new JLabel(new ImageIcon("UI/background.jpg"))); // setup musicPlayer musicPlayer = new JButton("Stop Music"); add(musicPlayer); musicPlayer.addActionListener(new musicController()); game = new Dealer(new Player []{ new Player("You"), new Player("Robot 1"), new Player("Robot 2"), new Player("Robot 3")}); getOutput = game.deal(); ArrayList<Card> holdCard = new ArrayList<Card>(); for(int i = 0; i < game.players[0].getHoleCards().length; i++) { holdCard.add(game.players[0].getHoleCards()[i]); } //test print out System.out.println(getOutput); holeCardPanel = new PokerCardPanel(holdCard); this.add(holeCardPanel); play = new JButton("Play"); add(play); play.addActionListener(new startARound()); //this.add(fiveCardPanel); } private class musicController implements ActionListener { public void actionPerformed(ActionEvent e) { if(playMusic) { clip.stop(); playMusic = false; musicPlayer.setText("Play Music"); } else { clip.loop(Clip.LOOP_CONTINUOUSLY); playMusic = true; musicPlayer.setText("Stop Music"); } } } private class startARound implements ActionListener { public void actionPerformed(ActionEvent e) { getOutput = game.deal(); //test print out System.out.println(getOutput); ArrayList<Card> holdCard = new ArrayList<Card>(); for(int i = 0; i < game.players[0].getHoleCards().length; i++) { holdCard.add(game.players[0].getHoleCards()[i]); } } } } */
package com.monitora.monitoralog; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MonitoralogApiApplication { public static void main(String[] args) { SpringApplication.run(MonitoralogApiApplication.class, args); } }
package com.gyk.s2h.varmisin; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import com.squareup.picasso.Transformation; import java.io.IOException; import java.util.Map; public class Profil extends AppCompatActivity { private String userID; private KisiModel kisiModel; private DatabaseReference mDatabase; Uri selectedImageUri; Uri secilenResim; ImageView resim; TextView isim,kad,dtarih; private ImageView selectedImagePreview; String kisiAd,kullanıcıAd,Dtarih,kresim; private Map<String, Object> postValues; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profil); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); userID = user.getUid(); Log.d("userID:", userID); mDatabase = FirebaseDatabase.getInstance().getReference(); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout1); tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_black_24dp)); tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.arkadaslar)); tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.yaptiklarim)); isim=(TextView)findViewById(R.id.isim); kad=(TextView)findViewById(R.id.kullanici_adi); dtarih=(TextView)findViewById(R.id.dtarih); selectedImagePreview=(ImageView)findViewById(R.id.userpicture); final Transformation transformation = new RoundedTransformationBuilder() .borderColor(Color.LTGRAY) .borderWidthDp(4) .cornerRadiusDp(35) .oval(true) .build(); mDatabase.child("users").child(userID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { KisiModel user = dataSnapshot.getValue(KisiModel.class); if(user==null){ Toast.makeText(Profil.this, "Lütfen Profil bilgilerini ekleyiniz", Toast.LENGTH_SHORT).show(); } else{ kisiAd= user.getAdSoyad(); kullanıcıAd=user.getKullanici_adi(); Dtarih=user.getDtarih(); isim.setText(kisiAd); kad.setText(kullanıcıAd); dtarih.setText(Dtarih); kresim=user.getPath(); secilenResim= Uri.parse(kresim); //Picasso ile kullanı profili için secilenResim Uri siyle profil resmi oluşturuyoruz. Picasso.with(Profil.this).load(secilenResim).fit().transform(transformation).into(selectedImagePreview); } } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w("Hata","Hata mesajı"); } }); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); final ProfilPagerAdapter adapter = new ProfilPagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main2, menu); return true; } public void ProfilDüzenle(View view){ Intent intent= new Intent(this,UserProfilEdit.class); startActivity(intent); } }
package checkers.studentCLients; import java.util.ArrayList; import checkers.*; public class CheckersClientRandomMover implements CheckersClient{ Move lastMove = null; int MyColor; int [][] boardBeforLastMove = new int [][] { { 0, 1, 0, 1, 0, 1, 0, 1}, { 1, 0, 1, 0, 1, 0, 1, 0}, { 0, 1, 0, 1, 0, 1, 0, 1}, { 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0}, { 2, 0, 2, 0, 2, 0, 2, 0}, { 0, 2, 0, 2, 0, 2, 0, 2}, { 2, 0, 2, 0, 2, 0, 2, 0} }; public void boardNotify(Move newMove) { if (lastMove != null) Controller.updateTable(boardBeforLastMove, lastMove); lastMove = newMove; } public Move getMove() { ArrayList<Move> validMoves = Controller.getValidMoves(boardBeforLastMove, lastMove); int r = (int)Math.floor(Math.random() * validMoves.size()); Move newMove = validMoves.get(r); if (lastMove != null) Controller.updateTable(boardBeforLastMove, lastMove); lastMove = newMove; return newMove; } public void setColor(int color) { MyColor = color; } }
package vrcube; import processing.core.PApplet; import processing.vr.*; public class Sketch extends PApplet { public void settings() { fullScreen(STEREO); } public void setup() { } public void draw() { background(157); lights(); translate(width/2, height/2); rotateX(frameCount * 0.01f); rotateY(frameCount * 0.01f); box(350); } }
package com.locadoraveiculosweb.util.jpa; import static org.apache.commons.lang3.ObjectUtils.isEmpty; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Schedule; import javax.ejb.Singleton; import javax.ejb.Startup; import com.locadoraveiculosweb.modelo.BaseEntity; import lombok.Getter; import lombok.extern.log4j.Log4j; @Startup @Singleton @Log4j public class Cache<T extends BaseEntity> { @Getter Map<String, Object> cache; @PostConstruct public void initializer() { newIntance(); } @Schedule(dayOfMonth = "*", hour = "*/1", persistent = false) public void newIntance() { cache = new HashMap<>(); log.info("Cleaning the Cache."); } public boolean isInCache(String key) { return cache.containsKey(key) && !isEmpty(cache.get(key)); } @Lock(LockType.READ) public Object getValue(String key){ return cache.get(key); } @Lock(LockType.WRITE) public void putValue(String key, Object values) { cache.put(key, values); } @SuppressWarnings("unchecked") public void removeValue(T object, String key) { if(isInCache(key)) { List<T> list = (List<T>) cache.get(key); if(removeIf(object, list)) { putValue(key, list); } } } @SuppressWarnings("unchecked") public void updateValue(T object, String key) { if(isInCache(key)) { List<T> list = (List<T>) cache.get(key); if(removeIf(object, list)) { list.add(object); } else { list.add(object); } } } public void cleanCache(String cacheKey) { putValue(cacheKey, null); } private boolean removeIf(T object, List<T> list) { return list.removeIf(o -> o.getCodigo().equals(object.getCodigo())); } }
package com.ld.community.service.impl; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ld.common.dao.PublicInformationModelMapper; import com.ld.common.model.PublicInformationModel; import com.ld.common.utils.LoggerUtils; import com.ld.community.service.PublicInfoService; import com.ld.core.mybatis.BaseMybatisDao; import com.ld.core.mybatis.page.Pagination; @Service @SuppressWarnings("unchecked") public class PublicInfoServiceImpl extends BaseMybatisDao<PublicInformationModelMapper> implements PublicInfoService { @Autowired PublicInformationModelMapper publicInformationModelMapper; @Override public int deleteByPrimaryKey(Long id) { return publicInformationModelMapper.deleteByPrimaryKey(id); } @Override public int insert(PublicInformationModel record) { return publicInformationModelMapper.insert(record); } @Override public int insertSelective(PublicInformationModel record) { return publicInformationModelMapper.insertSelective(record); } @Override public PublicInformationModel selectByPrimaryKey(Long id) { return publicInformationModelMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKey(PublicInformationModel record) { return publicInformationModelMapper.updateByPrimaryKey(record); } @Override public int updateByPrimaryKeySelective(PublicInformationModel record) { return publicInformationModelMapper.updateByPrimaryKeySelective(record); } @Override public Pagination<PublicInformationModel> findPage(Map<String, Object> resultMap, Integer pageNo, Integer pageSize) { return super.findPage(resultMap, pageNo, pageSize); } @Override public Map<String, Object> deletePublicInfoById(Long id) { Map<String,Object> resultMap = new HashMap<String,Object>(); try { String resultMsg = "删除成功。"; this.deleteByPrimaryKey(id); resultMap.put("status", 200); resultMap.put("resultMsg", resultMsg); } catch (Exception e) { LoggerUtils.fmtError(getClass(), e, "根据IDS删除用户出现错误,id[%s]", id); resultMap.put("status", 500); resultMap.put("message", "删除出现错误,请刷新后再试!"); } return resultMap; } // @Override // public Set<String> findCommunityByUserId(Long userId) { // return communityModelMapper.findCommunityByUserId(userId); // } }
package logger.writer; import logger.sink.ISink; public abstract class AbstractWriter { final ISink sink; public AbstractWriter(ISink sink) { this.sink = sink; } public abstract void logWrite(String message); }
/* * 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.main.controller; import com.main.model.Feedback; import com.main.service.AllInsertService; import com.main.service.AllUpdateService; import com.main.service.AllViewService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; /** * * @author krisenla */ @Controller public class FeedbackController { @Autowired AllViewService viewService; @Autowired AllInsertService insertService; @Autowired AllUpdateService updateService; @Autowired Environment env; // feature: feedback grid view @RequestMapping(value = "fbgridLink") public ModelAndView fbgridLink(@RequestParam(value = "customerid") String customerid) { ModelAndView modelAndView = new ModelAndView("ViewFeedbackGrid"); modelAndView.addObject("fbListDetails", viewService.getanyjdbcdatalist("SELECT fb.id as fbid,fb.status as fbstatus,inv.*,cu.name as customername,bd.vehiclename as model,br.name as brand FROM feedback fb\n" + "inner join invoice inv on inv.id=fb.invoiceid\n" + "inner join customer cu on cu.mobilenumber=inv.customermobilenumber \n" + "inner join branddetails bd on bd.id=inv.vehicleid\n" + "inner join brand br on br.id=bd.brandid\n" + "where cu.id='"+customerid+"' and inv.isdelete='No' and fb.isdelete='No' and cu.isdelete='No' and bd.isdelete='No' and br.isdelete='No' \n" + "order by fb.savedate desc")); return modelAndView; } //user feedback questionairpage @RequestMapping(value = "userFeedbackLink") public ModelAndView userFeedbackLink(@RequestParam(value = "fbid") String fbid) { ModelAndView modelAndView = new ModelAndView("AddFeedback"); modelAndView.addObject("invoicedtls", viewService.getanyjdbcdatalist("SELECT fb.id as fbid,fb.status as fbstatus,inv.*,cu.id as customerid,cu.name as customername,bd.vehiclename as model,br.name as brand FROM feedback fb\n" + "inner join invoice inv on inv.id=fb.invoiceid\n" + "inner join customer cu on cu.mobilenumber=inv.customermobilenumber\n" + "inner join branddetails bd on bd.id=inv.vehicleid\n" + "inner join brand br on br.id=bd.brandid\n" + "where fb.id='" + fbid + "'").get(0)); modelAndView.addObject("followuphistorydetails", viewService.getanyhqldatalist("FROM followups where type='feedback' and feedbackid='" + fbid + "'")); return modelAndView; } //add feedback @RequestMapping(value = "insertFeedback") public String insertFeedback(@ModelAttribute Feedback feedback,@RequestParam(value = "customerid") String customerid) { feedback.setStatus("complete"); updateService.update(feedback); return "redirect:fbgridLink?customerid="+customerid; } }
package co.paikama.wfa; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientRequest; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.ExchangeFunction; import org.springframework.web.reactive.function.client.ExchangeFunctions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.net.URI; import java.util.List; import static co.paikama.wfa.Server.HOST; import static co.paikama.wfa.Server.PORT; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpMethod.POST; public class Client { private final ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector()); public static void main(String[] args) { final Client client = new Client(); client.createPerson(); client.printAllPeople(); } private void createPerson() { final URI uri = URI.create(String.format("http://%s:%d/person", HOST, PORT)); final Person jackDoe = new Person("Jack Doe", 16); final ClientRequest request = ClientRequest.method(POST, uri) .body(BodyInserters.fromObject(jackDoe)).build(); final Mono<ClientResponse> responseMono = exchange.exchange(request); System.out.println(responseMono.block().statusCode()); } private void printAllPeople() { final URI uri = URI.create(String.format("http://%s:%d/person", HOST, PORT)); final ClientRequest request = ClientRequest.method(GET, uri).build(); final Flux<Person> peopleFlux = exchange.exchange(request) .flatMapMany(clientResponse -> clientResponse.bodyToFlux(Person.class)); final Mono<List<Person>> peopleListMono = peopleFlux.collectList(); System.out.println(peopleListMono.block()); } }
/** * Déclaration de la classe Commande : */ package entities.model; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name="commandes") public class Commande implements Serializable { /** * ----------------les attributs : */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id_commande") private long idCommande; @Column(name="date_commande") private Date dateCommande; /** * déclaration des liaisons : */ /** * liaison entre commandes et clients : */ @ManyToOne @JoinColumn(name="client_id_fk", referencedColumnName="id_client") private Client client; /** * liaison entre commande et panier */ @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="panier_id_fk", referencedColumnName="id_panier") private Panier panier; /** * --------------Constructeurs : */ /** * un vide */ public Commande() { super(); } /** * un avec la date * @param dateCommande */ public Commande(Date dateCommande) { super(); this.dateCommande = dateCommande; } /** * un complet * @param idCommande * @param dateCommande */ public Commande(long idCommande, Date dateCommande) { super(); this.idCommande = idCommande; this.dateCommande = dateCommande; } /** * getter et setters -----------------: * @return */ public long getIdCommande() { return idCommande; } public void setIdCommande(long idCommande) { this.idCommande = idCommande; } public Date getDateCommande() { return dateCommande; } public void setDateCommande(Date dateCommande) { this.dateCommande = dateCommande; } public Panier getPanier() { return panier; } public void setPanier(Panier panier) { this.panier = panier; } /** * clients * @return */ public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } /** * -------------------------les méthodes : */ /** * réecriture toString */ @Override public String toString() { return "Commande [idCommande=" + idCommande + ", dateCommande=" + dateCommande + "]"; } }
package com.tencent.mm.plugin.appbrand.jsapi.audio; import com.tencent.mm.g.a.s; import com.tencent.mm.plugin.appbrand.jsapi.e; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.plugin.appbrand.media.a.f; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.z.a; import com.tencent.mm.z.b; import com.tencent.mm.z.d; class j$c extends a { public String appId = ""; public String bGW = ""; public String dGC = ""; public int dGs = 0; public boolean dGu = false; public boolean dGv = false; public double dGx; private e fFF; public l fFa; public int fFd; public String fHW; public boolean fHX = false; public String ffK; public String processName = ""; public j$c(e eVar, l lVar, int i) { this.fFF = eVar; this.fFa = lVar; this.fFd = i; } public final void ahW() { x.i("MicroMsg.Audio.JsApiSetAudioState", "SetAudioTask runTask"); this.fHX = false; this.fHW = ""; a jE = b.jE(this.bGW); a aVar = new a(); aVar.bGW = this.bGW; aVar.cfD = this.dGC; aVar.dGs = this.dGs; aVar.dGt = this.dGs; aVar.dGu = this.dGu; aVar.dGv = this.dGv; aVar.processName = this.processName; aVar.dGx = this.dGx; aVar.appId = this.appId; aVar.fromScene = 0; s sVar; if (jE != null && this.dGC.equalsIgnoreCase(jE.cfD) && b.jD(this.bGW)) { x.i("MicroMsg.Audio.JsApiSetAudioState", "same src is playing audio, not to start again, but setAudioParam to update"); x.i("MicroMsg.AudioPlayerHelper", "setAudioParam, audioId:%s, src:%s", new Object[]{aVar.bGW, aVar.cfD}); sVar = new s(); sVar.bGU.action = 18; sVar.bGU.bGW = aVar.bGW; sVar.bGU.bGY = aVar; com.tencent.mm.sdk.b.a.sFg.m(sVar); if (!sVar.bGV.bGZ) { this.fHX = true; this.fHW = "not to set audio param, the audioId is err"; x.e("MicroMsg.Audio.JsApiSetAudioState", "not to set audio param, the audioId is err"); } En(); return; } x.i("MicroMsg.Audio.JsApiSetAudioState", "appId:%s, audioId:%s, src:%s, startTime:%d", new Object[]{this.appId, this.bGW, this.dGC, Integer.valueOf(this.dGs)}); if (this.dGC.startsWith("wxfile://")) { aVar.filePath = this.dGC.substring(9); x.i("MicroMsg.Audio.JsApiSetAudioState", "filePath:%s", new Object[]{aVar.filePath}); } else if (!(this.dGC.startsWith("http://") || this.dGC.startsWith("https://"))) { d bD = f.bD(this.dGC, this.ffK); if (bD.isOpen()) { aVar.filePath = this.dGC; aVar.dGy = bD; } else { this.fHX = true; this.fHW = "the file not exist for src"; x.e("MicroMsg.Audio.JsApiSetAudioState", "the wxa audioDataSource not found for src %s", new Object[]{this.dGC}); En(); return; } } En(); if (!this.fHX) { x.d("MicroMsg.AudioPlayerHelper", "startAudio, audioId:%s", new Object[]{aVar.bGW}); sVar = new s(); sVar.bGU.action = 0; sVar.bGU.bGW = aVar.bGW; sVar.bGU.bGY = aVar; com.tencent.mm.sdk.b.a.sFg.m(sVar); } } public final void En() { super.En(); if (this.fFa == null) { x.e("MicroMsg.Audio.JsApiSetAudioState", "server is null"); } else if (this.fHX) { this.fFa.E(this.fFd, this.fFF.f("fail:" + this.fHW, null)); } else { this.fFa.E(this.fFd, this.fFF.f("ok", null)); } } }
package com.dealership.entity; // Generated 2015-2-19 12:56:59 by Hibernate Tools 3.4.0.CR1 import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * TUser generated by hbm2java */ @JsonIgnoreProperties({"userGroup","orders"}) @Entity @Table(name = "t_user", uniqueConstraints = { @UniqueConstraint(columnNames = "username"), @UniqueConstraint(columnNames = "email") }) public class User implements java.io.Serializable { private Integer userId; @ManyToOne(fetch = FetchType.LAZY) private UserGroup userGroup; private String username; private String password; private String email; private Date registTime; private Set<Order> orders = new HashSet<Order>(0); public User() { } public User(UserGroup userGroup, String username, String password, String email, Date registTime) { this.userGroup = userGroup; this.username = username; this.password = password; this.email = email; this.registTime = registTime; } public User(UserGroup userGroup, String username, String password, String email, Date registTime, Set<Order> Orders) { this.userGroup = userGroup; this.username = username; this.password = password; this.email = email; this.registTime = registTime; this.orders = Orders; } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "user_id", unique = true, nullable = true) public Integer getUserId() { return this.userId; } public void setUserId(Integer userId) { this.userId = userId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_group_id", nullable = false) public UserGroup getUserGroup() { return this.userGroup; } public void setUserGroup(UserGroup UserGroup) { this.userGroup = UserGroup; } @Column(name = "username", unique = true, nullable = false, length = 20) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Column(name = "password", nullable = false, length = 20) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Column(name = "email", unique = true, nullable = false, length = 20) public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "regist_time", nullable = false, length = 19) public Date getRegistTime() { return this.registTime; } public void setRegistTime(Date registTime) { this.registTime = registTime; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") public Set<Order> getOrders() { return this.orders; } public void setOrders(Set<Order> Orders) { this.orders = Orders; } }
package Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; //it is simplar to HashMap,but it is synchronised // stores the values on the key and value format // key----->object ----Hashcode----> value public class HashTableConcept { public static void main(String[] args) { Hashtable h1 = new Hashtable(); h1.put(1, "Tom"); h1.put(2, "Test"); h1.put(3, "JAVA"); // create a clone copy/shallow copy Hashtable h2 = new Hashtable(); h2 = (Hashtable) h1.clone(); System.out.println("the value of h1" + h1); System.out.println("the value of h2" + h2); h1.clear(); System.out.println("the value of h1" + h1); System.out.println("the value of h2" + h2); // contains value Hashtable st = new Hashtable(); st.put("A", "ANAND"); st.put("B", "RAVI"); st.put("c", "DON"); if (st.contains("ANAND")) { System.out.println("Value is found"); // print all the vlaues from hashtable by using - Enumeration -element() Enumeration e = st.elements(); System.out.println("Print values from st using Enumeration"); while (e.hasMoreElements()) { System.out.println(e.nextElement()); } // get all the values from hashtable by using entrySet()--- set of hashtable // values: System.out.println("Print values from st using entrySet()"); Set s = st.entrySet(); System.out.println(s); Hashtable st1 = new Hashtable(); st1.put("A", "ANAND"); st1.put("B", "RAVI"); // st1.put("D",null)// null pointer exeception st1.put("C", "DON"); // st1.put("C", "DON"); it contais only unique values // check both the hashtable are equal or not : if (st.equals(st1)) { System.out.println("Both are equal"); } // get the values from a key System.out.println(st.get("A")); // get the hashcode of shahtable object: System.out.println("the hashcode value of the objct st 1 is " + st1.hashCode()); } } }
package jp.smartcompany.job.modules.core.pojo.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import jp.smartcompany.job.modules.base.pojo.entity.BaseBean; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; import java.util.Date; /** * @author Xiao Wenpeng */ @TableName("t_access_audit") @ToString @Getter @Setter @Accessors(chain = true) @EqualsAndHashCode(of = "auditId",callSuper = true) public class AccessAuditDO extends BaseBean { @TableId private Long auditId; private String url; private String method; private Integer status; private Long time; private String ip; private Date requestTime; private Date responseTime; }
package uk.ac.ucl.umobile; import android.Manifest; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.messaging.FirebaseMessaging; import com.intel.jndn.management.types.FaceStatus; import com.intel.jndn.management.types.RibEntry; //import uk.ac.ucl.umobile.backend.VideoListService; import uk.ac.ucl.umobile.ui.fragments.FaceListFragment; import uk.ac.ucl.umobile.ui.fragments.FaceStatusFragment; import uk.ac.ucl.umobile.ui.fragments.LogcatFragment; import uk.ac.ucl.umobile.ui.fragments.LogcatSettingsFragment; import uk.ac.ucl.umobile.ui.fragments.RouteInfoFragment; import uk.ac.ucl.umobile.ui.fragments.RouteListFragment; import uk.ac.ucl.umobile.ui.fragments.ServiceFragment; import uk.ac.ucl.umobile.ui.fragments.DrawerFragment; import uk.ac.ucl.umobile.ui.fragments.SettingsFragment; import uk.ac.ucl.umobile.ui.fragments.list.kiosk.KioskFragment; import uk.ac.ucl.umobile.utils.G; import java.util.ArrayList; //import static uk.ac.ucl.umobile.backend.NotificationService.NEW_VIDEO; /** * Created by srenevic on 24/08/17. * * Main activity of the ubicdn app * */ public class MainActivity extends AppCompatActivity implements DrawerFragment.DrawerCallbacks, LogcatFragment.Callbacks, FaceListFragment.Callbacks, RouteListFragment.Callbacks //VideoListFragment.Callbacks*/ { ////////////////////////////////////////////////////////////////////////////// /** Reference to drawer fragment */ private DrawerFragment m_drawerFragment; public static final boolean DEBUG = true; /** Title that is to be displayed in the ActionBar */ private int m_actionBarTitleId = -1; /** Item code for drawer items: For use in onDrawerItemSelected() callback */ public static final int DRAWER_ITEM_GENERAL = 1; public static final int DRAWER_ITEM_NFD = 2; public static final int DRAWER_ITEM_FACES = 3; public static final int DRAWER_ITEM_ROUTES = 4; // public static final int DRAWER_ITEM_STRATEGIES = 4; public static final int DRAWER_ITEM_LOGCAT = 5; public static final int DRAWER_ITEM_SETTINGS = 6; private ProgressDialog mProgressDialog; private static final String TAG = "MainActivity"; // private FirebaseAuth mAuth; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1; private static final int PERMISSION_REQUEST_READ_EXTERNAL_STORAGE = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Intent intent = new Intent(this, VideoListService.class); // startService(intent); // FirebaseMessaging.getInstance().subscribeToTopic("news"); Log.d("Main", "subscribed to topic news"); FragmentManager fragmentManager = getSupportFragmentManager(); //mAuth = FirebaseAuth.getInstance(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION); } }); builder.show(); } if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle("This app needs location access"); // builder.setMessage("Please grant location access"); // builder.setPositiveButton(android.R.string.ok, null); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_READ_EXTERNAL_STORAGE); } }); builder.show(); } } if (savedInstanceState != null) { m_drawerFragment = (DrawerFragment)fragmentManager.findFragmentByTag(DrawerFragment.class.toString()); } if (m_drawerFragment == null) { ArrayList<DrawerFragment.DrawerItem> items = new ArrayList<DrawerFragment.DrawerItem>(); items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_general, 0, DRAWER_ITEM_GENERAL)); items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_service, 0, DRAWER_ITEM_NFD)); items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_settings, 0, DRAWER_ITEM_SETTINGS)); items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_logcat, 0, DRAWER_ITEM_LOGCAT)); items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_faces, 0, DRAWER_ITEM_FACES)); items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_routes, 0, DRAWER_ITEM_ROUTES)); // items.add(new DrawerFragment.DrawerItem(R.string.drawer_item_strategies, 0, // DRAWER_ITEM_STRATEGIES)); m_drawerFragment = DrawerFragment.newInstance(items); fragmentManager .beginTransaction() .replace(R.id.navigation_drawer, m_drawerFragment, DrawerFragment.class.toString()) .commit(); } } @Override public void onStart() { super.onStart(); //signInAnonymously(); G.Log(TAG,"onstart"); /* if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { Object value = getIntent().getExtras().get(key); Log.d(TAG, "Key: " + key + " Value: " + value); } String video = getIntent().getStringExtra("title"); String desc = getIntent().getStringExtra("desc"); String url = getIntent().getStringExtra("url"); String action = NEW_VIDEO; Intent broadcast = new Intent(action) .putExtra("title", video) .putExtra("desc", desc) .putExtra("url", url); sendBroadcast(broadcast); }*/ } @Override public boolean onCreateOptionsMenu(Menu menu) { Log.d(TAG,"onCreateOptionsMenu" + String.valueOf(m_drawerFragment.shouldHideOptionsMenu())); if (!m_drawerFragment.shouldHideOptionsMenu()) { updateActionBar(); return super.onCreateOptionsMenu(menu); } else return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } ////////////////////////////////////////////////////////////////////////////// /** * Convenience method that updates and display the current title in the Action Bar */ @SuppressWarnings("deprecation") private void updateActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); if (m_actionBarTitleId != -1) { actionBar.setTitle(m_actionBarTitleId); } } /** * Convenience method that replaces the main fragment container with the * new fragment and adding the current transaction to the backstack. * * @param fragment Fragment to be displayed in the main fragment container. */ private void replaceContentFragmentWithBackstack(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) .replace(R.id.main_fragment_container, fragment) .addToBackStack(null) .commit(); } ////////////////////////////////////////////////////////////////////////////// @Override public void onDrawerItemSelected(int itemCode, int itemNameId) { String fragmentTag = "org.schabi.newpipe.content-" + String.valueOf(itemCode); FragmentManager fragmentManager = getSupportFragmentManager(); // Create fragment according to user's selection Fragment fragment = fragmentManager.findFragmentByTag(fragmentTag); if (fragment == null) { switch (itemCode) { case DRAWER_ITEM_GENERAL: // fragment = VideoListFragment.newInstance(); try { fragment = KioskFragment.getInstance(0,"Trending"); } catch (Exception e) {} break; case DRAWER_ITEM_NFD: fragment = ServiceFragment.newInstance(); break; case DRAWER_ITEM_FACES: fragment = FaceListFragment.newInstance(); break; case DRAWER_ITEM_ROUTES: fragment = RouteListFragment.newInstance(); break; // TODO: Placeholders; Fill these in when their fragments have been created // case DRAWER_ITEM_STRATEGIES: // break; case DRAWER_ITEM_LOGCAT: fragment = LogcatFragment.newInstance(); break; case DRAWER_ITEM_SETTINGS: fragment = SettingsFragment.newInstance(); break; default: // Invalid; Nothing else needs to be done return; } } // Update ActionBar title m_actionBarTitleId = itemNameId; fragmentManager.beginTransaction() .replace(R.id.main_fragment_container, fragment, fragmentTag) .commit(); } private void showProgressDialog(String caption) { mProgressDialog = new ProgressDialog(this); final String msg = caption; new Thread() { public void run() { MainActivity.this.runOnUiThread(new Runnable() { public void run() { if (mProgressDialog == null) { mProgressDialog.setIndeterminate(true); } mProgressDialog.setMessage(msg); mProgressDialog.show(); } }); } }.start(); } @Override public void onDisplayLogcatSettings() { replaceContentFragmentWithBackstack(LogcatSettingsFragment.newInstance()); } @Override public void onFaceItemSelected(FaceStatus faceStatus) { replaceContentFragmentWithBackstack(FaceStatusFragment.newInstance(faceStatus)); } @Override public void onRouteItemSelected(RibEntry ribEntry) { replaceContentFragmentWithBackstack(RouteInfoFragment.newInstance(ribEntry)); } /*@Override public void onVideoItemSelected(String videoEntry) { replaceContentFragmentWithBackstack(VideoFragment.newInstance(videoEntry)); }*/ /*private void signInAnonymously() { // Sign in anonymously. Authentication is required to read or write from Firebase Storage. showProgressDialog(getString(R.string.progress_auth)); mAuth.signInAnonymously() .addOnSuccessListener(this, new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { Log.d(TAG, "signInAnonymously:SUCCESS"); hideProgressDialog(); updateUI(authResult.getUser()); } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Log.e(TAG, "signInAnonymously:FAILURE", exception); hideProgressDialog(); updateUI(null); } }); }*/ /* private void updateUI(FirebaseUser user) { // Signed in or Signed out if(user==null) { String msg = "Unable to athenticate to notifications server"; Log.d(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } } private void hideProgressDialog() { new Thread() { public void run() { MainActivity.this.runOnUiThread(new Runnable() { public void run() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } }); } }.start(); } public static IntentFilter getIntentFilter() { IntentFilter filter = new IntentFilter(); filter.addAction(NEW_VIDEO); return filter; }*/ }
package com.hb.rssai.bean; import java.util.List; /** * Created by Administrator on 2017/8/18 0018. */ public class ResDataGroup { /** * retObj : {"total":7,"rows":[{"val":1,"deleteFlag":false,"name":"新闻","id":"783a53b2-836e-11e7-a746-206a8a32e7b2"},{"val":2,"deleteFlag":false,"name":"科技","id":"86a5bfb1-836e-11e7-a746-206a8a32e7b2"},{"val":3,"deleteFlag":false,"name":"探索","id":"8d9a822f-836e-11e7-a746-206a8a32e7b2"},{"val":4,"deleteFlag":false,"name":"军事","id":"95b777a3-836e-11e7-a746-206a8a32e7b2"},{"val":5,"deleteFlag":false,"name":"娱乐","id":"9bd0b519-836e-11e7-a746-206a8a32e7b2"},{"val":6,"deleteFlag":false,"name":"数码","id":"a2616aa0-836e-11e7-a746-206a8a32e7b2"},{"val":7,"deleteFlag":false,"name":"游戏","id":"a650262d-836e-11e7-a746-206a8a32e7b2"}]} * retCode : 0 * retMsg : 操作成功 */ private RetObjBean retObj; private int retCode; private String retMsg; public RetObjBean getRetObj() { return retObj; } public void setRetObj(RetObjBean retObj) { this.retObj = retObj; } public int getRetCode() { return retCode; } public void setRetCode(int retCode) { this.retCode = retCode; } public String getRetMsg() { return retMsg; } public void setRetMsg(String retMsg) { this.retMsg = retMsg; } public static class RetObjBean { /** * total : 7 * rows : [{"val":1,"deleteFlag":false,"name":"新闻","id":"783a53b2-836e-11e7-a746-206a8a32e7b2"},{"val":2,"deleteFlag":false,"name":"科技","id":"86a5bfb1-836e-11e7-a746-206a8a32e7b2"},{"val":3,"deleteFlag":false,"name":"探索","id":"8d9a822f-836e-11e7-a746-206a8a32e7b2"},{"val":4,"deleteFlag":false,"name":"军事","id":"95b777a3-836e-11e7-a746-206a8a32e7b2"},{"val":5,"deleteFlag":false,"name":"娱乐","id":"9bd0b519-836e-11e7-a746-206a8a32e7b2"},{"val":6,"deleteFlag":false,"name":"数码","id":"a2616aa0-836e-11e7-a746-206a8a32e7b2"},{"val":7,"deleteFlag":false,"name":"游戏","id":"a650262d-836e-11e7-a746-206a8a32e7b2"}] */ private int total; private List<RowsBean> rows; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<RowsBean> getRows() { return rows; } public void setRows(List<RowsBean> rows) { this.rows = rows; } public static class RowsBean { /** * val : 1 * deleteFlag : false * name : 新闻 * id : 783a53b2-836e-11e7-a746-206a8a32e7b2 */ private int val; private boolean deleteFlag; private String name; private String id; private String url; private int groupType; private int maxVal; private int progressVal; public int getVal() { return val; } public void setVal(int val) { this.val = val; } public boolean isDeleteFlag() { return deleteFlag; } public void setDeleteFlag(boolean deleteFlag) { this.deleteFlag = deleteFlag; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getGroupType() { return groupType; } public void setGroupType(int groupType) { this.groupType = groupType; } public int getProgressVal() { return progressVal; } public void setProgressVal(int progressVal) { this.progressVal = progressVal; } public int getMaxVal() { return maxVal; } public void setMaxVal(int maxVal) { this.maxVal = maxVal; } } } }
package com.accp.pub.pojo; import java.util.Date; public class dorm { private Integer dormid; private String dormname; private Integer domainid; private Integer loucheng; private Integer userid; private Integer dormsex; private Integer berthcount; private Integer yingcount; private Integer kecount; private String berthstate; private Integer operatorid; private String operator; private Date operatortime; private Integer state; private Integer beiyong1; private String beiyong2; private String beiyong3; public Integer getDormid() { return dormid; } public void setDormid(Integer dormid) { this.dormid = dormid; } public String getDormname() { return dormname; } public void setDormname(String dormname) { this.dormname = dormname == null ? null : dormname.trim(); } public Integer getDomainid() { return domainid; } public void setDomainid(Integer domainid) { this.domainid = domainid; } public Integer getLoucheng() { return loucheng; } public void setLoucheng(Integer loucheng) { this.loucheng = loucheng; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public Integer getDormsex() { return dormsex; } public void setDormsex(Integer dormsex) { this.dormsex = dormsex; } public Integer getBerthcount() { return berthcount; } public void setBerthcount(Integer berthcount) { this.berthcount = berthcount; } public Integer getYingcount() { return yingcount; } public void setYingcount(Integer yingcount) { this.yingcount = yingcount; } public Integer getKecount() { return kecount; } public void setKecount(Integer kecount) { this.kecount = kecount; } public String getBerthstate() { return berthstate; } public void setBerthstate(String berthstate) { this.berthstate = berthstate == null ? null : berthstate.trim(); } public Integer getOperatorid() { return operatorid; } public void setOperatorid(Integer operatorid) { this.operatorid = operatorid; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator == null ? null : operator.trim(); } public Date getOperatortime() { return operatortime; } public void setOperatortime(Date operatortime) { this.operatortime = operatortime; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Integer getBeiyong1() { return beiyong1; } public void setBeiyong1(Integer beiyong1) { this.beiyong1 = beiyong1; } public String getBeiyong2() { return beiyong2; } public void setBeiyong2(String beiyong2) { this.beiyong2 = beiyong2 == null ? null : beiyong2.trim(); } public String getBeiyong3() { return beiyong3; } public void setBeiyong3(String beiyong3) { this.beiyong3 = beiyong3 == null ? null : beiyong3.trim(); } }
package com.tomek.controller; import com.tomek.data.Animal; import com.tomek.data.Dog; import com.tomek.util.ConnectionProvider; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ListServlet extends HttpServlet { private NamedParameterJdbcTemplate template; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Dog> animalList = getAnimals(); request.setAttribute("animalList", animalList); request.getRequestDispatcher("animalList.jsp").forward(request, response); } private List<Dog> getAnimals() { template = new NamedParameterJdbcTemplate(ConnectionProvider.getDSInstance()); String query = "SELECT Name, Race, Age, isFetching, isPurebred FROM dog"; List<Dog> animaList = template.query(query, BeanPropertyRowMapper.newInstance(Dog.class)); return animaList; } }
/** * @author * This is a base class which other base classes will extend to get the driver instance */ package com.scholastic.torque.pageobjects; import org.openqa.selenium.WebDriver; public abstract class BaseClass { public static WebDriver driver; public static boolean bResult; //Constructor public BaseClass(WebDriver driver){ BaseClass.driver = driver; BaseClass.bResult = true; } }
package com.example.flutter_module.host; import android.os.Bundle; import android.os.PersistableBundle; import org.jetbrains.annotations.NotNull; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.engine.FlutterEngine; public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(@NonNull @NotNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); flutterEngine.getPlugins().add(new HJPlugin()); } }
package woc.assignment.one; public class SumNumbers { public static void main(String[] args) { Integer result = 0; for(int i=0;i<args.length;i++) result += Integer.valueOf(args[i]); System.out.println(result); } }
package src.core.java.demo.wrapper; /** * Primitive type ---> [Wrapper class] ---> Object type * * Each data has respective primitive class * byte --> {@link Byte} * short --> {@link Short} * int --> {@link Integer} * char --> Character * long --> {@link Long} * double -->{@link Double} */ /** * wrapper classes are used for converting * 1. Primitive to Object --> Boxing * 2. Object to Primitive --> unboxing * 3. Primitive to String --> * 4. Sting to Primitive * 5. Object to String * 6. String to Object * */
package cn.edu.sdjzu.xg.bysj.service; import cn.edu.sdjzu.xg.bysj.dao.ActorDao; import cn.edu.sdjzu.xg.bysj.domain.authority.Actor; import lombok.Cleanup; import util.JdbcHelper; import java.sql.Connection; import java.sql.SQLException; public final class ActorService { private static ActorDao actorDao = ActorDao.getInstance(); private static ActorService actorService = new ActorService(); public static ActorService getInstance() { return actorService; } // 不会查找一个Actor集合 // 不会增加一个Actor // 不会修改一个Actor // 不会删除一个Actor public Actor find(Integer id) throws SQLException { @Cleanup Connection connection = JdbcHelper.getConn(); Actor actor = actorDao.find(id, connection); return actor; } }
package com.lr; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.HashMap; import java.util.Map; @SpringBootApplication (scanBasePackages = "com.lr") @MapperScan ("com.lr.mapper") //@EnableCaching @EnableTransactionManagement public class app{ /*" @Bean public ServletRegistrationBean servletRegistrationBean(DispatcherServlet dispatcherServlet) { ServletRegistrationBean bean = new ServletRegistrationBean(dispatcherServlet); bean.addUrlMappings("*.action"); return bean; } */ // @Bean // public CacheManager cacheManager(RedisTemplate redisTemplate) { // RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // cacheManager.setDefaultExpiration(60); // Map<String, Long> expiresMap = new HashMap<>(); // expiresMap.put("product", 5L); // cacheManager.setExpires(expiresMap); // return cacheManager; // } public static void main(String[] args) { SpringApplication.run(app.class, args); } }
package org.motechproject.server.svc; import org.motechproject.server.model.MessageProgram; public interface MessageProgramService { MessageProgram program(String programName); }
package com.hason.dtp.account.point.service; /** * 积分业务接口 * * @author Huanghs * @since 2.0 * @date 2017/11/15 */ public interface PointService { /** * (幂等)为新注册用户增加积分 * * @param userId 用户ID * @param add 增加的积分 * @return User */ void addRegistPoint(Long userId, int add); }
package com.koreait.model; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.koreait.dao.MemberDao; import com.koreait.dto.MemberDto; public class JoinAction implements Action { @Override public String command(HttpServletRequest request, HttpServletResponse response) { MemberDto mDto = new MemberDto(); mDto.setmId(request.getParameter("mId")); mDto.setmPw(request.getParameter("mPw")); mDto.setmName(request.getParameter("mName")); mDto.setmEmail(request.getParameter("mEmail")); mDto.setmPhone(request.getParameter("mPhone")); MemberDao mDao = MemberDao.getInstance(); int result = mDao.getInsertMember(mDto); request.setAttribute("result", result); // 보여줄 곳에 파라미터로 전달 return "join/joinResultPage.jsp"; // 보여줄 곳 ! } }
package jiwoo.roomBoard; import jiwoo.database.DBcon; import java.sql.SQLException; public class roomBoard { public DBcon db; public roomBoard(){ db = new DBcon(); } public void insertReview(String title, String content){ String sql = "Insert into roomboard (title,content,views,uid) values(?,?,?,?)"; try{ db.pstmt = db.con.prepareStatement(sql); db.pstmt.setString(1, title); db.pstmt.setString(2, content); db.pstmt.setString(3, "0"); db.pstmt.setString(4, "0"); db.pstmt.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } } }
/* * UniTime 3.2 - 3.5 (University Timetabling Application) * Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.timetable.action; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import org.cpsolver.ifs.util.DataProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.form.ExamSolverForm; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.dao.SessionDAO; import org.unitime.timetable.security.SessionContext; import org.unitime.timetable.security.rights.Right; import org.unitime.timetable.solver.exam.ExamSolverProxy; import org.unitime.timetable.solver.jgroups.SolverServer; import org.unitime.timetable.solver.service.SolverServerService; import org.unitime.timetable.solver.service.SolverService; import org.unitime.timetable.util.ExportUtils; import org.unitime.timetable.util.LookupTables; import org.unitime.timetable.util.RoomAvailability; /** * @author Tomas Muller */ @Service("/examSolver") public class ExamSolverAction extends Action { @Autowired SolverService<ExamSolverProxy> examinationSolverService; @Autowired SessionContext sessionContext; @Autowired SolverServerService solverServerService; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ExamSolverForm myForm = (ExamSolverForm) form; // Check Access sessionContext.checkPermission(Right.ExaminationSolver); if (sessionContext.getUser().getCurrentAuthority().hasRight(Right.CanSelectSolverServer)) { List<String> hosts = new ArrayList<String>(); for (SolverServer server: solverServerService.getServers(true)) hosts.add(server.getHost()); Collections.sort(hosts); if (ApplicationProperty.SolverLocalEnabled.isTrue()) hosts.add(0, "local"); hosts.add(0, "auto"); request.setAttribute("hosts", hosts); } // Read operation to be performed String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op")); ExamSolverProxy solver = examinationSolverService.getSolver(); Session acadSession = SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId()); RoomAvailability.setAvailabilityWarning(request, acadSession, (solver==null?myForm.getExamType():solver.getExamTypeId()), true, false); LookupTables.setupExamTypes(request, sessionContext.getUser().getCurrentAcademicSessionId()); if (op==null) { myForm.init("y".equals(request.getParameter("reload"))); return mapping.findForward("showSolver"); } if ("Export XML".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); sessionContext.checkPermission(Right.ExaminationSolutionExportXml); byte[] buf = solver.exportXml(); OutputStream out = ExportUtils.getXmlOutputStream(response, "solution"); out.write(buf); out.flush(); out.close(); return null; } if ("Restore From Best".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); solver.restoreBest(); } if ("Store To Best".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); solver.saveBest(); } if (op.startsWith("Save")) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); solver.save(); } if ("Unload".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); examinationSolverService.removeSolver(); myForm.reset(mapping, request); myForm.init(false); } if ("Clear".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); solver.clear(); } // Reload if ("Reload Input Data".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isWorking()) throw new Exception("Solver is working, stop it first."); ActionMessages errors = myForm.validate(mapping, request); if(errors.size()>0) { saveErrors(request, errors); return mapping.findForward("showSolver"); } DataProperties config = examinationSolverService.createConfig(myForm.getSetting(), myForm.getParameterValues()); config.setProperty("Exam.Type", String.valueOf(myForm.getExamType())); request.getSession().setAttribute("Exam.Type", myForm.getExamType()); examinationSolverService.reload(config); } if ("Start".equals(op) || "Load".equals(op)) { boolean start = "Start".equals(op); if (solver!=null && solver.isWorking()) throw new Exception("Solver is working, stop it first."); ActionMessages errors = myForm.validate(mapping, request); if(errors.size()>0) { saveErrors(request, errors); return mapping.findForward("showSolver"); } DataProperties config = examinationSolverService.createConfig(myForm.getSetting(), myForm.getParameterValues()); config.put("Exam.Type", String.valueOf(myForm.getExamType())); config.put("General.StartSolver", new Boolean(start).toString()); request.getSession().setAttribute("Exam.Type", myForm.getExamType()); if (myForm.getHost() != null) config.setProperty("General.Host", myForm.getHost()); if (solver == null) { solver = examinationSolverService.createSolver(config); } else if (start) { solver.setProperties(config); solver.start(); } } if ("Stop".equals(op)) { if (solver==null) throw new Exception("Solver is not started."); if (solver.isRunning()) solver.stopSolver(); myForm.reset(mapping, request); myForm.init(false); } if ("Refresh".equals(op)) { myForm.reset(mapping, request); myForm.init(false); } return mapping.findForward("showSolver"); } }
package com.infotec.ses; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("cp") public class CpResource { CpRepositorio repo = new CpRepositorio(); @GET @Produces({MediaType.APPLICATION_JSON}) @Path("cpscol/{colonia}") public List<Cp> getCpColonia(@PathParam("colonia") String colonia) { System.out.println("Si corre!"); return repo.getCpColonia(colonia); } @GET @Produces({MediaType.APPLICATION_JSON}) @Path("cpscp/{cp}") public List<Cp> getCpInfo(@PathParam("cp") String cp) { System.out.println("Si corre!"); return repo.getCpInfo(cp); } }