blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
89e65de72372cda58ad40cd75316eedce566f388
Java
MREkstrom/FooTrace
/app/src/main/java/com/example/michael/footrace/FormatUtilities.java
UTF-8
839
2.453125
2
[]
no_license
package com.example.michael.footrace; import android.content.res.AssetManager; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.widget.TextView; /** * Created by Michael on 11/30/2016. * * Contains various formatting utilities for text found throughout the app. This is useful * for when text is generated outside of the XML, or a custom font is required */ public class FormatUtilities { //Generates a dialog text title with the given text public static TextView makeDialogTitle(TextView base, AssetManager assets, String text){ base.setText(text); base.setTypeface(Typeface.createFromAsset(assets, "mvboli.ttf")); base.setTextSize(25f); base.setGravity(Gravity.CENTER_HORIZONTAL); return base; } }
true
1c33ea08376232b38d3079873b79e63c4c69215c
Java
HenryR-226/UberChess499
/gradleproject1/src/main/java/gradleproject1/Move.java
UTF-8
10,672
3.265625
3
[]
no_license
package gradleproject1; /** * * @author Henry Rheault * * Move started as a specific type of string, eg, nE4, KG7. It has * changed to store the old and new board squares it was involving, it's * notation, and the piece that moved. */ public class Move { private BoardButton old; private int oldrow, oldcol; private BoardButton n3w; private int newrow, newcol; private String abbreviation; private Piece piece; private Piece captured = null; private boolean isWhite; private boolean capture = false; private static Player whitePlayer; private static Player blackPlayer; private static Board b; private static int movesWithoutCapture = 0; public Move(Piece p, BoardButton button, boolean thisIsAMoveGeneratorOnlyWillNotPushAMove) throws Exception { // Overloaded // boardbutton // to attempt a move to try { BoardButton[][] GameBoard = b.getGameBoard(); // Fetch gameboard object String s = p.getLocation(); char loc[] = s.toCharArray(); int i = (int) loc[0] - 'A'; // Number column int j = (int) loc[1] - '0' - 1; this.old = GameBoard[i][j]; //System.out.println("Calling remove on boardbutton" + i + " " + j); this.n3w = button; this.piece = p; String abbrev = n3w.getAbbreviation(); //System.out.println("Line 92 in Move, " + p.getAbbrev() + " moved from " + loc[0] + loc[1] + " to " + abbrev + "."); String move = String.valueOf(p.getAbbrev()); if (n3w.getPiece() != null) { move = move + "x"; // x means a piece captured the piece on it's destination square capture = true; this.captured = n3w.getPiece(); } move = move + abbrev; setAbbreviation(move); } catch (Exception e) { System.out.println("Invalid move constructor taking board square. Try again."); e.printStackTrace(); } } //Castle move. Called from above move method and then above move method will be crashed within the try-catch. Unless someone's paying //Religious attention to Console it shouldn't matter. public Move (King k, Rook r) { this.captured = r; this.piece = k; BoardButton[][] bb = b.getGameBoard(); int col1, row1, col2, row2; String s; col1 = k.getCol(); row1 = k.getRow(); col2 = r.getCol(); row2 = r.getRow(); BoardButton itr = bb[col1][row1]; if (!k.isWhite) { if (col1 - col2 > 0) { //King is castling LEFT k.setLocation("C8"); itr = bb[2][7]; this.n3w = itr; n3w.removePiece(); n3w.setPiece(k); r.setLocation("D8"); itr = bb[3][7]; this.old = itr; old.removePiece(); old.setPiece(r); itr = bb[4][7]; itr.removePiece(); itr = bb[0][7]; itr.removePiece(); s = "krk"; } else { //King is castling RIGHT k.setLocation("G8"); itr = bb[6][7]; this.n3w = itr; n3w.removePiece(); n3w.setPiece(k); r.setLocation("F8"); itr = bb[5][7]; this.old = itr; old.removePiece(); old.setPiece(r); s = "krq"; itr = bb[4][7]; itr.removePiece(); itr=bb[7][7]; itr.removePiece(); } } else { if (col1 - col2 > 0) { //King is castling LEFT k.setLocation("C1"); itr = bb[2][0]; this.n3w = itr; n3w.removePiece(); n3w.setPiece(k); r.setLocation("D1"); itr = bb[3][0]; this.old = itr; old.removePiece(); old.setPiece(r); s = "KRK"; itr = bb[4][0]; itr.removePiece(); itr = bb[0][0]; itr.removePiece(); } else { //King is castling RIGHT k.setLocation("G8"); itr = bb[6][0]; this.n3w = itr; n3w.removePiece(); n3w.setPiece(k); r.setLocation("F8"); itr = bb[5][0]; this.old = itr; old.removePiece(); old.setPiece(r); s = "KRQ"; itr = bb[4][0]; itr.removePiece(); itr = bb[7][0]; itr.removePiece(); } } movesWithoutCapture++; this.abbreviation = s; } public Move(Piece p, BoardButton button) throws Exception { // Overloaded constructor, simply declare a boardbutton // to attempt a move to try { BoardButton[][] GameBoard = b.getGameBoard(); // Fetch gameboard object boolean castle = false; if ((p.getAbbrev() == 'K' || p.getAbbrev() == 'k') && (Math.abs(button.getColumn() - p.getCol())>1)) { //This is a castle move int colDiff = button.getColumn() - p.getCol(); //This crashes with ArrayOutOfBoundsException to get out of standard move constructor. NOT BROKEN. Rook r = null; if (colDiff > 0) { //Castling right if (!p.isWhite) { r = (Rook) GameBoard[7][7].getPiece(); Move m = new Move((King)p, r); castle=true; } else { r = (Rook) GameBoard[0][0].getPiece(); Move m = new Move((King)p, r); castle = true; } } else { if (!p.isWhite) { r = (Rook) GameBoard[0][7].getPiece(); Move m = new Move((King)p, r); castle = true; } else { r = (Rook) GameBoard[0][0].getPiece(); Move m = new Move((King)p, r); castle = true; } } } if (!castle) { String s = p.getLocation(); char loc[] = s.toCharArray(); int i = (int) loc[0] - 'A'; // Number column int j = (int) loc[1] - '0' - 1; this.old = GameBoard[i][j]; this.n3w = button; this.piece = p; String abbrev = n3w.getAbbreviation(); System.out.println(p.getAbbrev() + " moved from " + loc[0] + loc[1] + " to " + abbrev + "."); String move = String.valueOf(p.getAbbrev()); if (n3w.getPiece() != null && n3w.getPiece().isWhite() != piece.isWhite()) { move = move + "x"; // x means a piece captured the piece on it's destination square capture = true; this.captured = n3w.getPiece(); movesWithoutCapture = 0; n3w.removePiece(piece); } else old.removePiece(); move = move + abbrev; setAbbreviation(move); if (p.isWhite()) { if (whitePlayer.inCheck()) // If we're in check, make sure this takes us out of check if (!whitePlayer.getKing().isInCheck(GameBoard, whitePlayer.getPieceList(), this.piece, this)) whitePlayer.removeCheck(); // else return null because you can't push this move whitePlayer.addMove(this); } else { if (blackPlayer.inCheck()) if (!blackPlayer.getKing().isInCheck(GameBoard, whitePlayer.getPieceList(), this.piece, this)) blackPlayer.removeCheck(); // else return null because you can't push this move blackPlayer.addMove(this); } String location = this.n3w.getAbbreviation(); // Update pawn first move field if (this.piece.getAbbrev() == 'p' || this.piece.getAbbrev() == 'P') { if (this.piece.firstMove()) { piece.madeFirstMove(); if (Math.abs(this.n3w.getRow() - this.old.getRow()) == 2) this.getPiece().incRank(); } if (this.piece.getRank() == 5 && ((Pawn) this.piece).canPromote()) { try { ((Pawn) this.piece).promote(); } catch (Exception e) { } } this.getPiece().incRank(); this.getPiece().madeFirstMove(); } old.removePiece(); n3w.setPiece(p); p.setLocation(location); if (p.getAbbrev() == 'p' || p.getAbbrev() == 'P') movesWithoutCapture = 0; // Stalemate!! if (movesWithoutCapture == 50 || (b.getBlackPlayer().getPieceList().size() == 1 && b.getWhitePlayer().getPieceList().size() == 1)) { System.out.println("50 move or King-only stalemate! Game's over. Line 171 Move"); Player.getGameState().setWinrar(null); Player.getGameState().setStalemate(); } } } catch (Exception e) { System.out.println("Invalid move constructor taking board square. Try again."); e.printStackTrace(); } } /** * Move constructor for pawn promotion only, straight up column */ public Move (Pawn p) { assert (p.getRow() == 6 || p.getRow() == 1); BoardButton[][] GameBoard = b.getGameBoard(); // Fetch gameboard object String s = p.getLocation(); char loc[] = s.toCharArray(); int i = (int) loc[0] - 'A'; // Number column int j = (int) loc[1] - '0' - 1; this.old = GameBoard[i][j]; if (p.isWhite) this.n3w = GameBoard[p.getCol()][7]; if (!p.isWhite) this.n3w = GameBoard[p.getCol()][0]; //this.piece = p; String abbrev = n3w.getAbbreviation(); String move = String.valueOf(p.getAbbrev()); movesWithoutCapture = 0; move = move + abbrev; setAbbreviation(move); Piece promoted = p.promote(); old.removePiece(); n3w.setPiece(promoted); this.piece = promoted; promoted.setLocation(abbrev); } //Overloaded, boolean true = steps RIGHT, false = steps LEFT public Move (Pawn p, boolean side) { assert (p.getRow() == 6 || p.getRow() == 1); BoardButton[][] GameBoard = b.getGameBoard(); // Fetch gameboard object String s = p.getLocation(); char loc[] = s.toCharArray(); int i = (int) loc[0] - 'A'; // Number column int j = (int) loc[1] - '0' - 1; this.old = GameBoard[i][j]; if (p.isWhite) { if (side) this.n3w = GameBoard[p.getCol()+1][7]; else this.n3w = GameBoard[p.getCol()-1][7]; } if (!p.isWhite) { if (side) this.n3w = GameBoard[p.getCol()+1][0]; else this.n3w = GameBoard[p.getCol()-1][0]; } //this.piece = p; String abbrev = n3w.getAbbreviation(); String move = String.valueOf(p.getAbbrev()); String x = "x"; movesWithoutCapture = 0; move = move + x + abbrev; if (n3w.isFull()) captured = n3w.getPiece(); setAbbreviation(move); Piece promoted = p.promote(); old.removePiece(); n3w.removePiece(promoted); n3w.setPiece(promoted); this.piece = promoted; promoted.setLocation(abbrev); } /** @author Henry Rheault * Generates and returns a move based on a input string. * Passed in * @throws Exception */ public Move newMove(Piece p, BoardButton button) throws Exception { Move m = new Move(p, button); return m; } // Get the boardbutton the move was FROM public BoardButton getOld() { return this.old; } // Get the boardbutton the move was TO public BoardButton getNew() { return this.n3w; } // Return string/algebraic notation public String getAbbreviation() { return this.abbreviation; } // To be updated: Make it take in args of char and do the operations/checks as // done in the Move constructors above // To be equivalent to proper Object Oriented form. IE: "no funky data" private void setAbbreviation(String s) { this.abbreviation = s; } public static void setGameBoard(Board board) { b = board; } public static void setWhitePlayer(Player whitey) { whitePlayer = whitey; } public static void setBlackPlayer(Player black) { blackPlayer = black; } public Piece getPiece() { return this.piece; } public Piece getCaptured() { return this.captured; } public boolean wasCaptured() { return capture; } }
true
3ef33cbc67e8e8c7c28f7ee7b5763358e8709931
Java
eladavron/CPS
/src/main/client/client/GUI/Forms/Customers/NewPreorder.java
UTF-8
4,731
2.390625
2
[]
no_license
package client.GUI.Forms.Customers; import client.GUI.CPSClientGUI; import client.GUI.Controls.DateTimeCombo; import client.GUI.Controls.WaitScreen; import client.GUI.Helpers.*; import entity.Message; import entity.ParkingLot; import entity.PreOrder; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import java.net.URL; import java.util.Date; import java.util.ResourceBundle; /** * A GUI controller for creating new Preorders. */ public class NewPreorder extends GUIController implements Initializable { @FXML private Button btnBack; @FXML private DatePicker entryDatePicker; @FXML private DatePicker exitDatePicker; @FXML private ComboBox<String> cmbEntryMinute; @FXML private ComboBox<String> cmbExitMinute; @FXML private ComboBox<String> cmbEntryHour; @FXML private ComboBox<String> cmbExitHour; @FXML private ComboBox<ParkingLot> cmbParkingLot; @FXML private ComboBox<Integer> cmbCarID; @FXML private Button btnCreate; @FXML private Label lblAvailability; private DateTimeCombo _entryDateTime; private DateTimeCombo _exitDateTime; /** * {@inheritDoc} */ @Override public void initialize(URL location, ResourceBundle resources) { btnBack.setTooltip(new Tooltip("Back")); Platform.runLater(new Runnable() { @Override public void run() { Inits.initCars(cmbCarID); Inits.initParkingLots(cmbParkingLot); } }); _entryDateTime = new DateTimeCombo(entryDatePicker, cmbEntryHour, cmbEntryMinute); _exitDateTime = new DateTimeCombo(exitDatePicker, cmbExitHour, cmbExitMinute); } /** * Validate the form * @return true if valid, false if not. */ private boolean validateForm() { Validation.clearAllHighlighted(); /* If full subscription, do not allow parking for more than 14 days. */ return Validation.validateTimes(_entryDateTime, _exitDateTime) && Validation.notEmpty(cmbParkingLot, cmbCarID); } /** * Create the order and send it to the server * @param event the button click event. */ @FXML void createOrder(ActionEvent event) { if (!validateForm()) return; WaitScreen waitScreen = new WaitScreen(); Date entryTime = _entryDateTime.getDateTime(); Date exitTime = _exitDateTime.getDateTime(); int parkingLotNumber = cmbParkingLot.getSelectionModel().getSelectedItem().getParkingLotID(); PreOrder newOrder = new PreOrder(CPSClientGUI.getLoggedInUserID(), cmbCarID.getValue(), exitTime, parkingLotNumber , 0.0, entryTime); newOrder.setOrderID(0); Message newMessage = new Message(Message.MessageType.CREATE, Message.DataType.PREORDER, newOrder); MessageRunnable onSuccess = new MessageRunnable() { @Override public void run() { PreOrder preorder = (PreOrder) getMessage().getData().get(0); waitScreen.showSuccess("Order created successfully!", preorder.toGUIString()); waitScreen.setOnClose(new Runnable() { @Override public void run() { CPSClientGUI.goBack(false); } }); } }; MessageRunnable onFailure = new MessageRunnable() { @Override public void run() { waitScreen.showError("Order failed!", getErrorString()); } }; MessageTasker createOrder = new MessageTasker(newMessage, onSuccess, onFailure, "Reserving..."); waitScreen.run(createOrder, 10); } /** * Refreshes the Parking Lots view.<br> * This is needed in case the user cancelled the part where the program queries the server for parking lots. * @param event the button click event. */ @FXML private void refreshLots(ActionEvent event) { Inits.initParkingLots(cmbParkingLot); } /** * Handles the "Manage..." click next to car by redirecting to the {@link ManageCars} screen. * @param event The click event. */ @FXML void manageCars(ActionEvent event) { CPSClientGUI.changeGUI(CPSClientGUI.MANAGE_CARS, this); } /** * Goes back to the previous screen. The name is remnant of an older GUI scheme. * @param event The click event. */ @FXML void returnToMain(ActionEvent event) { CPSClientGUI.goBack(true); } }
true
883856b87e34c5069b0e3ec28332a0898e1e56f5
Java
zeratul0522/InterviewPrep
/src/main/java/algorithm/B.java
UTF-8
592
3.078125
3
[]
no_license
package main.java.algorithm; import main.java.javabasic.A; /** * @Desc * @Author Fan Zejun E-mail:fzj0522@outlook.com * @Version Created at: 2018/9/13 上午10:56 */ public class B implements Cloneable{ public void func(){ System.out.println("func executed"); } public static void main(String[] args){ A a = new A(); B b = new B(); Object o = new Object(); try{ B another = (B)b.clone(); another.func(); }catch (CloneNotSupportedException e){ System.out.println(e.getStackTrace()); } } }
true
721dba23526b097e7b49ade682885421cec0ffd5
Java
vinee-sha/Online_Food_Ordering_System
/GetYourFood/src/com/web/EditUserData.java
UTF-8
2,205
2.4375
2
[]
no_license
package com.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; 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 com.dao.UserDAO; import com.dto.User; @WebServlet("/EditUserData") public class EditUserData extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int pincode = Integer.parseInt(request.getParameter("pincode")); String emailId = request.getParameter("emailId"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String city = request.getParameter("city"); String address = request.getParameter("address"); String state = request.getParameter("state"); String district = request.getParameter("district"); String password = request.getParameter("password"); User user = new User(emailId, phone, name, password, city, address, state, district, pincode); UserDAO userDAO = new UserDAO(); int result = userDAO.updateUserData(user); out.println("<html>"); if(result > 0) { out.println("<body>"); out.println("<h1 style='color:white;'><center>Successfully Updated..</center></h1>"); out.println("</body>"); request.setAttribute("result", result); RequestDispatcher requestDispatcher = request.getRequestDispatcher("Restaurants.jsp"); requestDispatcher.include(request, response); } else { out.println("<h1 style='color:white;'><center>Updation Failed!!</center></h1>"); out.println("</body>"); RequestDispatcher requestDispatcher = request.getRequestDispatcher("Restaurants.jsp"); requestDispatcher.include(request, response); } out.println("</html>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
47ba0ba9a94d5c87aedd7865dca6adec2c36aee8
Java
crossatom/UniCommons
/src/main/java/ru/unicorn/storm/unicommons/utils/Reflection.java
UTF-8
831
2.40625
2
[]
no_license
package ru.unicorn.storm.unicommons.utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class Reflection { public void sendPacket(Player p, Object packet) { try { Object handle = p.getClass().getMethod("getHandle").invoke(p); Object playerConnection = handle.getClass().getField("playerConnection").get(handle); playerConnection.getClass().getMethod("sendPacket", getNMClass("Packet")).invoke(playerConnection, packet); } catch (Exception ex) {} } public Class<?> getNMClass(String name) { try { return Class.forName("net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3] + "." + name); } catch (ClassNotFoundException ex) {} return null; } }
true
c44eb70d859673c68188ff40c426e4f6ab2af0e9
Java
termeneder/compingo
/lingo/src/main/java/bram/lingo/resultobjects/Finished.java
UTF-8
416
1.976563
2
[]
no_license
package bram.lingo.resultobjects; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; public class Finished { public Finished() { finishedqueryList = new ArrayList<FinishedQuery>(); } @XmlElement(name = "query") public List<FinishedQuery> finishedqueryList; public void add(FinishedQuery query) { finishedqueryList.add(query); } }
true
8237890d4b44eb76c73f41d507094dcfb7abaaed
Java
gmsmirnov/gsmirnov
/chapter_1-002/src/main/java/ru/job4j/chess/Cell.java
UTF-8
946
3.3125
3
[ "Apache-2.0" ]
permissive
package ru.job4j.chess; /** * Chessboard cell. * * @author Gregory Smirnov (artress@ngs.ru) * @version 1.0 * @since 01/03/2018 */ public class Cell { private int xCoord; private int yCoord; public Cell(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; } public int getXCoord() { return xCoord; } public int getYCoord() { return yCoord; } @Override public boolean equals(Object o) { boolean result = false; if (this == o) { result = true; } if (o == null || this.getClass() != o.getClass()) { result = false; } else { Cell cell = (Cell) o; if (this.xCoord == cell.xCoord && this.yCoord == cell.yCoord) { result = true; } } return result; } @Override public int hashCode() { return super.hashCode(); } }
true
b6e2bf225847cd2795dffc9ef565c011f9275348
Java
D-a-r-e-k/Code-Smells-Detection
/Preparation/processed-dataset/god-class_4_1100/52.java
UTF-8
3,272
2.03125
2
[]
no_license
/** * Reads an SVG "linearGradient" element. */ private void readLinearGradientElement(IXMLElement elem) throws IOException { HashMap<AttributeKey, Object> a = new HashMap<AttributeKey, Object>(); readCoreAttributes(elem, a); double x1 = toLength(elem, readAttribute(elem, "x1", "0"), 0.01); double y1 = toLength(elem, readAttribute(elem, "y1", "0"), 0.01); double x2 = toLength(elem, readAttribute(elem, "x2", "1"), 0.01); double y2 = toLength(elem, readAttribute(elem, "y2", "0"), 0.01); boolean isRelativeToFigureBounds = readAttribute(elem, "gradientUnits", "objectBoundingBox").equals("objectBoundingBox"); ArrayList<IXMLElement> stops = elem.getChildrenNamed("stop", SVG_NAMESPACE); if (stops.size() == 0) { stops = elem.getChildrenNamed("stop"); } if (stops.size() == 0) { // FIXME - Implement xlink support throughouth SVGInputFormat String xlink = readAttribute(elem, "xlink:href", ""); if (xlink.startsWith("#") && identifiedElements.get(xlink.substring(1)) != null) { stops = identifiedElements.get(xlink.substring(1)).getChildrenNamed("stop", SVG_NAMESPACE); if (stops.size() == 0) { stops = identifiedElements.get(xlink.substring(1)).getChildrenNamed("stop"); } } } if (stops.size() == 0) { if (DEBUG) { System.out.println("SVGInpuFormat: Warning no stops in linearGradient " + elem); } } double[] stopOffsets = new double[stops.size()]; Color[] stopColors = new Color[stops.size()]; double[] stopOpacities = new double[stops.size()]; for (int i = 0; i < stops.size(); i++) { IXMLElement stopElem = stops.get(i); String offsetStr = readAttribute(stopElem, "offset", "0"); if (offsetStr.endsWith("%")) { stopOffsets[i] = toDouble(stopElem, offsetStr.substring(0, offsetStr.length() - 1), 0, 0, 100) / 100d; } else { stopOffsets[i] = toDouble(stopElem, offsetStr, 0, 0, 1); } // 'stop-color' // Value: currentColor | <color> | inherit // Initial: black // Applies to: 'stop' elements // Inherited: no // Percentages: N/A // Media: visual // Animatable: yes // Computed value: Specified <color> value, except i stopColors[i] = toColor(stopElem, readAttribute(stopElem, "stop-color", "black")); if (stopColors[i] == null) { stopColors[i] = new Color(0x0, true); } //'stop-opacity' //Value: <opacity-value> | inherit //Initial: 1 //Applies to: 'stop' elements //Inherited: no //Percentages: N/A //Media: visual //Animatable: yes //Computed value: Specified value, except inherit stopOpacities[i] = toDouble(stopElem, readAttribute(stopElem, "stop-opacity", "1"), 1, 0, 1); } AffineTransform tx = toTransform(elem, readAttribute(elem, "gradientTransform", "none")); Gradient gradient = factory.createLinearGradient(x1, y1, x2, y2, stopOffsets, stopColors, stopOpacities, isRelativeToFigureBounds, tx); elementObjects.put(elem, gradient); }
true
b66e18cfbeb499a64021ddeeb02521f78b78cf09
Java
junges521/src_awe
/src/main/java/com/bytedance/android/livesdk/chatroom/presenter/g.java
UTF-8
1,075
1.546875
2
[]
no_license
package com.bytedance.android.livesdk.chatroom.presenter; import com.bytedance.android.live.core.network.response.d; import com.bytedance.android.livesdk.chatroom.model.p; import com.bytedance.android.livesdk.chatroom.presenter.f; import com.meituan.robust.ChangeQuickRedirect; import com.meituan.robust.PatchProxy; import io.reactivex.functions.Consumer; public final /* synthetic */ class g implements Consumer { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f11355a; /* renamed from: b reason: collision with root package name */ private final f f11356b; public g(f fVar) { this.f11356b = fVar; } public final void accept(Object obj) { if (PatchProxy.isSupport(new Object[]{obj}, this, f11355a, false, 5161, new Class[]{Object.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{obj}, this, f11355a, false, 5161, new Class[]{Object.class}, Void.TYPE); return; } ((f.a) this.f11356b.b()).a((p) ((d) obj).f7871b); } }
true
0f58fc7393b696a29a144af4923bca3344fa4b6b
Java
evignacio/backend-test-java
/src/main/java/br/fcamara/test/controller/EstabelecimentoController.java
UTF-8
2,549
2.3125
2
[]
no_license
package br.fcamara.test.controller; import java.net.URI; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import br.fcamara.test.domain.entities.Estabelecimento; import br.fcamara.test.application.service.EstabelecimentoService; @RestController @RequestMapping("/api/estabelecimento") public class EstabelecimentoController { @Autowired private EstabelecimentoService estabelecimentoService; @GetMapping public List<Estabelecimento> GetAll() { return estabelecimentoService.findAll(); } @GetMapping("/{id}") public ResponseEntity<Estabelecimento> findById(@PathVariable Long id) { Estabelecimento estabelecimento = estabelecimentoService.findById(id); if(estabelecimento.getId() > 0) return ResponseEntity.ok().body(estabelecimento); return ResponseEntity.notFound().build(); } @PostMapping public ResponseEntity<Estabelecimento> save(@RequestBody @Valid Estabelecimento estabelecimento, UriComponentsBuilder uriBuilder) { Estabelecimento estabelecimentoSave = estabelecimentoService.save(estabelecimento); URI uri = uriBuilder.path("/api/estabelecimento/{id}").buildAndExpand(estabelecimentoSave.getId()).toUri(); return ResponseEntity.created(uri).body(estabelecimentoSave); } @PutMapping("/{id}") public ResponseEntity<Estabelecimento> update(@PathVariable Long id, @RequestBody @Valid Estabelecimento estabelecimento) { estabelecimento.setId(id); Estabelecimento estabelecimentoUpdate = estabelecimentoService.update(estabelecimento); if(estabelecimentoUpdate.getId() > 0) return ResponseEntity.ok(estabelecimentoUpdate); else return ResponseEntity.notFound().build(); } @DeleteMapping("/{id}") public ResponseEntity<?> delete(@PathVariable Long id){ if(estabelecimentoService.delete(id)) return ResponseEntity.ok().body("Estabelecimento excluido com sucesso"); return ResponseEntity.notFound().build(); } }
true
7d7ea7d620a65ed49f89ac60de890a4a91a4c1a0
Java
jsdelivrbot/ionic4-angular6
/telegraph/cq/core-app/core-app-review/src/test/java/uk/co/telegraph/core/review/entity/EntityDefinitionPropertiesServletTest.java
UTF-8
1,418
2.078125
2
[]
no_license
package uk.co.telegraph.core.review.entity; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.List; import org.apache.sling.api.request.RequestPathInfo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.common.collect.Lists; @RunWith(MockitoJUnitRunner.class) public class EntityDefinitionPropertiesServletTest extends AbstractEntityServletTest { private EntityDefinitionPropertiesServlet servlet; @Mock private RequestPathInfo requestPathInfo; @Override @Before public void setup() { servlet = new EntityDefinitionPropertiesServlet(); super.setup(); when(request.getRequestPathInfo()).thenReturn(requestPathInfo); when(requestPathInfo.getSelectorString()).thenReturn("properties"); } @Test public void whenEntityHasGotPropertiesExpectTheyAreInJson() throws IOException { when(entityDefinition.getEntityDefinitionProperties()).thenReturn(getTwoProperties()); runTest("list_two_properties.json", servlet); } @Test public void whenEntityHasGotNoExpectEmptyJson() throws IOException { when(entityDefinition.getEntityDefinitionProperties()).thenReturn(getEmptyProperties()); runTest("list_no_properties.json", servlet); } private List<EntityDefinitionProperty> getEmptyProperties() { return Lists.newLinkedList(); } }
true
2085c517e891c2d8a596b90b231e648c2dd05e30
Java
MatheusNCarvalho/Crud-Android-e-Sqlite
/app/src/main/java/com/example/matheus/sqllite/configuracao/UsuarioContract.java
UTF-8
564
1.734375
2
[]
no_license
package com.example.matheus.sqllite.configuracao; import android.provider.BaseColumns; /** * Created by Matheus on 11/11/2017. */ public final class UsuarioContract implements BaseColumns { private UsuarioContract(){ } public static final String NOME_TABELA ="usuarios"; public static final String COLUNA_ID ="_id"; public static final String COLUNA_NOME ="nome"; public static final String COLUNA_EMAIL ="email"; public static final String COLUNA_CPF ="cpf"; public static final String COLUNA_TELEFONE ="telefone"; }
true
e7c8bf2e367bfb2157aa382603020d8fbb22975a
Java
TVanLinh/blog-project-oec
/src/main/java/model/PostRestBody.java
UTF-8
1,490
2.046875
2
[]
no_license
package model; import com.fasterxml.jackson.annotation.JsonView; import entities.Post; import jsonviews.Views; import java.util.List; /** * Created by linhtran on 10/05/2017. */ public class PostRestBody { @JsonView(Views.Public.class) private String msg; @JsonView(Views.Public.class) private int numberPage; @JsonView(Views.Public.class) int numberConf; @JsonView(Views.Public.class) int numberApprove; @JsonView(Views.Public.class) List<Post> posts; @JsonView(Views.Public.class) private int totalPost; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getNumberPage() { return numberPage; } public void setNumberPage(int numberPage) { this.numberPage = numberPage; } public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this.posts = posts; } public int getNumberConf() { return numberConf; } public void setNumberConf(int numberConf) { this.numberConf = numberConf; } public int getNumberApprove() { return numberApprove; } public void setNumberApprove(int numberApprove) { this.numberApprove = numberApprove; } public int getTotalPost() { return totalPost; } public void setTotalPost(int totalPost) { this.totalPost = totalPost; } }
true
4b607efed0a6d95618d257f782d7d983776b4afa
Java
RaresPopa22/RecursiveXMLParser
/src/Main.java
UTF-8
1,278
2.84375
3
[]
no_license
import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { try { RecursiveDOMRefactor recursiveDOM = new RecursiveDOMRefactor("./classes.xml"); Map<String, Integer> map = recursiveDOM.getFields(); Map.Entry maxEntry = map.entrySet().stream() .max(Map.Entry.comparingByValue()) .get(); for (int i = 0; i < (int) maxEntry.getValue(); i++) { System.out.println("*** AT DEPTH " + i); int constant = i; map.entrySet().stream() .filter(entry -> entry.getValue() == constant) .forEach(entry -> System.out.println(entry.getKey())); } } catch (IOException | SAXException | ParserConfigurationException e) { e.printStackTrace(); } } // to get alias use this private static String getAlias(String className) { return Arrays.stream(className.split("")) .filter(s -> Character.isUpperCase(s.charAt(0))) .map(s -> s.toLowerCase()) .collect(Collectors.joining("")); } }
true
92bb7895eef8511679343105a7381117a11779ab
Java
SumitAnglekar/LeetCode
/Binary Tree/Java/src/PostOrderTraversalBinaryTree.java
UTF-8
1,078
3.328125
3
[]
no_license
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class PostOrderTraversalBinaryTree { public static List<Integer> postorderTraversal(TreeNode root) { LinkedList <TreeNode> stack = new LinkedList<>(); LinkedList <Integer> result = new LinkedList<>(); if(root==null) return result; stack.add(root); while(!stack.isEmpty()){ TreeNode node = stack.pollLast(); result.add(node.val); if(node.left !=null){ stack.add(node.left); } if(node.right !=null){ stack.add(node.right); } } return result; } public static void main(String args[]){ List<Integer> arr = new ArrayList<Integer>(); TreeNode tree = new TreeNode(); tree = new TreeNode(1); tree.left= new TreeNode(2); tree.right= new TreeNode(3); tree.left.left = new TreeNode(4); tree.left.right = new TreeNode(5); postorderTraversal(tree); } }
true
85b9c6ea592d5961ac80f53bbc76fac0e5b42a04
Java
hsyou/wagu
/src/main/java/com/hsyou/wagu/controller/AccountController.java
UTF-8
1,963
2.09375
2
[]
no_license
package com.hsyou.wagu.controller; import com.hsyou.wagu.model.Account; import com.hsyou.wagu.model.AccountDTO; import com.hsyou.wagu.service.AccountService; import com.hsyou.wagu.service.JwtTokenProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.social.google.api.plus.Person; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Optional; @RestController @RequestMapping("/account") //@CrossOrigin(origins = "*") public class AccountController { @Autowired private AccountService accountService; @GetMapping("{id}") public ResponseEntity<Account> getAccount(@PathVariable long id){ return ResponseEntity.ok(accountService.getAccount(id)); } @PutMapping("") public ResponseEntity<Account> updateAccount(@RequestBody Account account){ return ResponseEntity.ok(accountService.saveAccount(account)); } @PutMapping("/name") public ResponseEntity<String> updateName (@RequestBody AccountDTO accountDTO){ long id = 0; try{ id= Long.parseLong(SecurityContextHolder.getContext().getAuthentication().getName()); System.out.println(id); }catch (Exception ex){ ex.printStackTrace(); throw new ResponseStatusException(HttpStatus.UNAUTHORIZED,"Unauthorized"); } accountService.updateAccountName(id, accountDTO.getName()); return ResponseEntity.ok("ok"); } }
true
1ea682ae120e5c86ab91ab978d8e550a85e2693e
Java
Raghav369/BasePP-project
/src/test/java/com/BNPPROJECT/pageobjects/Loginpage.java
UTF-8
1,152
2.03125
2
[]
no_license
package com.BNPPROJECT.pageobjects; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; public class Loginpage { WebDriver ldriver; public Loginpage(WebDriver rdriver) { ldriver = rdriver; PageFactory.initElements(rdriver, this); } @FindBy(name ="loginForm:userName") @CacheLookup WebElement txtUserName; @FindBy(name ="loginForm:password") @CacheLookup WebElement txtPassword; @FindBy(name ="loginForm:submit") @CacheLookup WebElement btnlogin; @FindBy(xpath ="//*[@id=\"alreadyLoginForm:j_id20\"]") @CacheLookup WebElement popup; @FindBy(xpath ="//*[@id=\"logoutHeaderForm:logoutwhennomenu\"]") @CacheLookup WebElement logout; public void setUserName(String uname) { txtUserName.sendKeys(uname); } public void setPassword(String Pwd) { txtPassword.sendKeys(Pwd); } public void Clickbtn() { btnlogin.click(); } public void loginpop() { popup.click();} public void logout1() { logout.click(); } }
true
c5d56a22ab85d41d22b7ba5eef7c2297e32fe01d
Java
codewithnonny/spring_mvc
/src/main/java/com/springmvc/controller/ContactController.java
UTF-8
709
2.25
2
[]
no_license
package com.springmvc.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class ContactController { @RequestMapping("contact") public String contact() { System.out.println("contact page "); return "contact"; } @RequestMapping(path="processform",method=RequestMethod.POST) public String processform(@RequestParam("email") String email, Model model) { System.out.println(email); model.addAttribute("email",email); return "contact"; } }
true
03cc39e8a71a7036e20ac3a4504f104ed7c364fe
Java
amennet/bingo
/bingo-register/src/main/java/com/framework/register/zookeeper/zkclient/ZkclientZookeeperTransporter.java
UTF-8
384
1.945313
2
[]
no_license
package com.framework.register.zookeeper.zkclient; import com.framework.common.register.URL; import com.framework.register.zookeeper.ZookeeperClient; import com.framework.register.zookeeper.ZookeeperTransporter; public class ZkclientZookeeperTransporter implements ZookeeperTransporter { public ZookeeperClient connect(URL url) { return new ZkclientZookeeperClient(url); } }
true
c2dab8a557f0065e578680ca40e971b63e079c0d
Java
1007944735/WardrobeAssistant
/app/src/main/java/com/example/wardrobeassistant/Constant.java
UTF-8
1,969
2.078125
2
[]
no_license
package com.example.wardrobeassistant; public interface Constant { //服装色系 String COLOR_COLD_SYSTEM = "coldSystem"; String CN_COLOR_COLD_SYSTEM = "冷色系"; String COLOR_WARM_SYSTEM = "warmSystem"; String CN_COLOR_WARM_SYSTEM = "暖色系"; //服装类型 String TYPE_OVERCOAT = "overcoat"; String CN_TYPE_OVERCOAT = "外套"; String TYPE_OUTERWEAR = "outerwear"; String CN_TYPE_OUTERWEAR = "上衣"; String TYPE_TROUSERS = "trousers"; String CN_TYPE_TROUSERS = "裤子"; String TYPE_SHOES = "shoes"; String CN_TYPE_SHOES = "鞋子"; //服装场景 String OCCASION_DAILY = "daily"; String CN_OCCASION_DAILY = "日常"; String OCCASION_WORK = "work"; String CN_OCCASION_WORK = "工作"; String OCCASION_SPORT = "sport"; String CN_OCCASION_SPORT = "运动"; //服装保暖等级 String WARMTH_LEVEL_SPRING_AUTUMN = "springAutumn"; String CN_WARMTH_LEVEL_SPRING_AUTUMN = "春秋"; String WARMTH_LEVEL_SUMMER = "summer"; String CN_WARMTH_LEVEL_SUMMER = "夏"; String WARMTH_LEVEL_WINTER = "winter"; String CN_WARMTH_LEVEL_WINTER = "冬"; //位置信息 String LOCATION_HANGING_CLOTHES_ONE = "pin10"; String CN_LOCATION_HANGING_CLOTHES_ONE = "挂衣区一"; String LOCATION_HANGING_CLOTHES_TWO = "pin9"; String CN_LOCATION_HANGING_CLOTHES_TWO = "挂衣区二"; String LOCATION_HANGING_CLOTHES_THREE = "pin8"; String CN_LOCATION_HANGING_CLOTHES_THREE = "挂衣区三"; String LOCATION_STORAGE_CLOTHES_ONE = "pin7"; String CN_LOCATION_STORAGE_CLOTHES_ONE = "收纳区一"; String LOCATION_STORAGE_CLOTHES_TWO = "pin6"; String CN_LOCATION_STORAGE_CLOTHES_TWO = "收纳区二"; String LOCATION_STORAGE_CLOTHES_THREE = "pin5"; String CN_LOCATION_STORAGE_CLOTHES_THREE = "收纳区三"; String LOCATION_STORAGE_CLOTHES_FOUR = "pin4"; String CN_LOCATION_STORAGE_CLOTHES_FOUR = "收纳区四"; }
true
e3eb232344ee14e5d9a24d4ccd886422ac5da4db
Java
Legends-of-Valeros/LOV-Plugin-2019
/src/main/java/com/legendsofvaleros/features/playermenu/events/PlayerOptionsOpenEvent.java
UTF-8
1,247
2.21875
2
[]
no_license
package com.legendsofvaleros.features.playermenu.events; import com.legendsofvaleros.features.gui.slot.ISlotAction; import com.legendsofvaleros.features.gui.slot.Slot; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; public class PlayerOptionsOpenEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } boolean cancelled = false; @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean cancel) { cancelled = cancel; } private List<Slot> slots = new ArrayList<>(); public List<Slot> getSlots() { return slots; } public void addSlot(ItemStack stack, ISlotAction action) { slots.add(new Slot(stack, action)); } public PlayerOptionsOpenEvent(Player player) { super(player); } }
true
625e685a7b3ea32f9474f0ddc5ed5ac2e497bacb
Java
crstffr/omen.alien
/src/omen/alien/component/MajorLayout.java
UTF-8
2,448
2.71875
3
[]
no_license
package omen.alien.component; import omen.alien.Const; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; public class MajorLayout extends Layout { Layout currentStateObj; String currentStateStr; public LinkedHashMap<String, Layout> states = new LinkedHashMap<>(); public LinkedHashMap<String, Widget> widgets = new LinkedHashMap<>(); public int color = Const.WHITE; public ButtonRow buttonRow = new ButtonRow(); public MajorLayout() { onEnable(() -> { buttonRow.setColor(color); widgets.forEach((String key, Widget widget) -> widget.enable()); if (currentStateObj != null) { currentStateObj.enable(); } }); onDisable(() -> { widgets.forEach((String key, Widget widget) -> widget.disable()); if (currentStateObj != null) { currentStateObj.disable(); } }); onDraw(() -> { buttonRow.draw(); widgets.forEach((String key, Widget widget) -> widget.draw()); if (currentStateObj != null) { currentStateObj.draw(); } }); onClear(() -> { if (currentStateObj != null) { currentStateObj.clear(); } buttonRow.clear(); }); } public boolean stateIs(String what) { return currentStateStr.equals(what); } public Layout getStateObj() { return states.get(currentStateStr); } public void setState(String name) { currentStateStr = name; currentStateObj = getStateObj(); states.forEach((String key, Layout layout) -> { if (layout != null && !key.equals(name)) { layout.disable(); } }); currentStateObj.enable(); } public void customKeyHandler(char key, int keyCode) { // meant to be provided by consumer } public void keyPressed(char key, int keyCode) { if (isEnabled) { if (currentStateObj != null) { currentStateObj.keyPressed(key, keyCode); } if (buttonRow.buttons.size() == Const.UI_BUTTONS.length) { buttonRow.buttons.forEach((Button button) -> { if (button.key == key) { button.trigger(); } }); } customKeyHandler(key, keyCode); } } }
true
fb6ec577f945a04dbb99a3bddd49aa8fdb1be65e
Java
HKMOpen/ReWallet
/walletapp/ReWallet/src/main/java/com/imusic/rewallet/model/GlobalDataInfo.java
UTF-8
4,625
2.125
2
[]
no_license
package com.imusic.rewallet.model; public class GlobalDataInfo { static class Nested{ static GlobalDataInfo _instance = new GlobalDataInfo(); } public static GlobalDataInfo getInstance(){ return Nested._instance; } private String _language; private int _searchRewardsCategoryId = -1; private int _searchRewardsCountryId = -1; private int _searchAppsCategoryId = -1; private int _searchAppsCountryId = -1; //private String _searchCategoryThumb; private String _searchRewardsCategoryPressThumb; private String _searchRewardsCategoryUnpressThumb; private String _searchRewardsCountryPressThumb; private String _searchRewardsCountryUnpressThumb; private String _searchRewardsCountryDesc; private String _searchAppsCategoryPressThumb; private String _searchAppsCategoryUnpressThumb; private String _searchAppsCountryPressThumb; private String _searchAppsCountryUnpressThumb; private String _searchAppsCountryDesc; public String getLanguage() { if(_language == null || _language.length() == 0) return "zh-hant"; //"en","zh","ja" return _language; } public void setLanguage(String language) { this._language = language; } public void clearAllData(){ _searchRewardsCategoryId = 0; _searchRewardsCountryId = -1; _searchAppsCategoryId = 0; _searchAppsCountryId = -1; _searchRewardsCategoryPressThumb = null; _searchRewardsCategoryUnpressThumb = null; _searchRewardsCountryPressThumb = null; _searchRewardsCountryUnpressThumb = null; _searchRewardsCountryDesc = null; _searchAppsCategoryPressThumb = null; _searchAppsCategoryUnpressThumb = null; _searchAppsCountryPressThumb = null; _searchAppsCountryUnpressThumb = null; _searchAppsCountryDesc = null; } //---------------------------------------------------- public int getRewardsSearchCategoryId(){ return _searchRewardsCategoryId; } public void setRewardsSearchCategoryId(int id){ this._searchRewardsCategoryId = id; } public int getAppsSearchCategoryId(){ return _searchAppsCategoryId; } public void setAppsSearchCategoryId(int id){ this._searchAppsCategoryId = id; } //----------------------------------------------------- public int getRewardsSearchCountryId(){ return _searchRewardsCountryId; } public void setRewardsSearchCountryId(int id){ this._searchRewardsCountryId = id; } public int getAppsSearchCountryId(){ return _searchAppsCountryId; } public void setAppsSearchCountryId(int id){ this._searchAppsCountryId = id; } // ----------------------------------------------------------- public String getRewardsSearchCategoryUnpressThumb(){ return _searchRewardsCategoryUnpressThumb; } public void setRewardsSearchCategoryUnpressThumb(String unpress){ _searchRewardsCategoryUnpressThumb = unpress; } public String getRewardsSearchCategoryPressThumb(){ return _searchRewardsCategoryPressThumb; } public void setRewardsSearchCategoryPressThumb(String press){ _searchRewardsCategoryPressThumb = press; } public String getRewardsSearchCountryDesc(){ return _searchRewardsCountryDesc; } public void setRewardsSearchCountryDesc(String desc){ this._searchRewardsCountryDesc = desc; } public String getRewardsSearchCountryPressThumb(){ return this._searchRewardsCountryPressThumb; } public void setRewardsSearchCountryPressThumb(String press){ this._searchRewardsCountryPressThumb = press; } public String getRewardsSearchCountryUnpressThumb(){ return this._searchRewardsCountryUnpressThumb; } public void setRewardsSearchCountryUnpressThumb(String unpress){ this._searchRewardsCountryUnpressThumb = unpress; } //================ public String getAppsSearchCategoryUnpressThumb(){ return _searchAppsCategoryUnpressThumb; } public void setAppsSearchCategoryUnpressThumb(String unpress){ _searchAppsCategoryUnpressThumb = unpress; } public String getAppsSearchCategoryPressThumb(){ return _searchAppsCategoryPressThumb; } public void setAppsSearchCategoryPressThumb(String press){ _searchAppsCategoryPressThumb = press; } public String getAppsSearchCountryDesc(){ return _searchAppsCountryDesc; } public void setAppsSearchCountryDesc(String desc){ this._searchAppsCountryDesc = desc; } public String getAppsSearchCountryPressThumb(){ return this._searchAppsCountryPressThumb; } public void setAppsSearchCountryPressThumb(String press){ this._searchAppsCountryPressThumb = press; } public String getAppsSearchCountryUnpressThumb(){ return this._searchAppsCountryUnpressThumb; } public void setAppsSearchCountryUnpressThumb(String unpress){ this._searchAppsCountryUnpressThumb = unpress; } }
true
ffe2b0f61a7a8579f9377bb2b52bbfcd6053a2ef
Java
sonyu/android_projects
/Caculator/app/src/main/java/vkz/android/dev/caculator/div_operator.java
UTF-8
729
2.640625
3
[]
no_license
package vkz.android.dev.caculator; /** * Created by Administrator on 1/11/2017. */ public class div_operator { // public mul_operator mul = new mul_operator(); public String div_int(String s1, String s2){ String s =""; String result =""; String dau =""; if(s1.substring(0,1).equals("-")){ dau ="-"; s1 = s1.substring(1,s1.length()); } int dem =0; float s1a = Float.parseFloat(s1); float s2a = Float.parseFloat(s2); if(s2a==0){ s ="Division by zero !"; }else{ result =String.valueOf(s1a/s2a); s = result; // mul.remove_rezo(s); } return dau+s; } }
true
ecbc625a6343530862cef56b7522dc85c85259bc
Java
Jakz/java-pix-lib
/src/main/java/com/pixbits/lib/log/Reporter.java
UTF-8
589
2.65625
3
[]
no_license
package com.pixbits.lib.log; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; public class Reporter<T> { private Optional<Consumer<T>> destination; public Reporter() { this.destination = Optional.empty(); } public Reporter(Consumer<T> destination) { setDestination(destination); } public void setDestination(Consumer<T> destination) { this.destination = Optional.of(destination); } public void report(Supplier<T> supplier) { destination.ifPresent(c -> c.accept(supplier.get())); } }
true
951e7513ab578878b0b877fbc7d1afc5fd539ead
Java
Shb90ties/ALL
/Java OO/AFsummery.java
UTF-8
1,242
2.5
2
[]
no_license
byte short int long float double char boolean interface X { public void draw(); } interface Y extends X { public void draw(); } class ggg implements Y { public void draw(){ .... } } class fff extends ggg { public void draw(){ .... } } enum month{ jan,feb,apr } @Override public void draw() import myPack; public class Main { public static void main(String[] args)throws IOException { // ClassNotFoundException,InputMismatchException ggg g = new ggg(); ggg.draw(); month M = month.jan; month M = month.valueOf("jan"); month alltypes[] = PLtypes.values(); for(month m: allypes){ System.out.println("month "+m); } } public int scan() throws InputMismatchException { Scanner s = new Scanner(System.in); int n = s.nextInt(); string str = s.nextString(); try{...}catch(InputMismatchException)finally{...} } public void save(){ FileOutputStream FOS = new FileOutputStream("List.dat"); ObjectOutputStream OOS = new ObjectOutputStream(FOS); OOS.writeObject(object); } public void load() throw IOException { try{ FileInputStream FIS = new FileInputStream("List.dat"); ObjectInputStream OIS = new ObjectInputStream(FIS); object = (objectType)OIS.readObject(); }catch (IOException e){...}finally{...} } }
true
6caff56a53c8ea246f381408589e03eaceb9843c
Java
jepsonw/Data_Structures_and_Algorithm_Analysis_in_Java
/src/QuickSort.java
GB18030
1,929
3.9375
4
[]
no_license
/** * Ӧг÷һ źƽʱ临ӶO(N*logN)O(N^2) Ҫռ䡣ȶ * ĽҪѡȡpivotϣõDzֻ㷨οQuickSelect⡣ * JavaлԪõǸĽĿ */ public class QuickSort { private static <T extends Comparable<? super T>> T Median(T[] input, int left, int right) { int middle = (right + left) / 2; if (input[middle].compareTo(input[left]) < 0) { SwapRef(input, middle, left); } if (input[right].compareTo(input[left]) < 0) { SwapRef(input, right, left); } if (input[right].compareTo(input[middle]) < 0) { SwapRef(input, middle, right); } SwapRef(input, middle, right); return input[right]; } private static <T extends Comparable<? super T>> void SwapRef(T[] input, int i, int j) { T temp = input[i]; input[i] = input[j]; input[j] = temp; } private static <T extends Comparable<? super T>> void QuickSort(T[] input, int left, int right) { if (right > left) { T pivot = Median(input, left, right); int i = left, j = right - 1; while (true) { while (i < right && input[i].compareTo(pivot) < 0) { i++; } while (j >= left && input[j].compareTo(pivot) > 0) { j--; } if (i < j) { SwapRef(input, i++, j--); } else { break; } } SwapRef(input, right, i); QuickSort(input, left, i - 1); QuickSort(input, i + 1, right); } } public static <T extends Comparable<? super T>> void QuickSort(T[] input) { if (input == null) { return; } QuickSort(input, 0, input.length - 1); } public static void main(String[] args) { Integer[] test1 = new Integer[] { 213, 123, 432, 54, 56765, 5324, 8768, 234 }; QuickSort.QuickSort(test1); for (int i = 0; i < test1.length; i++) { System.out.println(test1[i]); } } }
true
b9773ffb032e6fe6c0e86386270129d8667704eb
Java
GayaneHarutyunyan/DataBaseBrainFart
/src/main/java/services/TestAvailabilityService.java
UTF-8
705
2.03125
2
[]
no_license
package services; import dao.TestAvailabilityDao; import models.TestAvailability; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service(value = "testAvailabilityService") public class TestAvailabilityService { @Autowired @Qualifier("testAwailableDatabaseDao") private TestAvailabilityDao testAvailabilityDao; public TestAvailabilityService() { } @Transactional public List<TestAvailability> getAll() { return testAvailabilityDao.getAll(); } }
true
0dd2f2a8a4cd7111460c0defb099c82fa761dbba
Java
tossakonsir/spring-web-app
/src/test/java/com/example/demo/ReviewApiControllerTests.java
UTF-8
2,240
1.90625
2
[]
no_license
package com.example.demo; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import com.example.demo.model.Review; import com.example.demo.repository.ReviewRepository; @DataJpaTest @AutoConfigureTestDatabase(replace = Replace.NONE) class ReviewApiControllerTests { @Autowired private ReviewRepository reviewReposiroty; @Test public void testGetReviewById() { Review mockReview = new Review(); mockReview.setReviewId((long) 2); mockReview.setReview("สั่งไป2 เมนู คือมัชฉะลาเต้ร้อน กับ ไอศครีมชาเขียว มัชฉะลาเต้ร้อน รสชาเขียวเข้มข้น หอม มัน แต่ไม่กลมกล่อม มันจืดแบบจืดสนิท ส่วนไอศครีมชาเขียว ทานแล้วรสมันออกใบไม้ๆมากกว่าชาเขียว แล้วก็หวานไป โดยรวมแล้วเฉยมากก ดีแค่รสชาเขียวเข้ม มีน้ำเปล่าบริการฟรี"); Review review = reviewReposiroty.findById((long) 2).get(); assertThat(review.getReview()).isEqualTo(mockReview.getReview()); } @Test public void testGetReviewByText() { List<Review> review = reviewReposiroty.searchByReviewLike("ไอติมมันม่วง"); assertThat(review.size()).isEqualTo(1); } @Test public void testEditReview() { reviewReposiroty.findById((long) 1).map(Review -> { Review.setReview("test edit review"); return reviewReposiroty.save(Review); }); Review review = reviewReposiroty.findById((long) 1).get(); assertThat(review.getReview()).isEqualTo("test edit review"); } }
true
b58787ba62eeeef62f3aad916089bfdb063019bd
Java
CoderFreeMan/prototype_pattern
/src/copy_test/DeepCopy.java
UTF-8
1,093
2.953125
3
[]
no_license
package copy_test; import java.util.ArrayList; /** * <p> Date :2018/4/25 </p> * <p> Module : </p> * <p> Description : </p> * <p> Remark : </p> * * @author yangdejun * @version 1.0 * <p>--------------------------------------------------------------</p> * <p>修改历史</p> * <p> 序号 日期 修改人 修改原因 </p> * <p> 1 </p> */ public class DeepCopy implements Cloneable { private ArrayList<String> arrayList = new ArrayList<>(); @Override protected DeepCopy clone() throws CloneNotSupportedException { DeepCopy deepCopy = null; try { deepCopy = (DeepCopy) super.clone(); deepCopy.arrayList = (ArrayList<String>) this.arrayList.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return deepCopy; } public void setValue(String value) { this.arrayList.add(value); } public ArrayList<String> getValue() { return this.arrayList; } }
true
2c692b0b28e9e6973f57fe74c4359e41911b7d1c
Java
zhaohenghf/generator-1
/src/main/java/com/ichings/generator/dto/CodeDto.java
UTF-8
2,126
2.34375
2
[]
no_license
package com.ichings.generator.dto; import com.ichings.generator.util.JsonParser; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.List; /** * 生成代码配置 * * @author 宋欢 */ @ApiModel public class CodeDto implements Serializable { @ApiModelProperty(value = "根包名", required = false, dataType = "String", example = "com.domain.sample") private String packageName; @ApiModelProperty(value = "作者名", required = false, dataType = "String", example = "张三") private String authorName; @ApiModelProperty(value = "模板目录(建议绝对路径)", required = false, dataType = "String", example = "template") private String templateDir; @ApiModelProperty(value = "目标代码目录(建议绝对路径)", required = false, dataType = "String", example = "target-code") private String targetDir; @ApiModelProperty(value = "表名列表,置空:全部表", required = false, dataType = "List", example = "[]") private List<String> tableNames; @Override public String toString() { return JsonParser.toJson(this); } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public String getTemplateDir() { return templateDir; } public void setTemplateDir(String templateDir) { this.templateDir = templateDir; } public String getTargetDir() { return targetDir; } public void setTargetDir(String targetDir) { this.targetDir = targetDir; } public List<String> getTableNames() { return tableNames; } public void setTableNames(List<String> tableNames) { this.tableNames = tableNames; } }
true
8bdfd28cdd4ad3510aba840b523afdde5fd86164
Java
Akchy/CSLibrary
/app/src/main/java/com/drc/cslibraryadmin/History.java
UTF-8
10,131
2.125
2
[]
no_license
package com.drc.cslibraryadmin; import android.app.Activity; import android.app.DatePickerDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Toast; 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.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; public class History extends AppCompatActivity { EditText bookno; Button fdate,tdate,search; DatePickerDialog datePickerDialog; FirebaseDatabase database; DatabaseReference ref,ref1; RecyclerView recyclerView; RecyclerView.Adapter adapter ; private Button scan_btn; int mode=0,x=1; int fmonth,fday, fyear,mday,mmonth,myear; Date fdateval,mdateval,cdateval; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); setTitle("History"); bookno = (EditText)findViewById(R.id.bno); search = (Button)findViewById(R.id.search); database = FirebaseDatabase.getInstance(); ref = database.getReference("ID"); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(History.this)); TextWatcher textWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { x=1; } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }; bookno.addTextChangedListener(textWatcher); scan_btn=(Button)findViewById(R.id.sno); final Activity activity = this; scan_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { x=1; IntentIntegrator integrator = new IntentIntegrator(activity); integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES); integrator.setPrompt("Book Id Scan"); integrator.setCameraId(0); integrator.setBeepEnabled(false); integrator.setBarcodeImageEnabled(false); integrator.initiateScan(); mode=1; } }); fdate = (Button) findViewById(R.id.fdate); tdate = (Button) findViewById(R.id.tdate); // perform click event on edit text fdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { x=1; // calender class's instance and get current date , month and year from calender final Calendar c = Calendar.getInstance(); int fYear = c.get(Calendar.YEAR); // current year int fMonth = c.get(Calendar.MONTH); // current month int fDay = c.get(Calendar.DAY_OF_MONTH); // current day // date picker dialog datePickerDialog = new DatePickerDialog(History.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // set day of month , month and year value in the edit text fdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year); fday = dayOfMonth; fmonth = monthOfYear+1; fyear=year; } },fYear, fMonth, fDay); datePickerDialog.show(); } }); tdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { x=1; // calender class's instance and get current date , month and year from calender final Calendar c = Calendar.getInstance(); int mYear = c.get(Calendar.YEAR); // current year int mMonth = c.get(Calendar.MONTH); // current month int mDay = c.get(Calendar.DAY_OF_MONTH); // current day // date picker dialog datePickerDialog = new DatePickerDialog(History.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // set day of month , month and year value in the edit text tdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year); mday = dayOfMonth; mmonth = monthOfYear+1; myear=year; } }, mYear, mMonth, mDay); datePickerDialog.show(); } }); // Toast.makeText(History.this,fdate.getText().toString(),Toast.LENGTH_SHORT).show(); } public void searchHistory(View view){ if(fdate.getText().equals("From")||tdate.getText().equals("To")) Toast.makeText(History.this, "Select the Date Interval", Toast.LENGTH_SHORT).show(); else { ref1 = ref.child(bookno.getText().toString()).child("History"); ref1.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { if (x == 1) { List<NewHis> list = new ArrayList<>(); for (DataSnapshot postSnapshot : snapshot.getChildren()) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); try { fdateval = sdf.parse(fday + "-" + fmonth + "-" + fyear); mdateval = sdf.parse(mday + "-" + (mmonth) + "-" + myear); cdateval = sdf.parse(postSnapshot.getKey()); } catch (ParseException p) { } // Toast.makeText(History.this,cdateval.toString(),Toast.LENGTH_SHORT).show(); if ((fdateval.before(cdateval) || fdateval.equals(cdateval)) && (mdateval.after(cdateval) || mdateval.equals(cdateval))) { // Toast.makeText(History.this,"jjj",Toast.LENGTH_SHORT).show(); for (DataSnapshot innerSnapshot : postSnapshot.getChildren()) { NewHis newhis = new NewHis(); newhis.setVal(innerSnapshot.getValue().toString()); newhis.setTime(innerSnapshot.getKey()); newhis.setDate(postSnapshot.getKey()); list.add(newhis); } } } adapter = new RecyclerViewAdapterHistory(History.this, list); recyclerView.setAdapter(adapter); x++; if (adapter.getItemCount() == 0) { Toast.makeText(History.this, "No History", Toast.LENGTH_SHORT).show(); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_history,menu); MenuItem menuItem = menu.findItem(R.id.action_settings); return true; } public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); if (id == R.id.action_settings) { Intent intent = new Intent(getApplicationContext(), GenHistory.class); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result= IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result!=null){ if(result.getContents()==null){ Toast.makeText(this, "You cancelled this scanning", Toast.LENGTH_SHORT).show(); } else{ if(mode==1) bookno.setText(result.getContents()); } } else { super.onActivityResult(requestCode, resultCode, data); } } }
true
8bcd73924e0c082fe49232811c0b6ef04019e22c
Java
VjrutNAT/Kyo
/app/src/main/java/com/kyo/vjrutnat/sunshine/Adapter/WeatherAdapter.java
UTF-8
4,194
2.1875
2
[]
no_license
package com.kyo.vjrutnat.sunshine.Adapter; import android.app.Fragment; import android.content.Context; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.kyo.vjrutnat.sunshine.Items.Weather; import com.kyo.vjrutnat.sunshine.R; import com.kyo.vjrutnat.sunshine.SunShine.FragmentDetails; import com.kyo.vjrutnat.sunshine.SunShine.SunShine; import com.kyo.vjrutnat.sunshine.Utils.UrlWeather; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by VjrutNAT on 12/28/2016. */ public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.ViewHoller> { public static final String TAG = WeatherAdapter.class.getName(); private Context mContext; private ArrayList<Weather> mData; private LayoutInflater mInflater; public WeatherAdapter(Context mContext, ArrayList<Weather> mData, SunShine sunShine) { this.mContext = mContext; this.mData = mData; mInflater = LayoutInflater.from(mContext); } @Override public ViewHoller onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.items_information, parent, false); ViewHoller viewHoller = new ViewHoller(view); return viewHoller; } @Override public void onBindViewHolder(ViewHoller holder, int position) { Weather weather = mData.get(position); Picasso.with(mContext).load(UrlWeather.ICON_WEATHER_URL + weather.getId() + ".png").into(holder.mId); holder.mDay.setText(weather.getDay()); holder.mStatus.setText(weather.getStatus()); holder.mTempeMax.setText(weather.getTemperutare_from()); holder.mTempeMin.setText(weather.getTemperutare_to()); holder.position = position; } @Override public int getItemCount() { return mData.size(); } public class ViewHoller extends RecyclerView.ViewHolder { ImageView mId; TextView mDay; TextView mStatus; TextView mTempeMax; TextView mTempeMin; int position; public ViewHoller(final View itemView) { super(itemView); mId = (ImageView) itemView.findViewById(R.id.imv_static); mDay = (TextView) itemView.findViewById(R.id.tv_day); mStatus = (TextView) itemView.findViewById(R.id.tv_clouds); mTempeMax = (TextView) itemView.findViewById(R.id.tv_temperature_from); mTempeMin = (TextView) itemView.findViewById(R.id.tv_temperature_to); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Weather weatherDetails = mData.get(position); String day = weatherDetails.getDay(); String status = weatherDetails.getStatus(); String tempMax = weatherDetails.getTemperutare_to(); String tempMin = weatherDetails.getTemperutare_from(); String icon = weatherDetails.getId(); String humidity = weatherDetails.getHumidity(); String pressure = weatherDetails.getPressure(); String wind = weatherDetails.getWind(); String date = weatherDetails.getDate(); FragmentManager fragmentManager = ((FragmentActivity) mContext).getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); FragmentDetails fragmentDetails = FragmentDetails.newInstance(day, status, tempMax, tempMin, icon, humidity, pressure, wind, date); transaction.replace(R.id.container, fragmentDetails); transaction.addToBackStack(FragmentDetails.TAG); transaction.commit(); } }); } } }
true
e902bc744d70f6d97c2599c8294728a50d73e8b8
Java
heisehuanyin/ExUI
/src/ws/exui/uiview/ExSplitPane.java
UTF-8
3,527
2.46875
2
[]
no_license
package ws.exui.uiview; import java.awt.geom.Rectangle2D; import ws.exui.uibase.I_GraphicsPort; import ws.exui.uibase.I_Point; import ws.exui.uibase.I_Size; import ws.exui.uibase.WPoint; import ws.exui.uibase.WSize; public class ExSplitPane extends ExView { public final static int HORIZONTAL = 0; public final static int VERTICAL = 1; private int oriented = HORIZONTAL; public ExSplitPane(int oriented) { this.oriented = oriented; } @Override public void __operate_ResizeSubviewSize() { int count = this.view_GetChildCount(); if(this.oriented == HORIZONTAL) { int adjnum = 0; double basicWidths = 0; //统计basicWidth总占用,统计AutoWidth==ture设置子视图数量 for(int i=0;i<count;++i) { I_View one = this.view_GetChildAtIndex(i); if(one.adjust_IsAutoWidth()) { ++adjnum; } basicWidths += one.size_GetBasicSize().getWidth() + one.margin_GetMargin().getLeftSpace() + one.margin_GetMargin().getRightSpace(); } //获取组件可调空间 double voidWidth = this.size_GetVisibleSize().getWidth() - basicWidths; double everyAdj = voidWidth / adjnum; double offSet = 0; //调整每个组件的尺寸 for(int i=0;i<count;++i) { I_View one = this.view_GetChildAtIndex(i); if(one.adjust_IsAutoWidth()) { I_Size vSize = new WSize(one.size_GetBasicSize().getWidth() + everyAdj, one.size_GetVisibleSize().getHeight()); one.size_SetVisibleSize(vSize); } I_Size sizev = new WSize(one.size_GetVisibleSize().getWidth(), this.size_GetVisibleSize().getHeight() - one.margin_GetMargin().getTopSpace() - one.margin_GetMargin().getBottomSpace()); one.size_SetVisibleSize(sizev); offSet += one.margin_GetMargin().getLeftSpace(); I_Point point = new WPoint(offSet ,one.margin_GetMargin().getTopSpace()); one.point_SetOriginPoint(point); offSet += one.size_GetVisibleSize().getWidth() + one.margin_GetMargin().getRightSpace(); } }else { int adjnum = 0; double basicHeights = 0; for(int i=0;i<count;++i) { I_View one = this.view_GetChildAtIndex(i); if(one.adjust_IsAutoHeight()) { ++adjnum; } basicHeights += one.size_GetBasicSize().getHeight()+ one.margin_GetMargin().getTopSpace() + one.margin_GetMargin().getBottomSpace(); } double voidHeight = this.size_GetVisibleSize().getHeight() - basicHeights; double everyAdj = voidHeight / adjnum; double offSet = 0; for(int i=0; i< count; ++i) { I_View one = this.view_GetChildAtIndex(i); if(one.adjust_IsAutoHeight()) { I_Size vSize = new WSize(one.size_GetVisibleSize().getWidth(), one.size_GetBasicSize().getHeight() + everyAdj); one.size_SetVisibleSize(vSize); } I_Size sizel = new WSize(this.size_GetVisibleSize().getWidth() - one.margin_GetMargin().getLeftSpace() - one.margin_GetMargin().getRightSpace(), one.size_GetVisibleSize().getHeight()); one.size_SetVisibleSize(sizel); offSet += one.margin_GetMargin().getTopSpace(); I_Point point = new WPoint(one.margin_GetMargin().getLeftSpace(), offSet); one.point_SetOriginPoint(point); offSet += one.size_GetVisibleSize().getHeight() + one.margin_GetMargin().getBottomSpace(); } } } @Override public void __paintItSelf(I_GraphicsPort port) { Rectangle2D.Double varea = new Rectangle2D.Double(0, 0, this.size_GetVisibleSize().getWidth(), this.size_GetVisibleSize().getHeight()); port.fillShape(varea, null); } }
true
f6cf849cb3ecd8786ac11d63953954fd90cdfe9c
Java
OrgSmells/codehaus-mule-git
/trunk/mule-jbi/core/main/src/java/org/mule/jbi/registry/JbiDescriptor.java
UTF-8
2,771
1.929688
2
[]
no_license
/* * $Id$ * ------------------------------------------------------------------------------------------------------ * * Copyright (c) SymphonySoft Limited. All rights reserved. * http://www.symphonysoft.com * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ package org.mule.jbi.registry; import com.sun.java.xml.ns.jbi.JbiDocument; import org.mule.registry.RegistryComponent; import org.mule.registry.RegistryDescriptor; import org.mule.registry.RegistryException; import org.mule.registry.ValidationException; import java.io.File; import java.io.FileNotFoundException; /** * todo document * * @author <a href="mailto:ross.mason@symphonysoft.com">Ross Mason</a> * @version $Revision: 3 $ */ public class JbiDescriptor implements RegistryDescriptor { public static final String JBI_DESCRIPTOR = "META-INF/jbi.xml"; protected String installRoot; protected JbiDocument.Jbi configuration = null; public JbiDescriptor(JbiDocument.Jbi configuration) throws RegistryException { // if (this.installRoot == null) { // throw new IllegalStateException("installRoot must be set"); // } // this.installRoot = installRoot; // this.configuration = configuration; init(); } public JbiDescriptor(String installRoot) throws RegistryException { if (installRoot == null) { throw new IllegalStateException("installRoot must be set"); } this.installRoot = installRoot; init(); } public RegistryComponent getComponent() { return null; } public boolean isServiceAssembly() { return configuration.isSetServiceAssembly(); } public boolean isComponent() { return configuration.isSetComponent(); } public boolean isSharedLibrary() { return configuration.isSetSharedLibrary(); } public boolean isServices() { return configuration.isSetServices(); } public Object getConfiguration() { return configuration; } protected void init() throws RegistryException { try { if (this.configuration == null) { File file = new File(this.installRoot, JBI_DESCRIPTOR); if (!file.isFile()) { throw new FileNotFoundException(file.getAbsolutePath()); } this.configuration = JbiDocument.Factory.parse(file).getJbi(); validate(); } } catch (Exception e) { throw new RegistryException(e); } } public void validate() throws ValidationException { // Check version number if (this.configuration.getVersion().doubleValue() != 1.0) { throw new ValidationException("version attribute should be '1.0'"); } } }
true
1b0e24b2872a0593c38fc3166bee589c971cb5d9
Java
Deepthi10/APN-Android-App
/app/src/main/java/org/apnplace/model/PreceptorResponse.java
UTF-8
552
2.09375
2
[]
no_license
package org.apnplace.model; import org.apnplace.utility.Details; /** * Created by dlakshmi on 10/25/2016. */ public class PreceptorResponse { String status; Details userdetails; public PreceptorResponse() { } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Details getUserdetails() { return userdetails; } public void setUserdetails(Details userdetails) { this.userdetails = userdetails; } }
true
96b529b0063568e926191c5547dbe05d43ddb3cc
Java
PangDongdon/spring-study
/src/test/java/com/dongdong/spring/test/LeetCode/sort/Sort164.java
UTF-8
1,685
3.5
4
[]
no_license
package com.dongdong.spring.test.leetCode.sort; import org.junit.Test; import java.util.Arrays; /** * @Description: 最大间距 :给定无序的数组,排序后找出最大差值。 * @Date: 2020/8/31 15:41 * @Author: dongdong */ public class Sort164 { public int lookMaxSub(int[] a){ //对数组进行排序 Arrays.sort(a); //对已经排好的数组进行操作 int max=0; if(a.length<2){ return 0; } for(int i=0;i<a.length-1;i++){ int ss=a[i+1]-a[i]; if(ss>max){ max=ss; } } return max; } @Test public void test(){ int[] ss={1,3,6,9,90}; System.out.println(lookMaxSub(ss)); } public static class Solution1{ public int maximumGap(int[] nums){ if(nums.length<2){ return 0; } Arrays.sort(nums); int max=Integer.MIN_VALUE; for(int i=1;i<nums.length;){ while(i<nums.length && nums[i]==nums[i-1]){ i++; } if(i==nums.length){ i--; max=(nums[i]-nums[i-1]>max) ? nums[i]-nums[i-1] :max; break; }else{ max=(nums[i]-nums[i-1]>max) ? nums[i]-nums[i-1] :max; } if(nums[i]!=nums[i-1]){ i++; } } return max; } @Test public void test(){ int[] ss={1,3,6,9,90}; System.out.println(maximumGap(ss)); } } }
true
a6c3070d963215368e13bf3365e1fc3b63246f01
Java
jcortavee/spring-control-access
/src/main/java/com/umg/accesscontrol/security/AuthenticationFilter.java
UTF-8
3,174
2.203125
2
[]
no_license
package com.umg.accesscontrol.security; import com.fasterxml.jackson.databind.ObjectMapper; import com.umg.accesscontrol.SpringApplicationContext; import com.umg.accesscontrol.models.UserLoginRequest; import com.umg.accesscontrol.services.UserService; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; public AuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { UserLoginRequest credentials = new ObjectMapper() .readValue(request.getInputStream(), UserLoginRequest.class); return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword(), new ArrayList<>() ) ); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String username = ((User) authResult.getPrincipal()).getUsername(); String token = Jwts.builder() .setSubject(username) .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, SecurityConstants.TOKEN_SECRET) .compact(); System.out.println(username); UserService userService = (UserService) SpringApplicationContext.getBean("userServiceImpl"); com.umg.accesscontrol.models.User user = userService.getUser(username); response.addHeader("UserID", String.valueOf(user.getId())); response.addHeader("Role", String.valueOf(user.getRole().getRole())); response.addHeader("Access-Control-Expose-Headers", "Authorization,Role,UserID"); response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token); } }
true
72e9fe933777f1b229191bb64c7f1b9b5e28fbd6
Java
Talend/apache-camel
/core/camel-management/src/main/java/org/apache/camel/management/mbean/RouteCoverageXmlParser.java
UTF-8
9,558
1.84375
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management.mbean; import java.io.InputStream; import java.util.Stack; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.apache.camel.CamelContext; import org.apache.camel.api.management.ManagedCamelContext; import org.apache.camel.api.management.mbean.ManagedProcessorMBean; import org.apache.camel.api.management.mbean.ManagedRouteMBean; /** * An XML parser that uses SAX to enrich route stats in the route dump. * <p/> * The coverage details: * <ul> * <li>exchangesTotal - Total number of exchanges</li> * <li>totalProcessingTime - Total processing time in millis</li> * </ul> * Is included as attributes on the route nodes. */ public final class RouteCoverageXmlParser { private RouteCoverageXmlParser() { } /** * Parses the XML. * * @param camelContext the CamelContext * @param is the XML content as an input stream * @return the DOM model of the routes with coverage information stored as attributes * @throws Exception is thrown if error parsing */ public static Document parseXml(final CamelContext camelContext, final InputStream is) throws Exception { final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); final SAXParser parser = factory.newSAXParser(); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); final DocumentBuilder docBuilder = dbf.newDocumentBuilder(); final Document doc = docBuilder.newDocument(); final Stack<Element> elementStack = new Stack<>(); final StringBuilder textBuffer = new StringBuilder(); final DefaultHandler handler = new DefaultHandler() { @Override public void setDocumentLocator(final Locator locator) { // noop } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { addTextIfNeeded(); final Element el = doc.createElement(qName); // add other elements for (int i = 0; i < attributes.getLength(); i++) { el.setAttribute(attributes.getQName(i), attributes.getValue(i)); } String id = el.getAttribute("id"); if (id != null) { try { if ("route".equals(qName)) { ManagedRouteMBean route = camelContext.getCamelContextExtension() .getContextPlugin(ManagedCamelContext.class).getManagedRoute(id); if (route != null) { long total = route.getExchangesTotal(); el.setAttribute("exchangesTotal", Long.toString(total)); long totalTime = route.getTotalProcessingTime(); el.setAttribute("totalProcessingTime", Long.toString(totalTime)); } } else if ("from".equals(qName)) { // grab statistics from the parent route as from would be the same Element parent = elementStack.peek(); if (parent != null) { String routeId = parent.getAttribute("id"); ManagedRouteMBean route = camelContext.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class) .getManagedRoute(routeId); if (route != null) { long total = route.getExchangesTotal(); el.setAttribute("exchangesTotal", Long.toString(total)); long totalTime = route.getTotalProcessingTime(); el.setAttribute("totalProcessingTime", Long.toString(totalTime)); // from is index-0 el.setAttribute("index", "0"); } } } else { ManagedProcessorMBean processor = camelContext.getCamelContextExtension().getContextPlugin(ManagedCamelContext.class) .getManagedProcessor(id); if (processor != null) { long total = processor.getExchangesTotal(); el.setAttribute("exchangesTotal", Long.toString(total)); long totalTime = processor.getTotalProcessingTime(); el.setAttribute("totalProcessingTime", Long.toString(totalTime)); int index = processor.getIndex(); el.setAttribute("index", Integer.toString(index)); } } } catch (Exception e) { // ignore } } // we do not want customId in output of the EIPs if (!"route".equals(qName)) { el.removeAttribute("customId"); } elementStack.push(el); } @Override public void endElement(final String uri, final String localName, final String qName) { addTextIfNeeded(); final Element closedEl = elementStack.pop(); if (elementStack.isEmpty()) { // is this the root element? doc.appendChild(closedEl); } else { final Element parentEl = elementStack.peek(); parentEl.appendChild(closedEl); } } @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { textBuffer.append(ch, start, length); } /** * outputs text accumulated under the current node */ private void addTextIfNeeded() { if (textBuffer.length() > 0) { final Element el = elementStack.peek(); final Node textNode = doc.createTextNode(textBuffer.toString()); el.appendChild(textNode); textBuffer.delete(0, textBuffer.length()); } } }; parser.parse(is, handler); return doc; } }
true
2bc51d4e780f55da9494c799d9dfae658bdd591b
Java
DelomLiu/data-structure
/稀疏数组/SparseArray.java
UTF-8
4,745
3.65625
4
[]
no_license
import java.io.*; public class SparseArray { public static void main(String[] args) throws IOException { // 创建一个原始的二维数组11*11 // 0代表没有棋子,1代表黑子,2代表篮子 int[][] chessArray = new int[11][11]; chessArray[1][2] = 1; chessArray[2][3] = 2; chessArray[4][5] = 2; // 输出原始的二维数组 System.out.println("原始的二维数组:"); for (int[] row : chessArray) { for (int data : row) { System.out.print(data + "\t"); } System.out.println(); } // 二维数组 转 稀疏数组 // 1、遍历原始的二维数组,得到非0数据的个数 int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 1; j < 11; j++) { if (chessArray[i][j] != 0) sum++; } } // 2、创建对应的稀疏数组 int sparseArray[][] = new int[sum + 1][3]; // 给稀疏数组赋值 sparseArray[0][0] = 11; sparseArray[0][1] = 11; sparseArray[0][2] = sum; // 遍历二维数组,将非0数据放到sparseArray中 int count = 0; // 用于记录是第几个非0数据 for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if (chessArray[i][j] != 0) { count++; sparseArray[count][0] = i; sparseArray[count][1] = j; sparseArray[count][2] = chessArray[i][j]; } } } System.out.println(); // 输出稀疏数组 System.out.println("得到的稀疏数组:"); for (int i = 0; i < sparseArray.length; i++) { System.out.println(sparseArray[i][0] + "\t" + sparseArray[i][1] + "\t" + sparseArray[i][2]); } System.out.println(); // 将稀疏数组保存到棋盘上,并命名为map.data // 创建map.data File file = new File("稀疏数组/map.data"); if (file.exists()) { System.out.println("文件已经存在"); } else { try { file.createNewFile(); System.out.println("文件创建成功"); } catch (Exception e) { e.printStackTrace(); } } // 写入 FileWriter f1 = null; try { f1 = new FileWriter(file);// 创建文件写入对象 for (int i = 0; i < sparseArray.length; i++) { for (int j = 0; j < 3; j++) { f1.write(sparseArray[i][j] + "\t"); } f1.write("\r\n"); } f1.close(); } catch (Exception e) { e.printStackTrace(); } // 从map.data里面读取稀疏数组 BufferedReader bufferedReader = null; // 为读取的稀疏数组分配空间 int[][] datas = new int[sparseArray.length][3]; try { InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file)); bufferedReader = new BufferedReader(inputStreamReader); String line = null; int i = 0; // 按行读取 while ((line = bufferedReader.readLine()) != null) { if (line != null) { // 将按行读取的字符串按空格分割,得到一个string数组 String[] strings = line.split("\\t"); // 依次转换为int类型存入到分配好空间的数组中 for (int k = 0; k < strings.length; k++) { datas[i][k] = Integer.valueOf(strings[k]); } // 行数加1 i++; } } } catch (Exception e) { e.printStackTrace(); } // 将稀疏数组 恢复成 二维数组 // 1、先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组 int newArray[][] = new int[datas[0][0]][datas[0][1]]; // 2、读取稀疏数组后几行的数据,并赋给原始的二维数组 for (int i = 1; i < datas.length; i++) { newArray[datas[i][0]][datas[i][1]] = datas[i][2]; } System.out.println(); // 输出恢复后的二维数组 System.out.println("恢复后的二维数组:"); for (int[] row : newArray) { for (int data : row) { System.out.print(data + "\t"); } System.out.println(); } } }
true
cd09ab6864e53f6086d649b7173301aa47456c16
Java
joansmith/sonar-java
/java-checks-testkit/src/test/java/org/sonar/java/checks/verifier/XmlCheckVerifierTest.java
UTF-8
5,873
1.84375
2
[]
no_license
/* * SonarQube Java * Copyright (C) 2012-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.java.checks.verifier; import com.google.common.collect.Lists; import org.fest.assertions.Fail; import org.junit.Test; import org.mockito.Mockito; import org.sonar.java.checks.verifier.XmlCheckVerifier.FakeXmlCheckContext; import org.sonar.java.xml.XmlCheck; import org.sonar.java.xml.XmlCheckContext; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.File; import java.io.IOException; import static org.fest.assertions.Assertions.assertThat; public class XmlCheckVerifierTest { private static final String XML_WITH_ISSUES = "src/test/files/xml/XmlCheckVerifier.xml"; private static final String XML_WITH_SECONDARIES = "src/test/files/xml/XmlCheckVerifierSecondaries.xml"; private static final String XML_NO_ISSUE = "src/test/files/xml/XmlCheckVerifierNoIssue.xml"; private static final String XML_PARSING_ISSUE = "src/test/files/xml/XmlCheckVerifierParsingIssue.xml"; private static XmlCheckContext fakeContext; @Test public void should_detect_issues() { XmlCheckVerifier.verify(XML_WITH_ISSUES, new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { fakeContext = context; context.reportIssue(this, 2, "Message1"); context.reportIssue(this, 4, "Message2"); } }); assertThat(((FakeXmlCheckContext) fakeContext).getMessages()).hasSize(2); } @Test public void should_detect_issues_using_nodes() { XmlCheckVerifier.verify(XML_WITH_ISSUES, new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { try { context.reportIssue(this, firstNode(context, "//test2"), "Message1"); context.reportIssue(this, firstNode(context, "//test4"), "Message2"); } catch (Exception e) { Fail.fail(); } } }); } @Test public void should_detect_issues_using_secondaries() { XmlCheckVerifier.verify(XML_WITH_SECONDARIES, new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { try { context.reportIssue( this, firstNode(context, "//test2"), "Message1", Lists.newArrayList(new XmlCheckContext.XmlDocumentLocation("Message2", firstNode(context, "//test4")))); } catch (Exception e) { Fail.fail(); } } }); } private static Node firstNode(XmlCheckContext context, String expression) throws XPathExpressionException { Node result = null; for (Node node : context.evaluateOnDocument(context.compile(expression))) { result = node; break; } return result; } @Test public void should_fail_when_adding_issues_on_unknown_node() { try { XmlCheckVerifier.verify(XML_WITH_ISSUES, new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(context.getFile()); Node node = ((NodeList) XPathFactory.newInstance().newXPath().compile("//test2").evaluate(doc, XPathConstants.NODESET)).item(0); context.reportIssue(this, node, "Message1"); } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { Fail.fail(); } } }); } catch (AssertionError e) { assertThat(e).hasMessage("The provided node does not have line attribute 'start_column'"); } } @Test public void should_detect_issue_on_file() { XmlCheckVerifier.verifyIssueOnFile(XML_NO_ISSUE, "Message", new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { context.reportIssueOnFile(this, "Message"); } }); } @Test public void should_not_detect_issue() { XmlCheckVerifier.verifyNoIssue(XML_NO_ISSUE, new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { // do nothing } }); } @Test(expected = AssertionError.class) public void should_fail_when_parsing_issue() { XmlCheckVerifier.verifyNoIssue(XML_PARSING_ISSUE, new XmlCheck() { @Override public void scanFile(XmlCheckContext context) { // do nothing } }); } @Test(expected = AssertionError.class) public void should_fail_retrieving_messages_when_parsing_issue() { XmlCheckVerifier.retrieveExpectedIssuesFromFile(new File(XML_PARSING_ISSUE), Mockito.mock(CheckVerifier.class)); } @Test(expected = AssertionError.class) public void should_fail_retrieving_messages_when_files_does_not_exist() { XmlCheckVerifier.retrieveExpectedIssuesFromFile(new File(""), Mockito.mock(CheckVerifier.class)); } }
true
3030b8cddce9bc794a959b74a7b5eba32ca35ceb
Java
caibou/TvPinyinIME
/ime/src/main/java/me/caibou/ime/keyboard/KeyboardLoader.java
UTF-8
13,397
1.867188
2
[]
no_license
package me.caibou.ime.keyboard; import android.content.Context; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.KeyEvent; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.regex.Pattern; import me.caibou.ime.MeasureHelper; import me.caibou.ime.R; import me.caibou.ime.XmlParseUtil; import me.caibou.ime.pattern.Element; import me.caibou.ime.pattern.KeyRow; import me.caibou.ime.pattern.SoftKey; /** * @author caibou */ public class KeyboardLoader { private static final String TAG = "KeyboardLoader"; private static final String TAG_KEYBOARD = "keyboard"; private static final String TAG_ROW = "row"; private static final String TAG_KEYS = "keys"; private static final String TAG_KEY = "key"; private static final String ATTR_KEYBOARD_BACKGROUND_COLOR = "keyboard_background_color"; private static final String ATTR_DEF_KEY_TEXT_COLOR = "default_soft_key_label_color"; private static final String ATTR_DEF_KEY_NORMAL_COLOR = "soft_key_normal_bg_color"; private static final String ATTR_DEF_KEY_STROKE_COLOR = "default_soft_key_stroke_color"; private static final String ATTR_DEF_KEY_SELECTED_COLOR = "default_soft_key_selected_bg_color"; private static final String ATTR_DEF_KEY_PRESSED_COLOR = "default_soft_key_pressed_bg_color"; private static final String ATTR_DEF_KEY_WIDTH = "default_soft_key_width"; private static final String ATTR_DEF_KEY_HEIGHT = "default_soft_key_height"; private static final String ATTR_DEF_KEY_STROKE_WIDTH = "default_soft_key_stroke_width"; private static final String ATTR_DEF_KEY_ICON_SIZE = "default_soft_key_icon_size"; private static final String ATTR_DEF_KEYS_SPACING = "default_soft_keys_spacing"; private static final String ATTR_DEF_POS_X = "default_position_x"; private static final String ATTR_DEF_POS_Y = "default_position_y"; private static final String ATTR_LABEL = "label"; private static final String ATTR_LABELS = "labels"; private static final String ATTR_KEYCODE = "keycode"; private static final String ATTR_CODES = "codes"; private static final String ATTR_SPLITTER = "splitter"; private static final String ATTR_KEY_TEXT_SIZE = "text_size"; private static final String ATTR_ICON = "icon"; private static final String ATTR_WIDTH = "width"; private static final String ATTR_HEIGHT = "height"; private static final String ATTR_POS_X = "pos_x"; private static final String ATTR_POS_Y = "pos_y"; private static final String ATTR_CROSS_ROW = "cross_row"; private static final String ATTR_CROSS_COLUMNS = "cross_columns"; private static final String ATTR_TEXT_COLOR = "text_color"; private static final String ATTR_ICON_WIDTH = "icon_width"; private static final String ATTR_ICON_HEIGHT = "icon_height"; private static final String ATTR_STROKE_COLOR = "stroke_color"; private static final String ATTR_STROKE_WIDTH = "stroke_width"; private static final String ATTR_NORMAL_BG_COLOR = "normal_bg_color"; private static final String ATTR_PRESSED_COLOR = "pressed_color"; private static final String ATTR_SELECTED_COLOR = "selected_color"; private static final String ATTR_LABEL_ORIENTATION = "label_orientation"; private Resources resources; private int defKeyTextColor, defKeyNormalColor, defKeyStrokeColor, defKeySelectedColor, defPressedColor; private float defKeyStrokeWidth, defKeyIconSize, defTextSize; private float defKeyWidth, defKeyHeight, defPosX, defPosY, defKeySpacing; private float nextPosX, nextPosY; public KeyboardLoader(@NonNull Context context) { resources = context.getResources(); } public SoftKeyboard load(int keyboardId) { SoftKeyboard softKeyboard = new SoftKeyboard(); XmlResourceParser xmlParser = resources.getXml(keyboardId); try { int event = xmlParser.next(); while (event != XmlPullParser.END_DOCUMENT) { if (event == XmlResourceParser.START_TAG) { parseElementStartTag(xmlParser, softKeyboard); } else if (event == XmlResourceParser.END_TAG) { parseElementEndTag(xmlParser, softKeyboard); } event = xmlParser.next(); } } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { xmlParser.close(); } return softKeyboard; } private void parseElementEndTag(XmlResourceParser xmlParser, SoftKeyboard softKeyboard) { String attr = xmlParser.getName().toLowerCase(); switch (attr) { case TAG_ROW: nextPosX = defPosX; nextPosY += (defKeySpacing + defKeyHeight); break; } } private void parseElementStartTag(XmlResourceParser xmlParser, @NonNull SoftKeyboard softKeyboard) { String attr = xmlParser.getName().toLowerCase(); switch (attr) { case TAG_KEYBOARD: loadDefaultConfig(xmlParser); loadKeyboard(xmlParser, softKeyboard); nextPosX = defPosX; nextPosY = defPosY; break; case TAG_ROW: loadRow(softKeyboard); break; case TAG_KEYS: loadKeys(xmlParser, softKeyboard); break; case TAG_KEY: loadSingleKey(xmlParser, softKeyboard); break; } } private void loadDefaultConfig(XmlResourceParser xmlParser) { defKeyTextColor = XmlParseUtil.loadColor(resources, xmlParser, ATTR_DEF_KEY_TEXT_COLOR, resources.getColor(R.color.default_soft_key_label)); defKeyNormalColor = XmlParseUtil.loadColor(resources, xmlParser, ATTR_DEF_KEY_NORMAL_COLOR, resources.getColor(R.color.default_soft_key_normal_bg)); defKeyStrokeColor = XmlParseUtil.loadColor(resources, xmlParser, ATTR_DEF_KEY_STROKE_COLOR, resources.getColor(R.color.default_soft_key_stroke)); defKeySelectedColor = XmlParseUtil.loadColor(resources, xmlParser, ATTR_DEF_KEY_SELECTED_COLOR, resources.getColor(R.color.default_key_selected_bg)); defPressedColor = XmlParseUtil.loadColor(resources, xmlParser, ATTR_DEF_KEY_PRESSED_COLOR, resources.getColor(R.color.default_key_pressed_bg)); defKeyWidth = loadWidth(resources, xmlParser, ATTR_DEF_KEY_WIDTH, loadPercentValue(resources, MeasureHelper.KEYBOARD_WIDTH, R.string.default_soft_key_width)); defKeyHeight = loadHeight(resources, xmlParser, ATTR_DEF_KEY_HEIGHT, loadPercentValue(resources, MeasureHelper.KEYBOARD_HEIGHT, R.string.default_soft_key_height)); defPosX = loadWidth(resources, xmlParser, ATTR_DEF_POS_X, loadPercentValue(resources, MeasureHelper.KEYBOARD_WIDTH, R.string.default_soft_key_height)); defPosY = loadHeight(resources, xmlParser, ATTR_DEF_POS_Y, loadPercentValue(resources, MeasureHelper.KEYBOARD_HEIGHT, R.string.default_soft_key_height)); defKeyStrokeWidth = XmlParseUtil.loadDimen(resources, xmlParser, ATTR_DEF_KEY_STROKE_WIDTH, resources.getDimension(R.dimen.default_soft_key_stroke_width)); defKeyIconSize = loadWidth(resources, xmlParser, ATTR_DEF_KEY_ICON_SIZE, loadPercentValue(resources, MeasureHelper.KEYBOARD_WIDTH, R.string.default_soft_key_icon_size)); defTextSize = loadWidth(resources, xmlParser, ATTR_KEY_TEXT_SIZE, loadPercentValue(resources, MeasureHelper.KEYBOARD_WIDTH, R.string.default_soft_key_text_size)); } private void loadKeyboard(XmlResourceParser xmlParser, SoftKeyboard keyboard) { keyboard.backgroundColor = XmlParseUtil.loadColor( resources, xmlParser, ATTR_KEYBOARD_BACKGROUND_COLOR, R.color.keyboard_background_color); defKeySpacing = loadWidth(resources, xmlParser, ATTR_DEF_KEYS_SPACING, 0.009375f * MeasureHelper.KEYBOARD_WIDTH); keyboard.horizontalSpacing = defKeySpacing; keyboard.verticalSpacing = defKeySpacing; } private void loadRow(@NonNull SoftKeyboard softKeyboard) { KeyRow keyRow = new KeyRow(); softKeyboard.addKeyRow(keyRow); } private void loadKeys(XmlResourceParser xmlParser, SoftKeyboard softKeyboard) { String splitter = Pattern.quote(XmlParseUtil.loadString(resources, xmlParser, ATTR_SPLITTER)); if (!TextUtils.isEmpty(splitter)) { String[] keys = XmlParseUtil.loadString(resources, xmlParser, ATTR_CODES).split(splitter); String[] labels = XmlParseUtil.loadString(resources, xmlParser, ATTR_LABELS).split(splitter); for (int i = 0, size = keys.length; i < size; i++) { SoftKey softKey = getSoftKey(xmlParser); softKey.keyLabel = labels[i]; softKey.keyCode = Integer.parseInt(keys[i]); softKeyboard.addSoftKey(softKey); } } } private void loadSingleKey(XmlResourceParser xmlParser, @NonNull SoftKeyboard softKeyboard) { SoftKey softKey = getSoftKey(xmlParser); softKeyboard.addSoftKey(softKey); } private void loadPattern(Element element, XmlResourceParser xmlParser) { float width = loadWidth(resources, xmlParser, ATTR_WIDTH, defKeyWidth); float height = loadHeight(resources, xmlParser, ATTR_HEIGHT, defKeyHeight); float left = loadWidth(resources, xmlParser, ATTR_POS_X, nextPosX); float top = loadHeight(resources, xmlParser, ATTR_POS_Y, nextPosY); element.width = width; element.height = height; element.left = left; element.top = top; } @NonNull private SoftKey getSoftKey(XmlResourceParser xmlParser) { SoftKey softKey = new SoftKey(); softKey.keyCode = XmlParseUtil.loadInt( resources, xmlParser, ATTR_KEYCODE, KeyEvent.KEYCODE_UNKNOWN); softKey.textColor = XmlParseUtil.loadColor( resources, xmlParser, ATTR_TEXT_COLOR, defKeyTextColor); softKey.textSize = loadWidth( resources, xmlParser, ATTR_KEY_TEXT_SIZE, defTextSize); softKey.keyLabel = XmlParseUtil.loadString( resources, xmlParser, ATTR_LABEL); softKey.crossColumn = XmlParseUtil.loadInt( resources, xmlParser, ATTR_CROSS_COLUMNS, 1); softKey.crossRow = XmlParseUtil.loadInt( resources, xmlParser, ATTR_CROSS_ROW, 1); softKey.iconWidth = loadWidth( resources, xmlParser, ATTR_ICON_WIDTH, defKeyIconSize); softKey.iconHeight = loadHeight( resources, xmlParser, ATTR_ICON_HEIGHT, defKeyIconSize); softKey.normalColor = XmlParseUtil.loadColor( resources, xmlParser, ATTR_NORMAL_BG_COLOR, defKeyNormalColor); softKey.pressedColor = XmlParseUtil.loadColor( resources, xmlParser, ATTR_PRESSED_COLOR, defPressedColor); softKey.selectedColor = XmlParseUtil.loadColor( resources, xmlParser, ATTR_SELECTED_COLOR, defKeySelectedColor); softKey.strokeColor = XmlParseUtil.loadColor( resources, xmlParser, ATTR_STROKE_COLOR, defKeyStrokeColor); softKey.strokeWidth = XmlParseUtil.loadDimen( resources, xmlParser, ATTR_STROKE_WIDTH, defKeyStrokeWidth); softKey.orientation = XmlParseUtil.loadInt( resources, xmlParser, ATTR_LABEL_ORIENTATION, SoftKey.HORIZONTAL); softKey.icon = XmlParseUtil.loadDrawable( resources, xmlParser, ATTR_ICON); loadPattern(softKey, xmlParser); fixKeyRect(softKey); calNextPosX(softKey); return softKey; } private void calNextPosX(Element element) { nextPosX = element.right + defKeySpacing; } private void fixKeyRect(SoftKey softKey) { softKey.width = softKey.width * softKey.crossColumn + defKeySpacing * (softKey.crossColumn - 1); softKey.height = softKey.height * softKey.crossRow + defKeySpacing * (softKey.crossRow - 1); softKey.fixRange(); } private float loadWidth(Resources res, XmlResourceParser parser, String attr, float defValue) { float percent = XmlParseUtil.loadFloat(res, parser, attr, XmlParseUtil.NON_VALUE); if (percent == XmlParseUtil.NON_VALUE) { return defValue; } return percent * MeasureHelper.KEYBOARD_WIDTH; } private float loadHeight(Resources res, XmlResourceParser parser, String attr, float defValue) { float percent = XmlParseUtil.loadFloat(res, parser, attr, XmlParseUtil.NON_VALUE); if (percent == XmlParseUtil.NON_VALUE) { return defValue; } return percent * MeasureHelper.KEYBOARD_HEIGHT; } private float loadPercentValue(Resources res, float parent, int resId) { return Float.parseFloat(res.getString(resId)) * parent; } }
true
a6f023f24d308d4a1908adcb4a7e30f541a3983c
Java
emilioalvarezdiaz/ea-front-sdk-android
/ea-sdk/src/main/java/sdk/dive/tv/ui/modules/Seasons.java
UTF-8
810
1.945313
2
[]
no_license
package sdk.dive.tv.ui.modules; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.touchvie.sdk.model.Card; import sdk.dive.tv.ui.modules.viewholders.SeasonsHolder; /** * Created by Tagsonomy S.L. on 13/10/2016. */ public class Seasons extends HorizontalListModule { public Seasons() { super(); } @Override public RecyclerView.ViewHolder getViewHolder(LayoutInflater inflater, ViewGroup group) { ViewGroup viewGroup = (ViewGroup) inflater.inflate(this.layout, group, false); SeasonsHolder holder = new SeasonsHolder(viewGroup, getClass().getSimpleName()); return holder; } @Override public boolean validate(Card cardData, boolean isCarousel) { return true; } }
true
7c8b186229480dcd1a13c360cad523ff40d33528
Java
wwj912790488/supervisor
/common/src/main/java/com/arcsoft/supervisor/repository/settings/impl/TimeRepositoryImplRHEL.java
UTF-8
5,062
2.34375
2
[]
no_license
package com.arcsoft.supervisor.repository.settings.impl; import com.arcsoft.supervisor.model.domain.settings.NTPStatus; import com.arcsoft.supervisor.repository.settings.TimeRepository; import com.arcsoft.supervisor.utils.app.App; import com.arcsoft.supervisor.utils.app.ShellException; import org.springframework.stereotype.Repository; import java.io.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; /** * Implementation in centos for TimeDao * * @author xpeng * */ @Repository public class TimeRepositoryImplRHEL implements TimeRepository { private static final String ZONE_DIR = "/usr/share/zoneinfo/"; private static final String ZONE_SELF_CONFIG = "/etc/tz0001.conf"; @Override public List<String> listTimeZone(String main) throws ShellException, IOException { File dir = new File(ZONE_DIR + main); String names[] = dir.list(); Arrays.sort(names); for(String name : names){ System.out.println(name); } return Arrays.asList(names); } @Override public void setTimezone(String timezone) throws ShellException, IOException { String cmd = "ln -sf " + ZONE_DIR + timezone + " /etc/localtime"; StringWriter sw = new StringWriter(); App.syncExec(null, cmd, sw); try(BufferedWriter bw = new BufferedWriter(new FileWriter(ZONE_SELF_CONFIG))){ bw.write(timezone); } } @Override public String getTimezone() throws ShellException, IOException { //get self config file try(BufferedReader br = new BufferedReader(new FileReader(ZONE_SELF_CONFIG))){ return br.readLine(); }catch(FileNotFoundException e){ String cmd = "cat /etc/sysconfig/clock"; StringWriter sw = new StringWriter(); App.syncExec(null, cmd, sw); String ret = sw.toString(); String[] a = ret.split("\""); if(a.length > 2) return a[1]; } return null; } @Override public void setSystemTime(Date date) throws ShellException, IOException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String strDate = df.format(date); String cmd = "date -s \"" + strDate + "\""; StringWriter sw = new StringWriter(); App.syncExec(null, cmd, sw); //write the time to CMOS App.syncExec(null, "clock -w", sw); } @Override public NTPStatus getNTPStatus() throws ShellException, IOException { NTPStatus ntpStatus = new NTPStatus(); //get service status; String cmd = "service ntpd status"; StringWriter sw = new StringWriter(); App.syncExec(null, cmd, sw); String ret = sw.toString(); if(ret.contains("running")){ ntpStatus.setIsServiceOn(true); } //get ntp servers ntpStatus.setNtpServers(getNtpServers()); return ntpStatus; } @Override public void syncWithNTP(NTPStatus ntp) throws ShellException, IOException { String cmd = null; StringWriter sw = null; // to start ntp service if (ntp.getIsServiceOn()) { List<String> servers = ntp.getNtpServers(); if (servers.size() == 0) return; // first: stop ntpd service cmd = "service ntpd stop"; sw = new StringWriter(); App.syncExec(null, cmd, sw); // force to sync right now cmd = "ntpdate " + servers.get(0); sw = new StringWriter(); App.syncExec(null, cmd, sw); // add server address to conf setNTPServers(servers); // start the ntp service cmd = "service ntpd start"; sw = new StringWriter(); App.syncExec(null, cmd, sw); // start service on startup cmd = "chkconfig ntpd on"; sw = new StringWriter(); App.syncExec(null, cmd, sw); } else { //stop ntp service cmd = "service ntpd stop"; sw = new StringWriter(); App.syncExec(null, cmd, sw); } } private List<String> getNtpServers() throws IOException { String filename = "/etc/ntp.conf"; List<String> srevers = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String strContent = null; while ((strContent = br.readLine()) != null) { if (strContent.matches("^server\\s.*$")) { String[] results = strContent.split("\\s+"); if (results.length > 1 && results[1].length() > 0) srevers.add(results[1]); } } } return srevers; } private void setNTPServers(List<String> servers) throws IOException { String filename = "/etc/ntp.conf"; String filetmp = "/etc/ntp.conf.tmp"; StringBuffer sb = new StringBuffer(); //read and replace server try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String strContent = null; while ((strContent = br.readLine()) != null) { if (strContent.startsWith("server")) { strContent = ""; } sb.append(strContent).append("\n"); } } for(String server : servers){ sb.append("server " + server + "\n"); } //save the tmp file try(BufferedWriter bw = new BufferedWriter(new FileWriter(filetmp))){ bw.write(sb.toString()); } File file = new File(filename); File tmp = new File(filetmp); file.delete(); tmp.renameTo(file); } }
true
cbc18ffa7fca7c2dcd3c45d997ff7a5e3839e52c
Java
vandongkyd/GitBuyer
/presentation/src/main/java/com/fernandocejas/android10/sample/presentation/view/fragment/BaseWithMediaPickerFragment.java
UTF-8
9,281
1.867188
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.fernandocejas.android10.sample.presentation.view.fragment; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.content.FileProvider; import com.fernandocejas.android10.order.presentation.utils.Utils; import com.fernandocejas.android10.sample.presentation.dialog.SelectMediaModeDialog; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import static android.app.Activity.RESULT_OK; /** * Created by jerry on Feb-12-18. */ public abstract class BaseWithMediaPickerFragment extends BaseFragment { private static final int REQUEST_PERMISSION_FROM_REQUEST_LOAD_MEDIA = 101; private static final int REQUEST_PERMISSION_FROM_REQUEST_MEDIA_CAPTURE = 102; private static final int REQUEST_LOAD_IMAGE = 105; private static final int REQUEST_IMAGE_CAPTURE = 106; private static final int REQUEST_LOAD_VIDEO = 107; private static final int REQUEST_VIDEO_CAPTURE = 108; private static final int MEDIA_TYPE_PHOTO = 108; private static final int MEDIA_TYPE_VIDEO = 109; private SelectMediaModeDialog selectMediaModeDialog; private String currentPhotoPath; private SelectMediaModeDialog.OnClickListener onSelectMediaModeDialogClickListener = new SelectMediaModeDialog.OnClickListener() { @Override public void onCameraClicked() { BaseWithMediaPickerFragment.this.onCameraClicked(); } @Override public void onGalleryClicked() { BaseWithMediaPickerFragment.this.onGalleryClicked(); } @Override public void onDismissClicked() { } }; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_LOAD_IMAGE || requestCode == REQUEST_IMAGE_CAPTURE) { if (resultCode == RESULT_OK) { String picturePath = currentPhotoPath; if (data != null) { Uri selectedImage = data.getData(); if (selectedImage != null) { String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getActivity().getApplicationContext().getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); picturePath = cursor.getString(columnIndex); cursor.close(); } } onPhotoPicked(picturePath); } } else if (requestCode == REQUEST_LOAD_VIDEO || requestCode == REQUEST_VIDEO_CAPTURE) { if (resultCode == RESULT_OK) { if (data != null) { Uri selectedVideo = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getActivity().getApplicationContext().getContentResolver().query(selectedVideo, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String videoPath = cursor.getString(columnIndex); cursor.close(); onVideoPicked(videoPath); } } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_PERMISSION_FROM_REQUEST_LOAD_MEDIA: if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { onGalleryClicked(); } break; case REQUEST_PERMISSION_FROM_REQUEST_MEDIA_CAPTURE: if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { onCameraClicked(); } break; default: break; } } public void onPhotoClicked() { if (this.selectMediaModeDialog == null) { this.selectMediaModeDialog = new SelectMediaModeDialog(getActivity()); this.selectMediaModeDialog.setOnClickListener(onSelectMediaModeDialogClickListener); } this.selectMediaModeDialog.setMedia_type(MEDIA_TYPE_PHOTO); this.selectMediaModeDialog.show(); } public void onVideoClicked() { if (this.selectMediaModeDialog == null) { this.selectMediaModeDialog = new SelectMediaModeDialog(getActivity()); this.selectMediaModeDialog.setOnClickListener(onSelectMediaModeDialogClickListener); } this.selectMediaModeDialog.setMedia_type(MEDIA_TYPE_VIDEO); this.selectMediaModeDialog.show(); } public void onCameraClicked() { if (requestPermissions(REQUEST_PERMISSION_FROM_REQUEST_MEDIA_CAPTURE, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})) { return; } if (selectMediaModeDialog.getMedia_type() == MEDIA_TYPE_PHOTO) { Intent i = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (i.resolveActivity(getActivity().getApplicationContext().getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { ex.printStackTrace(); // Error occurred while creating the File } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), "com.global.buyer.file_provider", photoFile); i.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(i, REQUEST_IMAGE_CAPTURE); } } } else if (selectMediaModeDialog.getMedia_type() == MEDIA_TYPE_VIDEO) { Intent i = new Intent( MediaStore.ACTION_VIDEO_CAPTURE); if (i.resolveActivity(getActivity().getApplicationContext().getPackageManager()) != null) { startActivityForResult(i, REQUEST_VIDEO_CAPTURE); } } } public void onGalleryClicked() { if (requestPermissions(REQUEST_PERMISSION_FROM_REQUEST_LOAD_MEDIA, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})) { return; } if (selectMediaModeDialog.getMedia_type() == MEDIA_TYPE_PHOTO) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); i.setType("image/*"); startActivityForResult(i, REQUEST_LOAD_IMAGE); } else if (selectMediaModeDialog.getMedia_type() == MEDIA_TYPE_VIDEO) { Intent i = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, REQUEST_LOAD_VIDEO); } } public boolean requestPermissions(int requestCode, String[] permissions) { if (!Utils.verifyPermissions(getActivity(), permissions)) { requestPermissions( permissions, requestCode ); return true; } return false; } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getActivity().getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents currentPhotoPath = image.getAbsolutePath(); return image; } public abstract void onPhotoPicked(String path); public abstract void onVideoPicked(String path); }
true
f126e8c75e9fd0384e5d2d9e5170002194bef082
Java
ws5798980/SBProject
/wPortal/src/main/java/com/rs/mobile/wportal/activity/xsgr/CommodityManagementActivity.java
UTF-8
25,510
1.539063
2
[]
no_license
package com.rs.mobile.wportal.activity.xsgr; import android.content.Context; import android.os.Handler; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.guanaj.easyswipemenulibrary.EasySwipeMenuLayout; import com.rs.mobile.common.AppConfig; import com.rs.mobile.common.C; import com.rs.mobile.common.D; import com.rs.mobile.common.L; import com.rs.mobile.common.S; import com.rs.mobile.common.activity.BaseActivity; import com.rs.mobile.common.network.OkHttpHelper; import com.rs.mobile.common.util.GsonUtils; import com.rs.mobile.wportal.Constant; import com.rs.mobile.wportal.R; import com.rs.mobile.wportal.adapter.OnItemClickLitener; import com.rs.mobile.wportal.adapter.xsgr.ViewPagerAdapter; import com.rs.mobile.wportal.biz.xsgr.QueryCategoryList; import com.rs.mobile.wportal.fragment.xsgr.MyCommodityFragment; import com.rs.mobile.wportal.fragment.xsgr.MyCommodityFragment2; import com.rs.mobile.wportal.view.DividerItemDecoration; import org.json.JSONObject; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import listpoplibrary.ListPopWindowManager; import okhttp3.Request; import static com.rs.mobile.wportal.takephoto.CommonUtil.dip2px; public class CommodityManagementActivity extends BaseActivity { private List<Fragment> list; ViewPagerAdapter viewPagerAdapter; MyCommodityFragment myCommodityFragment; MyCommodityFragment2 myCommodityFragment2; TabLayout tabLayout; ViewPager viewPager; View viewLine; View contentView; private TextView tvSelect; RecyclerView recyclerView; private LinearLayout select, closeBtn; private String[] titles; private PopupWindow popupWindow; private List<QueryCategoryList.DataBean> mData = new ArrayList<>(); MyPopupWinAdapter popAdapter; public static String catergoryId = "0"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commodity_management); initView(); initListener(); initData(); } private void initData() { list = new ArrayList<>(); myCommodityFragment = new MyCommodityFragment(); myCommodityFragment2 = new MyCommodityFragment2(); titles = new String[]{getResources().getString(R.string.selling), getResources().getString(R.string.selling_done)}; list.add(myCommodityFragment); list.add(myCommodityFragment2); viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), this, list, titles); viewPager.setAdapter(viewPagerAdapter); viewPager.setCurrentItem(0); tabLayout.setupWithViewPager(viewPager); reflex(tabLayout); } private void initView() { closeBtn = (LinearLayout) findViewById(R.id.close_btn); tabLayout = (TabLayout) findViewById(R.id.tab_layout); viewPager = (ViewPager) findViewById(R.id.view_pager); viewLine = findViewById(R.id.view_line); select = (LinearLayout) findViewById(R.id.layout_select); tvSelect = (TextView) findViewById(R.id.tv_select); initType(); } private void initType() { contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.commodity_type, null, false); recyclerView = (RecyclerView) contentView.findViewById(R.id.recycler_view); EditText all = (EditText) contentView.findViewById(R.id.commodity_name); all.setText(getResources().getString(R.string.type_all)); ImageView add = (ImageView) contentView.findViewById(R.id.commodity_img); LinearLayout linearLayout = (LinearLayout) contentView.findViewById(R.id.title); add.setImageResource(R.drawable.icon_add_category); linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tvSelect.setText(getResources().getString(R.string.type_all)); popupWindow.dismiss(); if (viewPager.getCurrentItem() == 0){ catergoryId = "0"; myCommodityFragment.requestStoreCateList(1,catergoryId); }else if (viewPager.getCurrentItem() == 1){ catergoryId = "0"; myCommodityFragment2.requestStoreCateList(1,catergoryId); } } }); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean canAdd = true; for (int i = 0; i < mData.size(); i++) { if (mData.get(i).isAdd() == true) { canAdd = false; } } if (canAdd) { QueryCategoryList.DataBean bean = new QueryCategoryList.DataBean(); bean.setCustom_code("01071390009abcde"); bean.setId(""); bean.setImage_url(""); bean.setLevel_name(""); bean.setPid("0"); bean.setRid("0"); bean.setRank("0"); bean.setAdd(true); popAdapter.addItem(bean, popAdapter.getItemCount()); // recyclerView.getAdapter().notifyDataSetChanged(); } else { } } }); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), LinearLayoutManager.HORIZONTAL, R.drawable.divide_bg)); popAdapter = new MyPopupWinAdapter(getApplicationContext(), R.layout.commodity_type_item, mData); // popAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { // @Override // public void onItemClick(BaseQuickAdapter adapter, View view, int position) { // // // } // }); recyclerView.setAdapter(popAdapter); } private void initListener() { closeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { catergoryId = "0"; requestCategoryList(catergoryId, false); } }); } private void requestCategoryList(String catergoryId, final boolean isShow) { HashMap<String, Object> params = new HashMap<>(); params.put("lang_type", AppConfig.LANG_TYPE); params.put("token", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_TOKEN, "")); params.put("custom_code", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_CUSTOM_CODE, "")); params.put("CategoryId", "-1"); OkHttpHelper okHttpHelper = new OkHttpHelper(this); okHttpHelper.addPostRequest(new OkHttpHelper.CallbackLogic() { @Override public void onBizSuccess(String responseDescription, JSONObject data, String flag) { QueryCategoryList entity = GsonUtils.changeGsonToBean(responseDescription, QueryCategoryList.class); Log.i("123123", "responseDescription=" + responseDescription); if ("1".equals(entity.getStatus())) { // if (list.size() <= 0) { // list = entity.getData(); // } if (mData.size() > 0) { mData.clear(); } if (!isShow) { showCategoryPop(); } if (entity.getData() != null && entity.getData().size() > 0){ mData.addAll(entity.getData()); recyclerView.getAdapter().notifyDataSetChanged(); } } else { Toast.makeText(CommodityManagementActivity.this, entity.getMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onBizFailure(String responseDescription, JSONObject data, String flag) { } @Override public void onNetworkError(Request request, IOException e) { } }, Constant.XSGR_TEST_URL + Constant.COMMODITY_QUERYCATEGORY, GsonUtils.createGsonString(params)); } private void showCategoryPop() { LinearLayout title = (LinearLayout) findViewById(R.id.my_title); // int titleHeight = title.getHeight(); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); title.measure(h, 0); //标题栏高度 int titleHeight = title.getMeasuredHeight(); //状态栏高度 int statusHeight = getStatusBarHeight(CommodityManagementActivity.this); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); //屏幕高度 int screenHeight = metrics.heightPixels; //popupwindow高度 int height = screenHeight - titleHeight - statusHeight; popupWindow = ListPopWindowManager.getInstance().showCommonPopWindow(contentView, viewLine, CommodityManagementActivity.this, false, height); } public static int getStatusBarHeight(Context context) { Class<?> c = null; Object obj = null; Field field = null; int x = 0, statusBarHeight = 0; try { c = Class.forName("com.android.internal.R$dimen"); obj = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(obj).toString()); statusBarHeight = context.getResources().getDimensionPixelSize(x); } catch (Exception e1) { e1.printStackTrace(); } return statusBarHeight; } public class MyPopupWinAdapter extends BaseQuickAdapter<QueryCategoryList.DataBean, BaseViewHolder> { private Context context; private List<QueryCategoryList.DataBean> mdatas; public MyPopupWinAdapter(Context context, @LayoutRes int layoutResId, @Nullable List<QueryCategoryList.DataBean> data) { super(layoutResId, data); this.context = context; } @Override protected void convert(final BaseViewHolder helper, final QueryCategoryList.DataBean item) { final EditText name; final ImageView img; final Button done; img = helper.getView(R.id.commodity_img); name = helper.getView(R.id.commodity_name); done = helper.getView(R.id.edit_done); name.setText(item.getLevel_name() + ""); helper.getView(R.id.content).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tvSelect.setText(mData.get(helper.getAdapterPosition()).getLevel_name()); popupWindow.dismiss(); if (viewPager.getCurrentItem() == 0){ catergoryId = mData.get(helper.getAdapterPosition()).getId(); myCommodityFragment.requestStoreCateList(1,catergoryId); }else if (viewPager.getCurrentItem() == 1){ catergoryId = mData.get(helper.getAdapterPosition()).getId(); myCommodityFragment2.requestStoreCateList(1,catergoryId); } } }); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { img.setVisibility(View.GONE); done.setVisibility(View.VISIBLE); name.setEnabled(true); name.setSelectAllOnFocus(true);//设置全选 new Handler().postDelayed(new Runnable() {//加上延时 public void run() { name.setFocusable(true); name.setFocusableInTouchMode(true); name.requestFocus();//请求获得焦点 //调用系统输入法 InputMethodManager inputManager = (InputMethodManager) name.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(name, 0); } }, 200); } }); done.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String edit = name.getText().toString().trim(); final String method; HashMap<String, Object> params = new HashMap<>(); if (item.isAdd()) { method = Constant.COMMODITY_CATEGORYADD; params.put("lang_type", AppConfig.LANG_TYPE); params.put("token", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_TOKEN, "")); params.put("custom_code", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_CUSTOM_CODE, "")); params.put("level_name", edit); params.put("image_url", ""); params.put("rank", 0); params.put("pid", 0); params.put("rid", 0); } else { method = Constant.COMMODITY_CATEGORYEDIT; params.put("lang_type", AppConfig.LANG_TYPE); params.put("token", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_TOKEN, "")); params.put("custom_code", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_CUSTOM_CODE, "")); params.put("level_name", edit); params.put("image_url", ""); params.put("rank", item.getRank()); params.put("id", item.getId()); } if (edit.length() != 0) { OkHttpHelper okHttpHelper = new OkHttpHelper(context); okHttpHelper.addPostRequest(new OkHttpHelper.CallbackLogic() { @Override public void onBizSuccess(String responseDescription, JSONObject data, String flag) { QueryCategoryList entity = GsonUtils.changeGsonToBean(responseDescription, QueryCategoryList.class); Log.i("123123", "responseDescription=" + responseDescription); if ("1".equals(entity.getStatus())) { done.setVisibility(View.GONE); img.setVisibility(View.VISIBLE); catergoryId = "0"; requestCategoryList(catergoryId, true); } else { Toast.makeText(CommodityManagementActivity.this, entity.getMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onBizFailure(String responseDescription, JSONObject data, String flag) { } @Override public void onNetworkError(Request request, IOException e) { } }, Constant.XSGR_TEST_URL + method, GsonUtils.createGsonString(params)); } else { Toast.makeText(context, getResources().getString(R.string.please_white), Toast.LENGTH_SHORT).show(); } } }); helper.getView(R.id.right).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { D.showDialog(CommodityManagementActivity.this, -1, getResources().getString(R.string.title_promote), getResources().getString(R.string.sure_delgoods), getResources().getString(R.string.button_sure), new View.OnClickListener() { @Override public void onClick(View arg0) { D.alertDialog.dismiss(); if (item.isAdd()) { mData.remove(helper.getAdapterPosition()); popAdapter.notifyItemRemoved(helper.getAdapterPosition()); } else { delProduct(item.getId(), helper.getAdapterPosition()); EasySwipeMenuLayout easySwipeMenuLayout = helper.getView(R.id.es); easySwipeMenuLayout.resetStatus(); } } }, getResources().getString(R.string.button_cancel), new View.OnClickListener() { @Override public void onClick(View v) { D.alertDialog.dismiss(); } }); } }); helper.getView(R.id.right_menu_2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { D.showDialog(CommodityManagementActivity.this, -1, getResources().getString(R.string.title_promote), getResources().getString(R.string.sure_delgoods), getResources().getString(R.string.button_sure), new View.OnClickListener() { @Override public void onClick(View arg0) { D.alertDialog.dismiss(); if (item.isAdd()) { mData.remove(helper.getAdapterPosition()); popAdapter.notifyItemRemoved(helper.getAdapterPosition()); } else { delProduct(item.getId(), helper.getAdapterPosition()); EasySwipeMenuLayout easySwipeMenuLayout = helper.getView(R.id.es); easySwipeMenuLayout.resetStatus(); } } }, getResources().getString(R.string.button_cancel), new View.OnClickListener() { @Override public void onClick(View v) { D.alertDialog.dismiss(); } }); } }); if (item.isAdd()) { new Handler().postDelayed(new Runnable() {//加上延时 public void run() { img.setVisibility(View.GONE); done.setVisibility(View.VISIBLE); name.setEnabled(true); name.setFocusable(true); name.setFocusableInTouchMode(true); name.requestFocus();//请求获得焦点 //调用系统输入法 InputMethodManager inputManager = (InputMethodManager) name.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(name, 0); } }, 100); } } public void addItem(QueryCategoryList.DataBean text, int position) { mData.add(position, text); notifyItemInserted(position); } } public void reflex(final TabLayout tabLayout) { //了解源码得知 线的宽度是根据 tabView的宽度来设置的 tabLayout.post(new Runnable() { @Override public void run() { try { //拿到tabLayout的mTabStrip属性 LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0); int dp10 = dip2px(tabLayout.getContext(), 10); for (int i = 0; i < mTabStrip.getChildCount(); i++) { View tabView = mTabStrip.getChildAt(i); //拿到tabView的mTextView属性 tab的字数不固定一定用反射取mTextView Field mTextViewField = tabView.getClass().getDeclaredField("mTextView"); mTextViewField.setAccessible(true); TextView mTextView = (TextView) mTextViewField.get(tabView); tabView.setPadding(0, 0, 0, 0); //因为我想要的效果是 字多宽线就多宽,所以测量mTextView的宽度 int width = 0; width = mTextView.getWidth(); if (width == 0) { mTextView.measure(0, 0); width = mTextView.getMeasuredWidth(); } //设置tab左右间距为10dp 注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的 LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams(); params.width = width; params.leftMargin = dp10; params.rightMargin = dp10; tabView.setLayoutParams(params); tabView.invalidate(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }); } private void delProduct(String id, final int position) { HashMap<String, Object> params = new HashMap<>(); params.put("lang_type", AppConfig.LANG_TYPE); params.put("token", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_TOKEN, "")); params.put("custom_code", S.getShare(CommodityManagementActivity.this, C.KEY_JSON_CUSTOM_CODE, "")); params.put("id", id); OkHttpHelper okHttpHelper = new OkHttpHelper(this); okHttpHelper.addPostRequest(new OkHttpHelper.CallbackLogic() { @Override public void onBizSuccess(String responseDescription, JSONObject data, String flag) { QueryCategoryList entity = GsonUtils.changeGsonToBean(responseDescription, QueryCategoryList.class); Log.i("123123", "responseDescription=" + responseDescription); if ("1".equals(entity.getStatus())) { Toast.makeText(CommodityManagementActivity.this, entity.getMessage(), Toast.LENGTH_SHORT).show(); mData.remove(position); popAdapter.notifyItemRemoved(position); } else { Toast.makeText(CommodityManagementActivity.this, entity.getMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onBizFailure(String responseDescription, JSONObject data, String flag) { Log.e("responseDescription", responseDescription); // Log.e("JSONObject",data.toString()); Log.e("flag145", flag); } @Override public void onNetworkError(Request request, IOException e) { } }, Constant.XSGR_TEST_URL + Constant.COMMODITY_CATEGORYDEL, GsonUtils.createGsonString(params)); } public Fragment getVisibleFragment(){ FragmentManager fragmentManager = CommodityManagementActivity.this.getSupportFragmentManager(); List<Fragment> fragments = fragmentManager.getFragments(); for(Fragment fragment : fragments){ if(fragment != null && fragment.isVisible()) return fragment; } return null; } }
true
0bfa2626fc8c92d268c3fe63ce7847599105b862
Java
Strabox/vehicle-manager
/src/main/java/com/pt/pires/services/local/ILicenseService.java
UTF-8
181
1.804688
2
[ "Apache-2.0" ]
permissive
package com.pt.pires.services.local; /** * Services related to Licenses * @author André * */ public interface ILicenseService { boolean validateLicense(String license); }
true
218ebb9fe3cea1cb012bc9d012bf0d0214585a76
Java
somyungsub/kosta-refactoring
/src/code/refactoring/classmove_1/AccountTest.java
UTF-8
366
2.203125
2
[]
no_license
package code.refactoring.classmove_1; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class AccountTest { @Before public void setUp() throws Exception { } @Test public void testoverdraftCharge() { Account account = new Account(10); // testcode assertTrue(account.overdraftCharge() == 12.55); } }
true
31d022fbcbbd446d56a976f5ad6a86dc5ba80c4b
Java
JPCGameiro/UA-ECT
/1ºAno/P1/aula06/MediaDesvio/mediadesvio.java
UTF-8
690
3.65625
4
[]
no_license
import java.util.Scanner; import java.lang.Math; public class mediadesvio { public static void main(String[] args) { Scanner ler = new Scanner(System.in); System.out.print("Insira quantos números quer inserir: "); int N = ler.nextInt(); int[] array = new int[N]; int media = 0; double desvio = 0; for(int z=0;z<N;z++){ System.out.print("Insira um número: "); array[z] = ler.nextInt(); } for(int i=0;i<N;i++) media +=array[i]; media = media/N; for(int j=0;j<N;j++) desvio += Math.pow((array[j] - media), 2); desvio = Math.sqrt(desvio/N); System.out.println("Média: "+media); System.out.println("Desvio: "+desvio); } }
true
4d3ff74ef99cc1d9b50de8af932a2c891c05dc60
Java
CrazyWinner/WonderCloud
/app/src/main/java/com/cvsoftware/chatcloud/HowToActivity.java
UTF-8
1,982
1.976563
2
[]
no_license
package com.cvsoftware.chatcloud; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.widget.ImageButton; import com.cvsoftware.chatcloud.utils.AppIntroActivity; public class HowToActivity extends AppIntroActivity { boolean launch = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addSlide(new Slide(R.string.step1,R.string.step1desc,R.drawable.adim0, Color.parseColor("#00695C"))); addSlide(new Slide(R.string.step2,R.string.step2desc,R.drawable.adim1, Color.parseColor("#2E7D32"))); addSlide(new Slide(R.string.step3,R.string.step3desc,R.drawable.adim2, Color.parseColor("#0277BD"))); addSlide(new Slide(R.string.step4,R.string.step4desc,R.drawable.adim3, Color.parseColor("#E64A19"))); addSlide(new Slide(R.string.step5,R.string.step5desc,R.drawable.adim4,Color.parseColor("#512DA8"))); addSlide(new Slide(R.string.step6,R.string.step6desc,R.drawable.adim5,Color.parseColor("#512DA8"))); launch = getIntent().getBooleanExtra("launch",false); SharedPreferences sharedPreferences = getSharedPreferences("ChatCloudSharedPref", MODE_PRIVATE); sharedPreferences.edit().putBoolean("firstTime",false).apply(); } @Override public void onNextPage(){ if(currentPage == adapter.getCount()-1){ if(launch){ Intent i = new Intent(HowToActivity.this, MainActivity.class); startActivity(i); } finish(); } } @Override public void onPageChange(int page, int maxPage, ImageButton nextButton){ if(page == maxPage){ nextButton.setImageResource(R.drawable.ic_done_black_24dp); }else{ nextButton.setImageResource(R.drawable.ic_navigate_next_black_24dp); } } }
true
3862a95f5824529290f0797eeae5368f08930611
Java
moutainhigh/xcdv2
/bms-ledger-inventory/src/main/java/com/bms/linv/bean/param/LINV0111IParam.java
UTF-8
3,235
1.765625
2
[]
no_license
package com.bms.linv.bean.param; import com.framework.base.rest.param.BaseRestPaginationParam; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Created by zhang_jian4 on 2017/4/18. */ @ApiModel(value = "LINV0111IParam", description = "产品批次库存查询") public class LINV0111IParam extends BaseRestPaginationParam{ @ApiModelProperty(value = "物流区域ID") private String[] logisticsId; @ApiModelProperty(value = "销售平台") private String[] salePlatform; @ApiModelProperty(value = "货主ID") private String[] ownerId; @ApiModelProperty(value = "货主类型") private String[] ownerType; @ApiModelProperty(value = "生产商ID") private String[] producerId; @ApiModelProperty(value = "商品ID") private String[] commodityId; @ApiModelProperty(value = "产品ID") private String[] productId; @ApiModelProperty(value = "SKU编码") private String[] skuCode; @ApiModelProperty(value = "入库批次") private String[] lotNo; @ApiModelProperty(value = "销售状态ID") private String[] saleStatusId; @ApiModelProperty(value = "单位") private String[] uom; @ApiModelProperty(value = "库存类型") private String[] ivType; public String[] getLogisticsId() { return logisticsId; } public void setLogisticsId(String[] logisticsId) { this.logisticsId = logisticsId; } public String[] getSalePlatform() { return salePlatform; } public void setSalePlatform(String[] salePlatform) { this.salePlatform = salePlatform; } public String[] getOwnerId() { return ownerId; } public void setOwnerId(String[] ownerId) { this.ownerId = ownerId; } public String[] getOwnerType() { return ownerType; } public void setOwnerType(String[] ownerType) { this.ownerType = ownerType; } public String[] getProducerId() { return producerId; } public void setProducerId(String[] producerId) { this.producerId = producerId; } public String[] getCommodityId() { return commodityId; } public void setCommodityId(String[] commodityId) { this.commodityId = commodityId; } public String[] getProductId() { return productId; } public void setProductId(String[] productId) { this.productId = productId; } public String[] getSkuCode() { return skuCode; } public void setSkuCode(String[] skuCode) { this.skuCode = skuCode; } public String[] getLotNo() { return lotNo; } public void setLotNo(String[] lotNo) { this.lotNo = lotNo; } public String[] getSaleStatusId() { return saleStatusId; } public void setSaleStatusId(String[] saleStatusId) { this.saleStatusId = saleStatusId; } public String[] getUom() { return uom; } public void setUom(String[] uom) { this.uom = uom; } public String[] getIvType() { return ivType; } public void setIvType(String[] ivType) { this.ivType = ivType; } }
true
47441b89cc54e1376466973376c9c6da869c607b
Java
gdzzp1989/ybb
/src/main/java/ybb/algorithm/Conversion.java
UTF-8
367
2.890625
3
[]
no_license
package ybb.algorithm; import java.util.Stack; //10进制转8进制 public class Conversion { public static void main(String[] args) { Stack s = new Stack(); int num1= 1348; while(num1>0){ s.push(num1%8); num1=num1/8; } while(!s.empty()){ System.out.println(s.pop()); } } }
true
f9d442433ad97adea73eb08b00ac0e63507f8c1c
Java
tchenOpu/UsagiNo4G
/app/src/main/java/net/alwaysdata/woyanoro/usagino4g/MainActivity.java
UTF-8
6,416
2.140625
2
[]
no_license
package net.alwaysdata.woyanoro.usagino4g; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.SmsManager; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.content.Intent; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private AutoCompleteTextView editURL = null; private Button browse = null; private Button parametres = null; public static CheckBox simplifyBox = null; public static CheckBox zeroBox = null; public static EditText num_tel = null; public static Intent i=null; public static boolean themechange = false; public static int mode = 1; // 0 = nothing; 1 = client; 2 = server ; 3 = both? //theme blanc/noir public static int theme = 1; // 0 = noir ; 1 = blanc // // Notre liste de mots que connaîtra l'AutoCompleteTextView private static final String[] URLs = new String[]{ "http://www.google.com", "http://mail.google.com", "http://www.pso-world.com/forums/", "http://puyonexus.com/forum/", "www.google.com", "mail.google.com", "www.pso-world.com/forums/", "puyonexus.com/forum/", "woyanoro.alwaysdata.net" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (MainActivity.theme == 0) { setContentView(R.layout.activity_main_black); } else if (MainActivity.theme == 1) { setContentView(R.layout.activity_main); } browse = (Button) findViewById(R.id.button_browse); parametres = (Button) findViewById(R.id.button_parametres); simplifyBox = (CheckBox) findViewById(R.id.simplifybox); zeroBox = (CheckBox) findViewById(R.id.zerobox); num_tel = (EditText) findViewById(R.id.editPhone); //pref num tel autoset SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); num_tel.setText(prefs.getString("TelNumber", "")); // } @Override protected void onResume(){ super.onResume(); browse = (Button) findViewById(R.id.button_browse); parametres = (Button) findViewById(R.id.button_parametres); i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName()); // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if(!prefs.getBoolean("CodeSimplify",true)){ simplifyBox.setChecked(false); } simplifyBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (simplifyBox.isChecked()){ zeroBox.setChecked(false); } } }); zeroBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (zeroBox.isChecked()){ simplifyBox.setChecked(false); } } }); browse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mode==1){ TextView numerotel = (TextView) findViewById(R.id.editPhone); String numtel = numerotel.getText().toString(); if (numtel.length()==10){ System.out.print("OK"); TextView adresse = (TextView) findViewById(R.id.editURL); String lien = adresse.getText().toString(); if (simplifyBox.isChecked()){ lien = "#"+lien; } else if (zeroBox.isChecked()){ lien = "0"+lien; } else { lien = "-"+lien; } SmsManager manager = SmsManager.getDefault(); manager .sendTextMessage(numtel, null, lien, null, null); manager .sendTextMessage(numtel, null, "end", null, null); Toast.makeText(MainActivity.this, "Requête envoyée à "+numtel, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Le numero "+numtel+" n'a pas 10 chiffres.", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Le mode n'est pas réglé sur client.", Toast.LENGTH_SHORT).show(); } } }); parametres.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ActiviteParametres = new Intent(MainActivity.this, Parametres.class); startActivity(ActiviteParametres); } }); // On récupère l'AutoCompleteTextView déclaré dans notre layout editURL = (AutoCompleteTextView) findViewById(R.id.editURL); editURL.setThreshold(0); // On associe un adaptateur à notre liste… ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, URLs); // … puis on indique que notre AutoCompleteTextView utilise cet adaptateur editURL.setAdapter(adapter); } @Override protected void onRestart(){ super.onRestart(); if (themechange ==true) { themechange = false; if (MainActivity.theme == 0) { setContentView(R.layout.activity_main_black); } else if (MainActivity.theme == 1) { setContentView(R.layout.activity_main); } } } }
true
1272270e2a0b779f56729e4723cf7c66bcfd97cf
Java
khushhallchandra/CS-7641
/Assignment4/BURLAP/src/burlap/oomdp/singleagent/environment/SimulatedEnvironment.java
UTF-8
7,338
2.875
3
[ "MIT" ]
permissive
package burlap.oomdp.singleagent.environment; import burlap.oomdp.auxiliary.StateGenerator; import burlap.oomdp.auxiliary.common.ConstantStateGenerator; import burlap.oomdp.core.Domain; import burlap.oomdp.core.states.State; import burlap.oomdp.core.TerminalFunction; import burlap.oomdp.singleagent.GroundedAction; import burlap.oomdp.singleagent.RewardFunction; /** * An {@link burlap.oomdp.singleagent.environment.Environment} that simulates interactions using the {@link burlap.oomdp.singleagent.Action#performAction(burlap.oomdp.core.states.State, burlap.oomdp.singleagent.GroundedAction)} * method of the the {@link burlap.oomdp.core.Domain} provided to this Environment. The rewards and terminal states are similarly tracked using a * provided {@link burlap.oomdp.singleagent.RewardFunction} and {@link burlap.oomdp.core.TerminalFunction}. Initial states of the environment * are defined using a {@link burlap.oomdp.auxiliary.StateGenerator}. If no {@link burlap.oomdp.auxiliary.StateGenerator} is specified, * but an initial {@link burlap.oomdp.core.states.State} is provided in a constructor, then the {@link burlap.oomdp.auxiliary.StateGenerator} is * set to a {@link burlap.oomdp.auxiliary.common.ConstantStateGenerator} so that upon {@link #resetEnvironment()} method calls, * the initial state is the same as the original input state. * <br/><br/> * All returned environment observations are fully observable returning a copy of the true internal {@link burlap.oomdp.core.states.State} of * the environment. Copies of the state are returned to prevent tampering of the internal environment state. * <br/><br/> * By default, this {@link burlap.oomdp.singleagent.environment.Environment} will not allow states to change when the current * environment state is a terminal state (as specified by the input {@link burlap.oomdp.core.TerminalFunction}); instead, the * same current state will be returned with a reward of zero if someone attempts to interact with the environment through {@link #executeAction(burlap.oomdp.singleagent.GroundedAction)}. * In this case, the environment state will have to be manually changed with {@link #resetEnvironment()} or {@link #setCurStateTo(burlap.oomdp.core.states.State)} * to a non-terminal state before actions will affect the state again. Alternatively, you can allow actions to affect the state from * terminal states with the {@link #setAllowActionFromTerminalStates(boolean)} method. * @author James MacGlashan. */ public class SimulatedEnvironment implements StateSettableEnvironment, TaskSettableEnvironment{ /** * The domain of this environment */ protected Domain domain; /** * The reward function of this environment */ protected RewardFunction rf; /** * The terminal function for this environment */ protected TerminalFunction tf; /** * The state generator used to generate new states when the environment is reset with {@link #resetEnvironment()}; */ protected StateGenerator stateGenerator; /** * The current state of the environment */ protected State curState; /** * The last reward generated from this environment. */ protected double lastReward = 0.; /** * A flag indicating whether the environment will respond to actions from a terminal state. If false, * then once a the environment transitions to a terminal state, any action attempted by the {@link #executeAction(burlap.oomdp.singleagent.GroundedAction)} * method will result in no change in state and to enable action again, the Environment state will have to be * manually changed with the {@link #resetEnvironment()} method or the {@link #setCurStateTo(burlap.oomdp.core.states.State)} method. * If this value is true, then actions will be carried out according to the domain's transition dynamics. */ protected boolean allowActionFromTerminalStates = false; public SimulatedEnvironment(Domain domain, RewardFunction rf, TerminalFunction tf){ this.domain = domain; this.rf = rf; this.tf = tf; } public SimulatedEnvironment(Domain domain, RewardFunction rf, TerminalFunction tf, State initialState) { this.domain = domain; this.rf = rf; this.tf = tf; this.stateGenerator = new ConstantStateGenerator(initialState); this.curState = initialState; } public SimulatedEnvironment(Domain domain, RewardFunction rf, TerminalFunction tf, StateGenerator stateGenerator) { this.domain = domain; this.rf = rf; this.tf = tf; this.stateGenerator = stateGenerator; this.curState = stateGenerator.generateState(); } public Domain getDomain() { return domain; } public void setDomain(Domain domain) { this.domain = domain; } public RewardFunction getRf() { return rf; } public void setRf(RewardFunction rf) { this.rf = rf; } public TerminalFunction getTf() { return tf; } public void setTf(TerminalFunction tf) { this.tf = tf; } public StateGenerator getStateGenerator() { return stateGenerator; } public void setStateGenerator(StateGenerator stateGenerator) { this.stateGenerator = stateGenerator; } /** * Sets whether the environment will respond to actions from a terminal state. If false, * then once a the environment transitions to a terminal state, any action attempted by the {@link #executeAction(burlap.oomdp.singleagent.GroundedAction)} * method will result in no change in state and to enable action again, the Environment state will have to be * manually changed with the {@link #resetEnvironment()} method or the {@link #setCurStateTo(burlap.oomdp.core.states.State)} method. * If this value is true, then actions will be carried out according to the domain's transition dynamics. * @param allowActionFromTerminalStates if false, then actions are not allowed from terminal states; if true, then they are allowed. */ public void setAllowActionFromTerminalStates(boolean allowActionFromTerminalStates){ this.allowActionFromTerminalStates = true; } @Override public void setCurStateTo(State s) { if(this.stateGenerator == null){ this.stateGenerator = new ConstantStateGenerator(s); } this.curState = s; } @Override public State getCurrentObservation() { return this.curState.copy(); } @Override public EnvironmentOutcome executeAction(GroundedAction ga) { GroundedAction simGA = (GroundedAction)ga.copy(); simGA.action = this.domain.getAction(ga.actionName()); if(simGA.action == null){ throw new RuntimeException("Cannot execute action " + ga.toString() + " in this SimulatedEnvironment because the action is to known in this Environment's domain"); } State nextState; if(this.allowActionFromTerminalStates || !this.isInTerminalState()) { nextState = simGA.executeIn(this.curState); this.lastReward = this.rf.reward(this.curState, simGA, nextState); } else{ nextState = this.curState; this.lastReward = 0.; } EnvironmentOutcome eo = new EnvironmentOutcome(this.curState.copy(), simGA, nextState.copy(), this.lastReward, this.tf.isTerminal(nextState)); this.curState = nextState; return eo; } @Override public double getLastReward() { return this.lastReward; } @Override public boolean isInTerminalState() { return this.tf.isTerminal(this.curState); } @Override public void resetEnvironment() { this.lastReward = 0.; this.curState = stateGenerator.generateState(); } }
true
c3f9a4a81b16519809aee05a0741b1a5d85d4df6
Java
sayederfanarefin/springboot-backend-erp
/src/main/java/com/sweetitech/sweeterp/model/user/EmployeeDetails.java
UTF-8
3,452
2.21875
2
[]
no_license
package com.sweetitech.sweeterp.model.user; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; 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.PrePersist; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonFormat; @Entity @Table(name = "employee_details") public class EmployeeDetails implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @Column(unique = true, nullable = false) @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; private String designation; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id", nullable = false) private User user; @Column(columnDefinition="LONGTEXT") private String address; private String phone; private String emergenyContact; private String phone2; private String gender; private Date dateOfBirth; private Date joiningDate; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "fk_slaray") private Salary slaray; @Column(name = "created_at") public Date createdAt; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Date getJoiningDate() { return joiningDate; } public void setJoiningDate(Date joiningDate) { this.joiningDate = joiningDate; } public Salary getSlaray() { return slaray; } public void setSlaray(Salary slaray) { this.slaray = slaray; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @PrePersist void createdAt() { this.createdAt = new Date(); } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.000 ", timezone = "UTC") public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public EmployeeDetails() { super(); // TODO Auto-generated constructor stub } public String getEmergenyContact() { return emergenyContact; } public void setEmergenyContact(String emergenyContact) { this.emergenyContact = emergenyContact; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
true
6021f63c4680084f797b995373d71f0539762494
Java
betterGa/OJ-Record
/src/main/java/NowCoder/Rabbit.java
UTF-8
380
2.609375
3
[]
no_license
package NowCoder; public class Rabbit { public static int getTotalCount(int monthCount) { int[] rabbit=new int[monthCount]; rabbit[0]=1; rabbit[1]=0; for(int i=2;i<monthCount;i++) {rabbit[i]=rabbit[i-1]+rabbit[i-2];} int count=0; for(int j=0;j<monthCount;j++) { count=count+rabbit[j]; } return count; } }
true
6c368e9def9d6d1a20c920dc535c9146c8cc6f54
Java
henuliulei/ssm_bookSystem
/src/main/java/com/bupt/controller/LoginController.java
UTF-8
7,362
2.1875
2
[]
no_license
package com.bupt.controller; import com.bupt.pojo.Book; import com.bupt.pojo.Pagination; import com.bupt.pojo.User; import com.bupt.service.LoginService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; @Controller //@ResponseBody public class LoginController { @Resource(name = "LoginServiceImpl") private LoginService loginService; @CrossOrigin @ResponseBody @PostMapping("/login/{username}/{password}") public String judgeLogin1(@PathVariable("username") String username, @PathVariable("password") String password) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); int i = loginService.loginNum(username, password); String str = String.valueOf(i); String s = objectMapper.writeValueAsString(str); return s; } @CrossOrigin @ResponseBody @PostMapping("/register/{username}/{password}/{password1}/{email}/{mobile}") public String register(@PathVariable("username") String username, @PathVariable("password") String password, @PathVariable("password1") String password1, @PathVariable("email") String email, @PathVariable("mobile") String mobile) throws JsonProcessingException { String msg = ""; if (!password.equals(password1)) { msg = "注册失败,密码不一致"; return msg; } int num = loginService.UserNum(username); if (num > 0) { msg = "注册失败,已有该用户"; return msg; } if (num == 0 && password.equals(password1)) { int i = loginService.addUser(username, password, email, mobile); System.out.println(i); if (i > 0) { msg = "注册成功"; return msg; } } return "注册失败"; } @CrossOrigin @ResponseBody @GetMapping("/users/{query}/{pagenum}/{pagesize}") public String getUserList(@PathVariable("query") String query, @PathVariable("pagenum") int pagenum, @PathVariable("pagesize") int pagesize) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); Pagination pagination = new Pagination(); ArrayList<User> users = new ArrayList<>(); System.out.println(query + pagenum + pagesize); String like = ""; like = "%" + query + "%"; int start = (pagenum - 1) * pagesize; int offset = pagesize; pagination.setLike(like); pagination.setStart(start); pagination.setOffest(offset); System.out.println(pagination); users = (ArrayList<User>) this.loginService.getUserList(pagination); String s = objectMapper.writeValueAsString(users); System.out.println(users); return s; } @CrossOrigin @ResponseBody @GetMapping("/usersall/{pagenum}/{pagesize}") public String getUserListAll(@PathVariable("pagenum") int pagenum, @PathVariable("pagesize") int pagesize) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); ArrayList<User> users = new ArrayList<>(); int start = (pagenum - 1) * pagesize; int offset = pagesize; System.out.println(start + " " + offset); users = (ArrayList<User>) this.loginService.getUserListAll(start, offset); System.out.println("查询成功"); System.out.println(users); String s = objectMapper.writeValueAsString(users); return s; } @CrossOrigin @ResponseBody @GetMapping("/userstotal/{query}") public int getUserListNum(@PathVariable("query") String query) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); int total; Pagination pagination = new Pagination(); ; String like = ""; if (query != " ") { like = "%" + query + "%"; } else { like = ""; } pagination.setLike(like); System.out.println(pagination); if (like.equals("")) { } else { total = this.loginService.getUserListNum(pagination); System.out.println(total); return total; } return -1; } @CrossOrigin @ResponseBody @GetMapping("/usersalltotal") public int getUserListAllNum() throws JsonProcessingException { int total; total = this.loginService.getUserListAllNum(); System.out.println(total); return total; } @CrossOrigin @ResponseBody @GetMapping("/getuserbyname/{username}") public User getUserByName(@PathVariable("username") String username) { User userByName = this.loginService.getInfoByName(username); System.out.println(userByName); return userByName; } @CrossOrigin @ResponseBody @PutMapping("/updateuserbyname/{username}/{password}/{email}/{mobile}") public int updateUserByName(@PathVariable("username") String username, @PathVariable("password") String password, @PathVariable("email") String email, @PathVariable("mobile") String mobile) { User user = new User(); user.setUsername(username); user.setPassword(password); user.setEmail(email); user.setMobile(mobile); int i = this.loginService.updateUserByName(user); return i; } @CrossOrigin @ResponseBody @DeleteMapping("/deleteuserbyname/{username}/{pagenum}/{pagesize}") public String deleteUserByName(@PathVariable("username") String name, @PathVariable("pagenum") int pagenum, @PathVariable("pagesize") int pagesize) throws JsonProcessingException { System.out.println(name); int i = this.loginService.deleteUserByName(name); ObjectMapper objectMapper = new ObjectMapper(); ArrayList<User> users = new ArrayList<>(); int start = (pagenum - 1) * pagesize; int offset = pagesize; if (i == 1) { users = (ArrayList<User>) this.loginService.getUserListAll(start, offset); } String s = objectMapper.writeValueAsString(users); return s; } @CrossOrigin @ResponseBody @PutMapping("/updateuserbyname/{username}/{role}") public int updateRoleByName(@PathVariable("username") String username, @PathVariable("role") String role) { int i = this.loginService.updateRoleByName(username, role); return i; } @CrossOrigin @ResponseBody @GetMapping("/getAllBook/{pagenum}/{pagesize}") public List<Book> getAllBook(@PathVariable("pagenum") int pagenum, @PathVariable("pagesize") int pagesize) { ArrayList<Book> books; int start = (pagenum - 1) * pagesize; int offset = pagesize; books = (ArrayList<Book>) this.loginService.getAllBook(start, offset); return books; } @CrossOrigin @ResponseBody @GetMapping("/getBookNum") public int getBookListAllNum() throws JsonProcessingException { int total; total = this.loginService.getBookListAllNum(); return total; } }
true
ab9ce754e084cec34f32bb1097c49074c4de1c50
Java
hakeris1010/ODMRP_Sim
/src/NetworkSim/Logger.java
UTF-8
739
2.75
3
[]
no_license
package NetworkSim; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; /** * Created by haker on 2017-05-25. */ public class Logger { private static final String logFile = "odmrp.log"; private static PrintStream stream = System.out; private static final boolean loggerOn = true; static{ try { stream = new PrintStream(new FileOutputStream(logFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static <T> void logf(T type){ if(loggerOn) stream.print(type); } public static <T> void logfn(T type){ if(loggerOn) stream.println(type); } }
true
a1b41d2e4c038ae2c060e0a54053d16b2668a205
Java
MaCeballosRo/ALUMINATI
/app/src/main/java/mx/edu/ittepic/marcos/tpdm_u4_examen_aluminati/MainActivity.java
UTF-8
451
1.882813
2
[]
no_license
package mx.edu.ittepic.marcos.tpdm_u4_examen_aluminati; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Lienzo lienzo = new Lienzo(this); lienzo.setNivel(getIntent().getExtras().getInt("nivel")); setContentView(lienzo); } }
true
f5f3841fc40c68764779e9dec7f2ee2eaf3ca9e5
Java
wuchao226/ArcMenu
/animTest/src/main/java/com/wuc/imooc/VerticalMenuActivity.java
UTF-8
2,373
2.484375
2
[]
no_license
package com.wuc.imooc; import android.animation.ObjectAnimator; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatImageView; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class VerticalMenuActivity extends AppCompatActivity implements View.OnClickListener { private int[] res = new int[]{R.id.image_a, R.id.image_b, R.id.image_c, R.id.image_d, R.id.image_e, R.id.image_f, R.id.image_g, R.id.image_h}; private List<AppCompatImageView> mImageViews = new ArrayList<>(); private boolean flag = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vertical_menu); for (int i = 0; i < res.length; i++) { AppCompatImageView imageView = findViewById(res[i]); imageView.setOnClickListener(this); mImageViews.add(imageView); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.image_a: if (flag) { startAnim(); } else { stopAnim(); } break; default: Toast.makeText(this, "click" + view.getId(), Toast.LENGTH_LONG).show(); break; } } private void startAnim() { for (int i = 1; i < res.length; i++) { ObjectAnimator animator = ObjectAnimator.ofFloat(mImageViews.get(i), "translationY", 0L, i * 120); animator.setInterpolator(new LinearInterpolator()); animator.setStartDelay(i * 300); animator.setDuration(500); animator.start(); } flag = false; } private void stopAnim() { for (int i = 1; i < res.length; i++) { ObjectAnimator animator = ObjectAnimator.ofFloat(mImageViews.get(i), "translationY", i * 150, 0L); animator.setInterpolator(new LinearInterpolator()); animator.setStartDelay(i * 300); animator.setDuration(500); animator.start(); } flag = true; } }
true
4503a276630ae13d7b7eb6e5b78ac60755c2664d
Java
amalsajeev14/Final-Assignment
/src/Bestbuy/GiantSignup.java
UTF-8
4,191
2.28125
2
[]
no_license
package Bestbuy; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class GiantSignup { WebDriver driver; JavascriptExecutor jse; public void start() { try { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Amal Sajeev\\Downloads\\mtt\\chromedriver.exe"); driver=new ChromeDriver(); driver.manage().deleteAllCookies(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); driver.get("https://www.giant-bicycles.com/ca/account/create"); signup(); } catch (Exception e) { e.printStackTrace(); } } public void signup() { try { driver.get("https://www.giant-bicycles.com/ca/account/create"); driver.findElement(By.cssSelector(".btn-default")).click(); driver.findElement(By.id("Gender")).click(); { WebElement dropdown = driver.findElement(By.id("Gender")); dropdown.findElement(By.xpath("//option[. = 'Mr.']")).click(); } driver.findElement(By.cssSelector("#Gender > option:nth-child(2)")).click(); Thread.sleep(2000); driver.findElement(By.id("Order_OrderFirstname")).sendKeys("Amal"); driver.findElement(By.id("Order_OrderLastname")).sendKeys("Sajeev"); driver.findElement(By.id("Order_OrderStreet")).click(); Thread.sleep(2000); driver.findElement(By.id("Order_OrderStreet")).sendKeys("45254"); driver.findElement(By.id("Order_OrderAddress2")).sendKeys("21"); driver.findElement(By.id("Order_OrderPostalcode")).sendKeys("jvhsdjhs"); driver.findElement(By.id("Order_OrderCity")).click(); Thread.sleep(2000); driver.findElement(By.id("Order_OrderCity")).sendKeys("montreal"); { WebElement element = driver.findElement(By.id("Order_OrderState")); Actions builder = new Actions(driver); builder.moveToElement(element).clickAndHold().perform(); } { WebElement element = driver.findElement(By.id("Order_OrderState")); Actions builder = new Actions(driver); builder.moveToElement(element).perform(); } { WebElement element = driver.findElement(By.id("Order_OrderState")); Actions builder = new Actions(driver); builder.moveToElement(element).release().perform(); } driver.findElement(By.id("Order_OrderState")).click(); { WebElement dropdown = driver.findElement(By.id("Order_OrderState")); dropdown.findElement(By.xpath("//option[. = 'Quebec']")).click(); } driver.findElement(By.cssSelector("option:nth-child(12)")).click(); driver.findElement(By.id("Order_OrderPhone")).click(); Thread.sleep(2000); driver.findElement(By.id("Order_OrderPhone")).sendKeys("1234456789"); driver.findElement(By.id("Email")).click(); Thread.sleep(2000); driver.findElement(By.id("Email")).sendKeys("amal@gmail.com"); driver.findElement(By.cssSelector(".input-label")).click(); Thread.sleep(2000); driver.findElement(By.cssSelector(".year:nth-child(7)")).click(); Thread.sleep(2000); driver.findElement(By.cssSelector(".month:nth-child(6)")).click(); Thread.sleep(2000); driver.findElement(By.cssSelector("tr:nth-child(4) > .day:nth-child(4)")).click(); driver.findElement(By.id("Order_Password")).click(); Thread.sleep(2000); driver.findElement(By.id("Order_Password")).sendKeys("password"); driver.findElement(By.id("Order_PasswordConfirmed")).click(); Thread.sleep(2000); driver.findElement(By.id("Order_PasswordConfirmed")).sendKeys("password"); driver.findElement(By.cssSelector(".checkbox > label")).click(); Thread.sleep(2000); driver.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { GiantSignup gt=new GiantSignup(); gt.start(); } }
true
c4c7a6108a316862759fb5903d4215c71255475f
Java
MisterMaurya/SignletonClassInJava
/SingletonClass/src/beans/Singleton.java
UTF-8
496
3.0625
3
[]
no_license
package beans; public class Singleton { static Singleton singleton = null; private Singleton() { } public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); return singleton; } return singleton; } public static void main(String[] args) { Singleton singleton = getInstance(); Singleton singleton2 = getInstance(); System.out.println(singleton.hashCode()); System.out.println(singleton2.hashCode()); } }
true
1e5fd8ef487a13eef58eec655867aa5ef85a4f6c
Java
FH-Thomas-Herzog/Java
/Semester 4/20150516_lab_5/swe4-lab5/src/main/java/at/fh/ooe/swe4/lab5/collections/SortedMultiSet.java
UTF-8
290
2.671875
3
[]
no_license
package at.fh.ooe.swe4.lab5.collections; /** * * @author Thomas Herzog <thomas.herzog@students.fh-hagenberg.at> * @date May 16, 2015 * @param <T> */ public interface SortedMultiSet<T extends Comparable<T>> extends Iterable<T> { void add(T el); boolean contains(T el); T get(T el); int size(); }
true
98b723daa3a9baec5cc2a8c23c8bfc15b37660a8
Java
vernaaquino/Magic8Ball
/app/src/main/java/com/example/magic8ball/MainActivity.java
UTF-8
3,571
2.171875
2
[]
no_license
package com.example.magic8ball; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Vibrator; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Vibrator myVib; private SensorManager sensorManager; public SensorEventListener listener; Sensor gyroscopeReading; void makePrediction(TextView prediction){ String[] predictions = {"It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"}; //Randomly pick a prediction int randomNum = (int) (20.0 * Math.random()); prediction.setText(predictions[randomNum]); //Fade-in animation Animation animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in); prediction.startAnimation(animFadeIn); //Haptic feedback myVib.vibrate(50); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView prediction = (TextView) findViewById(R.id.pred); final Button predButton = (Button) findViewById(R.id.button); predButton.setBackgroundColor(Color.TRANSPARENT); myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE); // Touch Feedback predButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { makePrediction(prediction); } }); // Orientation Feedback sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); gyroscopeReading = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); listener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent sensorEvent) { Log.d("Debug", sensorEvent.values[0] + ""); if(sensorEvent.values[0] < -5){ makePrediction(prediction); } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }; sensorManager.registerListener(listener, gyroscopeReading, SensorManager.SENSOR_DELAY_UI); } @Override protected void onStop() { super.onStop(); sensorManager.unregisterListener(listener); } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(listener, gyroscopeReading, SensorManager.SENSOR_DELAY_FASTEST); } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(listener); } }
true
2431593b9ab1fd6ec3987ae7bc1addd1665077c3
Java
litaobowl/DBPool
/src/main/java/snaq/db/DBPoolDataSource.java
UTF-8
26,163
1.953125
2
[ "MIT", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
/* --------------------------------------------------------------------------- DBPool : Java Database Connection Pooling <http://www.snaq.net/> Copyright (c) 2001-2013 Giles Winstanley. All Rights Reserved. This is file is part of the DBPool project, which is licensed under the BSD-style licence terms shown below. --------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. 4. Redistributions of modified versions of the source code, must be accompanied by documentation detailing which parts of the code are not part of the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package snaq.db; import java.io.PrintWriter; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Objects; import java.util.Properties; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import snaq.util.ObjectPool; /** * A {@link DataSource} implementation which produces {@link Connection} * instances. This implementation internally references a {@link ConnectionPool} * which it uses to provide transparent connection pooling to the client. * * @author Giles Winstanley */ public class DBPoolDataSource implements DataSource, ConnectionPoolListener { /** Name prefix to use for {@code ConnectionPool} instance (JNDI name is appended). */ protected static final String POOL_NAME_PREFIX = "DBPoolDataSource-"; /** SLF4J shared instance for writing log entries. */ protected static final Logger logger = LoggerFactory.getLogger(DBPoolDataSource.class); /** {@code Driver} to use for database access. */ protected transient Driver driver; /** {@code ConnectionPool} instance used to source connections. */ protected transient ConnectionPool pool; /** {@code PrintWriter} instance used for logging. */ protected transient PrintWriter logWriter; // ------------------------------- // Standard DataSource properties. // ------------------------------- /** Description of this DataSource. */ private String description; // ----------------------------- // Custom DataSource properties. // ----------------------------- /** JNDI name of the {@code DBPoolDataSource}. */ private String name; /** Fully-qualified class name of the JDBC Driver for database access. */ private String driverClassName; /** JDBC URI protocol string. */ private String url; /** Fully-qualified class name of the {@link PasswordDecoder} for decoding passwords. */ private String passwordDecoderClassName; /** Fully-qualified class name of the {@link ConnectionValidator} for validating database connections. */ private String validatorClassName; /** SQL query string to use for validating database connections. */ private String validationQuery; /** Pool selection strategy. */ private String selection; /** Connection pool {@code minPool} parameter. */ private int minPool = 0; /** Connection pool {@code maxPool} parameter. */ private int maxPool = 0; /** Connection pool {@code maxSize} parameter. */ private int maxSize = 0; /** Connection pool {@code idleTimeout} parameter (seconds). */ private int idleTimeout = 0; /** Timeout in seconds for database connection attempts. */ private int loginTimeout = 3; /** Properties to send to driver. */ private Properties props = new Properties(); /** Flag determining whether a pool shutdown-hook is registered. */ private boolean shutdownHook = false; /** * Creates a new {@code DBPoolDataSource} instance. */ public DBPoolDataSource() { } /** * Registers a shutdown hook for this ConnectionPoolManager instance * to ensure it is released if the JVM exits */ public synchronized void registerShutdownHook() { this.shutdownHook = true; if (pool != null) pool.registerShutdownHook(); } /** * Unregisters a registered shutdown hook for this ConnectionPoolManager instance. */ public synchronized void removeShutdownHook() { this.shutdownHook = false; if (pool != null) pool.removeShutdownHook(); } /** * Writes a message to the log. * @param message message to write */ protected synchronized void log(String message) { String s = (name != null) ? (name + ": " + message) : message; logger.info(s); if (logWriter != null) logWriter.println(s); } /** * Writes a message with a {@code Throwable} to the log file. * @param message message to write * @param throwable {@code Throwable} instance to log */ protected synchronized void log(String message, Throwable throwable) { String s = (name != null) ? (name + ": " + message) : message; logger.info(s, throwable); if (logWriter != null) { logWriter.println(s); throwable.printStackTrace(logWriter); } } /** * Creates a new {@code DBPoolDataSource} instance. * @throws SQLException if required resources cannot be located/established */ protected synchronized void createConnectionPool() throws SQLException { logger.debug("ClassLoader is of type: " + getClass().getClassLoader().getClass().getName()); // Registered JDBC driver (if required). if (driver == null) { try { driver = (Driver)Class.forName(getDriverClassName()).newInstance(); DriverManager.registerDriver(driver); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { SQLException sqlx = new SQLException("Unable to register JDBC driver: " + getDriverClassName()); sqlx.initCause(ex); log(sqlx.getMessage(), sqlx); throw sqlx; } } // Create connection pool. String poolName = POOL_NAME_PREFIX + getName(); pool = new ConnectionPool(poolName, getMinPool(), getMaxPool(), getMaxSize(), getIdleTimeout(), getUrl(), props); pool.addConnectionPoolListener(this); if (getLogWriter() != null) pool.setLog(getLogWriter()); if (shutdownHook) pool.registerShutdownHook(); // Set ConnectionValidator as required. if (validatorClassName != null && !"".equals(validatorClassName)) { try { ConnectionValidator cv = (ConnectionValidator)Class.forName(validatorClassName).newInstance(); pool.setValidator(cv); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { log("Unable to instantiate validator class: " + validatorClassName); } } else if (validationQuery != null && !"".equals(validationQuery)) { ConnectionValidator cv = new SimpleQueryValidator(validationQuery); pool.setValidator(cv); } // Set PasswordDecoder as required. if (passwordDecoderClassName != null && !"".equals(passwordDecoderClassName)) { try { PasswordDecoder pd = (PasswordDecoder)Class.forName(passwordDecoderClassName).newInstance(); pool.setPasswordDecoder(pd); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { log("Unable to instantiate password decoder class: " + passwordDecoderClassName); } } // Set selection stragegy as required. if (selection != null) { switch (selection) { case "FIFO": pool.setSelectionStrategy(ObjectPool.Strategy.SELECT_FIFO); break; case "RANDOM": pool.setSelectionStrategy(ObjectPool.Strategy.SELECT_RANDOM); break; case "LIFO": default: } } } /** * Attempts to establish a connection with the database. * @return a {@code Connection} instance, or null if unable to connect * @throws java.sql.SQLException if a database access error occurs */ @Override public synchronized Connection getConnection() throws SQLException { if (pool == null) createConnectionPool(); // Get connection from pool. return getLoginTimeout() > 0 ? pool.getConnection(1000L * getLoginTimeout()) : pool.getConnection(); } /** * Attempts to establish a connection with the database. * @param username the database user on whose behalf the connection is being made * @param password the user's password * @return a {@code Connection} instance, or null if unable to connect * @throws java.sql.SQLException if a database access error occurs */ @Override public synchronized Connection getConnection(String username, String password) throws SQLException { throw new UnsupportedOperationException("Unsupport method; use getConnection() instead."); } /** * Synonym for {@link #releaseImmediately()} retained for backward * compatibility; will be removed. * @deprecated Use {@link #releaseImmediately()} instead */ @Deprecated public synchronized void releaseConnectionPool() { releaseImmediately(); } /** * Returns the description of this DataSource. * @return The description of this DataSource */ public synchronized String getDescription() { return this.description; } /** * Sets the description of this DataSource. * @param description description */ public synchronized void setDescription(String description) { this.description = description; } /** * Returns the username to use with this DataSource. * @return The username to use with this DataSource */ public synchronized String getUser() { return props.getProperty("user"); } /** * Sets the username to use with this DataSource. * @param username username */ public synchronized void setUser(String username) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); props.setProperty("user", username); } /** * Returns the password to use with this DataSource. * @return The password to use with this DataSource */ public synchronized String getPassword() { return props.getProperty("password"); } /** * Sets the password to use with this DataSource. * @param password password */ public synchronized void setPassword(String password) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); props.setProperty("password", password); } /** * Returns the JNDI name of the {@code DBPoolDataSource} instance. * @return The JNDI name of the {@code DBPoolDataSource} instance */ public synchronized String getName() { return name; } /** * Sets the JNDI name of the {@code DBPoolDataSource} instance. * @param name JNDI name */ public synchronized void setName(String name) { this.name = name; } /** * Returns the fully-qualified class name for the JDBC driver to use. * @return The fully-qualified class name for the JDBC driver to use */ public synchronized String getDriverClassName() { return this.driverClassName; } /** * Sets the class name for the JDBC driver to use. * @param driverClassName fully-qualified driver class name to use */ public synchronized void setDriverClassName(String driverClassName) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); this.driverClassName = driverClassName; } /** * Returns the fully-qualified class name of the {@link PasswordDecoder}. * @return The fully-qualified class name of the {@link PasswordDecoder} */ public synchronized String getPasswordDecoderClassName() { return this.passwordDecoderClassName; } /** * Sets the class name of the {@link PasswordDecoder} to use. * The specified class should implement the {@code PasswordDecoder} interface, * and have a no-argument constructor which can be used to instantiate it for use. * @param decoderClassName fully-qualified class name of password decoder to use */ public synchronized void setPasswordDecoderClassName(String decoderClassName) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); this.passwordDecoderClassName = decoderClassName; } /** * Returns the fully-qualified class name of the {@link ConnectionValidator}. * @return The fully-qualified class name of the {@link ConnectionValidator} */ public synchronized String getValidatorClassName() { return this.validatorClassName; } /** * Sets the class name of the {@link ConnectionValidator} to use. * The specified class should implement the {@code ConnectionValidator} * interface, and have a no-argument constructor which can be used to * instantiate it for use. * @param validatorClassName fully-qualified class name of validator to use */ public synchronized void setValidatorClassName(String validatorClassName) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); this.validatorClassName = validatorClassName; } /** * Returns the SQL query string to issue for connection validation. * This query is only used if the {@code validationClassName} has not * been explicitly set, in which case this query string is used with an * instance of {@link SimpleQueryValidator}. * @return SQL query string used for validation */ public synchronized String getValidationQuery() { return this.validationQuery; } /** * Sets the SQL query string to issue for connection validation. * This query is only used if the {@code validationClassName} has not * been explicitly set, in which case this query string is used with an * instance of {@link SimpleQueryValidator}. * @param validationQuery SQL query to use for validation */ public synchronized void setValidationQuery(String validationQuery) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); this.validationQuery = validationQuery; } /** * Returns the JDBC URL to use with this DataSource. * @return The JDBC URL to use with this DataSource */ public synchronized String getUrl() { return this.url; } /** * Sets the JDBC URL to use with this DataSource. * @param url JDBC URL to use */ public synchronized void setUrl(String url) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); this.url = url; } /** * Returns the minimum number of pooled connections in the underlying {@link ConnectionPool}. * @return The minimum number of pooled connections in the underlying {@link ConnectionPool} */ public synchronized int getMinPool() { return minPool; } /** * Sets the minimum number of pooled connections in the underlying {@link ConnectionPool}. * @param minPool minimum number of pooled connections */ public synchronized void setMinPool(int minPool) { this.minPool = minPool; if (pool != null) pool.setParameters(this.minPool, pool.getMaxPool(), pool.getMaxSize(), pool.getIdleTimeout()); } /** * Returns the maximum number of pooled connections in the underlying {@link ConnectionPool}. * @return The maximum number of pooled connections in the underlying {@link ConnectionPool} */ public synchronized int getMaxPool() { return maxPool; } /** * Sets the maximum number of pooled connections in the underlying {@link ConnectionPool}. * @param maxPool maximum number of pooled connections */ public synchronized void setMaxPool(int maxPool) { this.maxPool = maxPool; if (pool != null) pool.setParameters(pool.getMinPool(), this.maxPool, pool.getMaxSize(), pool.getIdleTimeout()); } /** * Returns the maximum number of connections in the underlying {@link ConnectionPool}. * @return The maximum number of connections in the underlying {@link ConnectionPool} */ public synchronized int getMaxSize() { return maxSize; } /** * Sets the maximum number of connections in the underlying {@link ConnectionPool}. * @param maxSize maximum number of connections */ public synchronized void setMaxSize(int maxSize) { this.maxSize = maxSize; if (pool != null) pool.setParameters(pool.getMinPool(), pool.getMaxPool(), this.maxSize, pool.getIdleTimeout()); } /** * Returns the idle timeout (seconds) for connections in the underlying {@link ConnectionPool}. * @return The idle timeout (seconds) for connections in the underlying {@link ConnectionPool} */ public synchronized int getIdleTimeout() { return idleTimeout; } /** * Sets the idle timeout (seconds) for connections in the underlying {@link ConnectionPool}. * @param idleTimeout idle timeout (seconds) */ public synchronized void setIdleTimeout(int idleTimeout) { this.idleTimeout = idleTimeout; if (pool != null) pool.setParameters(pool.getMinPool(), pool.getMaxPool(), pool.getMaxSize(), this.idleTimeout * 1000L); } /** * Returns the driver property for the specified key. * @param key property key * @return the driver property for the specified key */ public synchronized String getConnectionProperty(String key) { Objects.requireNonNull(key); return props.getProperty(key); } /** * Sets the driver property for the specified key. * @param key property key * @param value value of property */ public synchronized void setConnectionProperty(String key, String value) { Objects.requireNonNull(key); if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); if (value == null) props.remove(key); props.put(key, value); } /** * Returns a string denoting the pool selection strategy to use (one of LIFO/FIFO/RANDOM). * @return A string denoting the pool selection strategy to use (one of LIFO/FIFO/RANDOM) */ public synchronized String getSelectionStrategy() { return this.selection; } /** * Sets the class name for the JDBC driver to use. * @param selection string representing pool selection strategy to use (one of LIFO/FIFO/RANDOM) */ public synchronized void setSelectionStrategy(String selection) { if (pool != null) throw new IllegalStateException("Cannot call this method after DBPoolDataSource has been initialized"); if (selection == null) { this.selection = null; return; } String s = selection.trim().toUpperCase(); switch (s) { case "LIFO": case "FIFO": case "RANDOM": this.selection = selection; break; default: throw new IllegalArgumentException("Invalid selection strategy specified: " + selection); } } /** * Retrieves the log writer for this DataSource. */ @Override public synchronized PrintWriter getLogWriter() { return logWriter; } /** * Sets the log writer for this DataSource to the given {@code PrintWriter}. * @param out the new log writer; to disable logging, set to null */ @Override public synchronized void setLogWriter(PrintWriter out) { this.logWriter = out; if (pool != null) pool.setLog(this.logWriter); } /** * Sets the maximum time in seconds that this DataSource will wait while * attempting to connect to a database. A value of zero specifies that the * timeout is the default system timeout if there is one; * otherwise, it specifies that there is no timeout. * When a {@code DataSource} object is created, the login timeout is * initially zero. * @param seconds the DataSource login time limit */ @Override public synchronized void setLoginTimeout(int seconds) { this.loginTimeout = seconds; } @Override public synchronized int getLoginTimeout() { return this.loginTimeout; } /** * Releases the delegate {@link ConnectionPool} instance. */ public void release() { if (pool != null) pool.release(); } /** * Releases the delegate {@link ConnectionPool} instance allowing the * specified timeout before forcibly destroying connections. * A negative timeout is equivalent to no timeout, and the method will wait * for items to be checked in before destruction. If timeout &gt;= 0 then * items will be forcibly destroyed after the specified time has elapsed. * @param timeout timeout after which to forcibly destroy items (-1 for no timeout) */ public void release(long timeout) { if (pool != null) pool.release(timeout); } /** * Asynchronously releases the delegate {@link ConnectionPool} instance. */ public void releaseAsync() { if (pool != null) pool.releaseAsync(); } /** * Asynchronously releases the delegate {@link ConnectionPool} instance. * @param timeout timeout after which to forcibly destroy items (-1 for no timeout) */ public void releaseAsync(long timeout) { if (pool != null) pool.releaseAsync(timeout); } /** * Synonym for {@link #releaseImmediately()} retained for backward * compatibility; will be removed. * @deprecated Use {@link #releaseImmediately()} instead */ @Deprecated public void releaseForcibly() { if (pool != null) pool.releaseForcibly(); } /** * Immediately releases the delegate {@link ConnectionPool} instance. */ public void releaseImmediately() { if (pool != null) pool.releaseImmediately(); } @Override public synchronized String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()); sb.append('['); sb.append("name="); sb.append(getName()); sb.append(",driverClassName="); sb.append(getDriverClassName()); sb.append(",url="); sb.append(getUrl()); sb.append(",user="); sb.append(getUser()); sb.append(",loginTimeout="); sb.append(getLoginTimeout()); sb.append(",minPool="); sb.append(getMinPool()); sb.append(",maxPool="); sb.append(getMaxPool()); sb.append(",maxSize="); sb.append(getMaxSize()); sb.append(",idleTimeout="); sb.append(getIdleTimeout()); sb.append("s"); return sb.toString(); } @Override public synchronized boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isInstance(pool); } @Override public synchronized <T> T unwrap(Class<T> iface) throws SQLException { try { return iface.cast(pool); } catch (ClassCastException ccx) { throw new SQLException("Invalid interface specified for unwrap operation: " + iface.getName(), ccx); } } //************************************************************* // Event listener methods to maintain synchronization with pool //************************************************************* @Override public void poolInitCompleted(ConnectionPoolEvent evt) { } @Override public void poolCheckOut(ConnectionPoolEvent evt) { } @Override public void poolCheckIn(ConnectionPoolEvent evt) { } @Override public void validationError(ConnectionPoolEvent evt) { } @Override public void maxPoolLimitReached(ConnectionPoolEvent evt) { } @Override public void maxPoolLimitExceeded(ConnectionPoolEvent evt) { } @Override public void maxSizeLimitReached(ConnectionPoolEvent evt) { } @Override public void maxSizeLimitError(ConnectionPoolEvent evt) { } @Override public void poolFlushed(ConnectionPoolEvent evt) { } // Synchronizes parameters in case they are changed externally. @Override public synchronized void poolParametersChanged(ConnectionPoolEvent evt) { synchronized(pool) { this.minPool = pool.getMinPool(); this.maxPool = pool.getMaxPool(); this.maxSize = pool.getMaxSize(); this.idleTimeout = (int)pool.getIdleTimeout(); } } @Override public synchronized void poolReleased(ConnectionPoolEvent evt) { pool.removeConnectionPoolListener(this); pool = null; } //********************************** // Interface methods from JDBC 4.1 //********************************** // --- JDBC 4.1 --- @Override public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("DBPool uses SLF4J logging."); } // --- End JDBC 4.1 --- }
true
08d494e150767eb404af5c7c92ebdedc8e850300
Java
Facebook-Governance/AutomationFramework
/WebAppAutomation/src/main/java/com/org/pages/LandingPage.java
UTF-8
4,936
2.359375
2
[]
no_license
package com.org.pages; import java.util.List; import java.util.Random; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import com.org.Util.DataUtils; import com.org.Util.LocatorUtils; import com.org.Util.SeleniumUtils; public class LandingPage extends SeleniumUtils { public LandingPage(WebDriver driver) { super(driver); } public void selectWomenCategory() { click(LocatorUtils.getLocator("LandingPage.Women.Tab")); } public void applyThreeFilters() { click(LocatorUtils.getLocator("LandingPage.Women.Tab")); } public void selectProductFromTheListWithPrice(String price) { List<WebElement> products = getWebElements(LocatorUtils.getLocator("ProductList")); List<WebElement> productPrice = getWebElements(LocatorUtils.getLocator("ProductListWithPrice")); List<WebElement> productImage = getWebElements(LocatorUtils.getLocator("ProductImage")); for (int i = 0; i < products.size(); i++) { moveToElement(products.get(i)); waitFor(1); if (productPrice.get(i).getText().trim().equals(price)) { if (i != 0) { moveToElement(products.get(i - 1)); } productImage.get(i).click(); break; } } } public void switchToFrame(By element) { driver.switchTo().frame(driver.findElement(element)); } public void switchToDefaultContent() { driver.switchTo().defaultContent(); } public void changeColorOfProductIfAvailable() { List<WebElement> findElements = driver .findElements(LocatorUtils.getLocator("CheckOutPage.ColorSelector.PickColor")); if (findElements.size() > 1) { for (WebElement element : findElements) { if (element.getAttribute("class") != null || !element.getAttribute("class").equals("selected")) { element.click(); break; } } } } public void updateQuantity() { sendkeys(LocatorUtils.getLocator("ProductPage.Update.Quantity"), DataUtils.getTestData("QuantityToBeUpdated")); } public void selectSize() { Select ProductSize = new Select(driver.findElement(LocatorUtils.getLocator("ProductPage.SelectSize"))); ProductSize.selectByVisibleText(DataUtils.getTestData("ProductSizeToBeSelected")); } public void submitTheProduct() { click(LocatorUtils.getLocator("CheckOutPage.AddProduct.Button")); } public void proceedToCheckOut() { click(LocatorUtils.getLocator("CheckOutPage.ProceedToCheckOut.Button")); } public void reviewAndProceedToCheckOutProduct() { click(LocatorUtils.getLocator("ShoppingCart.ProceedToCheckOut.Button")); } public void loginToPortal() { sendkeys(LocatorUtils.getLocator("CheckOutPage.Login.Email"), DataUtils.getTestData("LoginEmail")); sendkeys(LocatorUtils.getLocator("CheckOutPage.Login.Password"), DataUtils.getTestData("LoginPassword")); click(LocatorUtils.getLocator("CheckOutPage.Login.SubmitButton")); } public void addNewAddress() { click(LocatorUtils.getLocator("AddressPage.AddNewAddress.Button")); System.out.println("Add New Address Now"); sendkeys(LocatorUtils.getLocator("AddressPage.AddressInput.AddressTextField"), DataUtils.getTestData("AddressLine")); sendkeys(LocatorUtils.getLocator("AddressPage.AddressInput.CityInput"), DataUtils.getTestData("City")); Select state = new Select(driver.findElement(LocatorUtils.getLocator("AddressPage.AddressInput.StateInput"))); state.selectByVisibleText(DataUtils.getTestData("State")); sendkeys(LocatorUtils.getLocator("AddressPage.AddressInput.ZipCodeInput"), DataUtils.getTestData("ZipCode")); sendkeys(LocatorUtils.getLocator("AddressPage.AddressInput.PhoneInput"), DataUtils.getTestData("HomePhoneNumber")); sendkeys(LocatorUtils.getLocator("AddressPage.AddressInput.MobilePhoneInput"), DataUtils.getTestData("MobilePhone")); sendkeys(LocatorUtils.getLocator("AddressPage.AddressInput.AddressAlias"), "My Address" + new Random().nextInt(1000000000)); click(LocatorUtils.getLocator("AddressPage.AddressInput.SaveAddressButton")); click(LocatorUtils.getLocator("AddressPage.ContnueButton")); } public void shippingPageAcceptTnC() { click(LocatorUtils.getLocator("ShippingPage.enableCheckBox")); click(LocatorUtils.getLocator("ShippingPage.SubmitButton")); } public void paymentPageForOder() { click(LocatorUtils.getLocator("PaymentPage.OptionBankWire.Tab")); click(LocatorUtils.getLocator("OrderConfirmationPage.ConfirmOrderButton")); } public void orderConfirmation() { Assert.assertEquals(getText(LocatorUtils.getLocator("OrderVerificationPage.TextVerification")), DataUtils.getTestData("OrderConfirmationText")); Assert.assertTrue(isDisplayed(LocatorUtils.getLocator("OrderVerificationPage.TextVerification")), "Oder has not been placed !!"); } }
true
e80aa6513703ddeb9d8e8db76a098ae8943d87c9
Java
suntinghui/LKOA4Android_Desea
/src/com/lkoa/activity/ScheduleActiveContentActivity.java
UTF-8
2,867
2.03125
2
[]
no_license
package com.lkoa.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.lkoa.R; import com.lkoa.business.ScheduleManager; import com.lkoa.client.LKAsyncHttpResponseHandler; import com.lkoa.model.JTHDContentItem; import com.lkoa.model.RCContentItem; import com.lkoa.util.LogUtil; /** * 日程安排-活动内容页 */ public class ScheduleActiveContentActivity extends CenterMsgBaseActivity { private static final String TAG = "ScheduleActiveContentActivity"; private ScheduleManager mScheduleMgr; private String mInfoId; private int mTitleResId; private LinearLayout mLinearContent; private View [] mViews = new View[8]; private String [] mNames = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule_active_content); mScheduleMgr = new ScheduleManager(); Intent intent = getIntent(); mInfoId = intent.getStringExtra("InfoId"); mTitleResId = intent.getIntExtra("titleResId", -1); mNames = getResources().getStringArray(R.array.active_content_item_names); findViews(); setupViews(); } @Override protected void findViews() { super.findViews(); mLinearContent = (LinearLayout)findViewById(R.id.content); mViews[0] = findViewById(R.id.active_title); mViews[1] = findViewById(R.id.active_hddd); mViews[2] = findViewById(R.id.active_fqbm); mViews[3] = findViewById(R.id.active_date); mViews[4] = findViewById(R.id.active_state); mViews[5] = findViewById(R.id.active_cyr); mViews[6] = findViewById(R.id.active_cjld); mViews[7] = findViewById(R.id.active_nr); } @Override protected void setupViews() { super.setupViews(); mTvTitle.setText(mTitleResId); mScheduleMgr.getJTHD(mApp.getUserId(), mInfoId, new LKAsyncHttpResponseHandler() { @Override public void successAction(Object obj) { LogUtil.i(TAG, "successAction(), obj="+obj); JTHDContentItem item = (JTHDContentItem) obj; mLinearContent.setVisibility(View.VISIBLE); setViews(item); } }); } private void setViews(JTHDContentItem item) { String[] contentVals = new String[8]; contentVals[0] = item.title; contentVals[1] = item.hddd; contentVals[2] = item.fqbm; contentVals[3] = item.date; contentVals[4] = item.state; contentVals[5] = item.cyr; contentVals[6] = item.cjld; contentVals[7] = item.nr; TextView title, content; for(int i=0; i<mViews.length; i++) { title = (TextView)mViews[i].findViewById(R.id.title); content = (TextView)mViews[i].findViewById(R.id.content_text); title.setText(mNames[i]); content.setText(contentVals[i]); } } }
true
6a0c5e7a60ae13cb88b725365bdc4f8012dba8cf
Java
nkn6294live/javalib
/src/main/java/nkn6294/java/lib/io/DefaultConvertData.java
UTF-8
720
2.703125
3
[]
no_license
package nkn6294.java.lib.io; import java.nio.charset.Charset; public class DefaultConvertData implements IConvertData { public DefaultConvertData() { } @Override public byte[] encrypt(String string) { if(string == null) { return null; } return string.getBytes(Charset.forName("UTF8")); } @Override public String decrypt(byte[] data) { if(data == null) { return null; } return new String(data, Charset.forName("UTF8")); } @Override public byte[] encryptBytes(byte[] data) { return data; } @Override public byte[] decryptBytes(byte[] data) { return data; } }
true
ef4da9e49bc1eb673ed9f609a81feceb481c203c
Java
sidalingooh/lmrd_management
/src/main/java/com/lmrd/service/user/BackUserRoleService.java
UTF-8
947
1.796875
2
[]
no_license
package com.lmrd.service.user; import com.lmrd.entity.user.BackUserRole; import com.lmrd.entity.user.BackUserRoleExample; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BackUserRoleService { long countByExample(BackUserRoleExample example); int deleteByExample(BackUserRoleExample example); int deleteByPrimaryKey(Long backUserRoleId); int insert(BackUserRole record); int insertSelective(BackUserRole record); List<BackUserRole> selectByExample(BackUserRoleExample example); BackUserRole selectByPrimaryKey(Long backUserRoleId); int updateByExampleSelective(@Param("record") BackUserRole record, @Param("example") BackUserRoleExample example); int updateByExample(@Param("record") BackUserRole record, @Param("example") BackUserRoleExample example); int updateByPrimaryKeySelective(BackUserRole record); int updateByPrimaryKey(BackUserRole record); }
true
48850c933f4db633e8835bc3a2ccc6ad482fce5c
Java
shianliang/skymall
/skymall-manager/skymall-manager-web/src/main/java/com/skymall/controller/ItemParamController.java
UTF-8
2,322
2.078125
2
[]
no_license
package com.skymall.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.skymall.common.pojo.DataResult; import com.skymall.common.pojo.SkymallResult; import com.skymall.common.utils.JsonUtils; import com.skymall.pojo.TbItemParam; import com.skymall.service.ItemParamService; /** * * <p>Title: ItemParamController</p> * <p>Description: 规格参数controller</p> * @author shianliang * @date 2018年4月22日 */ @Controller public class ItemParamController { @Autowired private ItemParamService itemParamService; /** * * <p>Title: itemParamList</p> * <p>Description:规格参数列表 </p> * @author shianliang * @date 2018年4月22日 * @version 1.0 * @param page * @param rows * @return */ @RequestMapping(value="/item/param/list",method=RequestMethod.GET) @ResponseBody public DataResult itemParamList(int page,int rows){ return itemParamService.itemParamList(page, rows); } /** * * <p>Title: getItemParamByItemCatId</p> * <p>Description:通过商品ID查询商品规格 </p> * @author shianliang * @date 2018年4月22日 * @version 1.0 * @param itemCatId * @return */ @RequestMapping("/item/param/query/itemcatid/{itemcatid}") @ResponseBody public SkymallResult getItemParamByItemCatId(@PathVariable("itemcatid")long itemCatId ){ return itemParamService.getItemParamByCatId(itemCatId); } /** * * <p>Title: saveItemParam</p> * <p>Description: 保存规格参数</p> * @author shianliang * @date 2018年4月22日 * @version 1.0 * @param cid * @param paramData * @return */ @RequestMapping("item/param/save/{cid}") @ResponseBody public SkymallResult saveItemParam(@PathVariable long cid,String paramData){ TbItemParam itemParam=new TbItemParam(); itemParam.setParamData(paramData); itemParam.setItemCatId(cid); return itemParamService.saveItemParam(itemParam); } }
true
32d7e4af736713dbb3966b9d44b3eafa8abf74c9
Java
ligarnes/campaign-player
/DistributedBeanManager/src/main/java/net/alteiar/shared/IUniqueObject.java
UTF-8
88
1.851563
2
[]
no_license
package net.alteiar.shared; public interface IUniqueObject { UniqueID getId(); }
true
505de06e1dd017c71692a041c4450bc8100e0ed9
Java
DanielGrech/TweeterTweeter
/src/com/DGSD/TweeterTweeter/DataFetchers/FetchProfileInfo.java
UTF-8
713
2.25
2
[]
no_license
package com.DGSD.TweeterTweeter.DataFetchers; import twitter4j.TwitterException; import twitter4j.User; import android.content.ContentValues; import com.DGSD.TweeterTweeter.StatusData; import com.DGSD.TweeterTweeter.TTApplication; public class FetchProfileInfo extends DataFetcher { public FetchProfileInfo(TTApplication app) { super(app); } public int fetchData(String account, String user, int type) throws TwitterException { User u = mTwitter.showUser(mTwitter.getId()); if(u != null){ ContentValues values = StatusData.createUserContentValues(account, user, u); if(mApplication.getStatusData(). insert(StatusData.PROFILE_TABLE, values)) { count++; } } return count; } }
true
25e89125619237995bb82ea5d0368b3821ef02cb
Java
mapleKirito/digital_teach
/src/main/java/com/linktones/digital_teach/service/LoginService.java
UTF-8
174
1.734375
2
[]
no_license
package com.linktones.digital_teach.service; import javax.servlet.http.Cookie; public interface LoginService { Cookie setLoginToken(String account, String password); }
true
961b9ebe7a7d26c0ec5552b03b12f688f1a4327d
Java
lixinyugithub/repo
/HisLite/hislite-payment-app/src/main/java/com/nbteam/hislite/payment/pay/mapper/PaymentMerchantMapper.java
UTF-8
800
1.875
2
[]
no_license
package com.nbteam.hislite.payment.pay.mapper; import com.nbteam.hislite.payment.api.pay.dto.PaymentMerchant; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface PaymentMerchantMapper { int deleteByPrimaryKey(Long insideMerchantId); int insert(PaymentMerchant record); int insertSelective(PaymentMerchant record); PaymentMerchant selectByPrimaryKey(Long insideMerchantId); int updateByPrimaryKeySelective(PaymentMerchant record); int updateByPrimaryKey(PaymentMerchant record); PaymentMerchant getPaymentMerchantByMode(@Param("hisId") Long hisId, @Param("bizChannel") String bizChannel, @Param("bizType") String bizType, @Param("payMode") String payMode); }
true
830e2eb9e27f4e0a2b99509a7251644cf0122fc5
Java
BorisChens/WL
/app/src/main/java/com/soft/zkrn/weilin_application/Activities/Setting/setting_function_photo.java
UTF-8
1,835
2.203125
2
[]
no_license
package com.soft.zkrn.weilin_application.Activities.Setting; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import com.zhy.base.fileprovider.FileProvider7; import java.io.File; public class setting_function_photo extends Setting_FeedBack { public static final int RC_CHOOSE_PHOTO = 2; //通过相册获取图片 private void choosePhoto() { //Intent.ACTION_PICK为选择数据 Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null); //"image/*"意思为路径 intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intentToPickPic, RC_CHOOSE_PHOTO); } // /* 实现拍照功能 */ public static final int RC_TAKE_PHOTO = 1; private String mTempPhotoPath; private Uri imageUri; private void takePhoto() { //ACTION_IMAGE_CAPTURE节省很多时间,不需要单独开发相机UI,直接调用系统相机 Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //访问SD卡下的文件夹 File fileDir = new File(Environment.getExternalStorageDirectory() + File.separator + "photoTest" + File.separator); //文件不存在 if (!fileDir.exists()) { fileDir.mkdirs(); } //选择图片形式 File photoFile = new File(fileDir, "photo.jpeg"); //获得绝对路径 mTempPhotoPath = photoFile.getAbsolutePath(); //调用了一个小众库的方法 imageUri = FileProvider7.getUriForFile(this, photoFile); //输入数据 intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intentToTakePhoto, RC_TAKE_PHOTO); } }
true
cfade2ceb2059d637518093124133da467d2ed2e
Java
5l1v3r1/pyramid-1
/core/src/main/java/edu/neu/ccs/pyramid/eval/MAP.java
UTF-8
7,035
2.6875
3
[ "Apache-2.0" ]
permissive
package edu.neu.ccs.pyramid.eval; import edu.neu.ccs.pyramid.dataset.MultiLabel; import edu.neu.ccs.pyramid.dataset.MultiLabelClfDataSet; import edu.neu.ccs.pyramid.multilabel_classification.MultiLabelClassifier; import edu.neu.ccs.pyramid.multilabel_classification.Utils; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * mean average precision * Created by chengli on 12/27/16. */ public class MAP { /** * compute mean average precision over given labels * @param classifier * @param dataSet * @return */ public static double map(MultiLabelClassifier.ClassProbEstimator classifier, MultiLabelClfDataSet dataSet, List<Integer> labels){ int numData = dataSet.getNumDataPoints(); double[][] probs = new double[dataSet.getNumDataPoints()][classifier.getNumClasses()]; IntStream.range(0, dataSet.getNumDataPoints()).parallel() .forEach(i->probs[i] = classifier.predictClassProbs(dataSet.getRow(i))); double sum = 0; for (int l: labels){ int[] binaryLabels = new int[numData]; double[] marginals = new double[numData]; for (int i=0;i<numData;i++){ if (dataSet.getMultiLabels()[i].matchClass(l)){ binaryLabels[i] = 1; } // leave the marginal 0 if l is a novel label in test set if (l<classifier.getNumClasses()){ marginals[i] = probs[i][l]; } } double averagePrecision = AveragePrecision.averagePrecision(binaryLabels, marginals); // System.out.println("AP for label "+l+"="+averagePrecision); sum += averagePrecision; } return sum/labels.size(); } /** * label MAP; marginals are provided by the classifiers * @param classifier * @param dataSet * @return */ public static double map(MultiLabelClassifier.ClassProbEstimator classifier, MultiLabelClfDataSet dataSet){ List<Integer> labels = IntStream.range(0, dataSet.getNumClasses()).boxed().collect(Collectors.toList()); return map(classifier, dataSet, labels); } public static double[] labelMapDetail(MultiLabelClassifier.ClassProbEstimator classifier, MultiLabelClfDataSet dataSet){ if (classifier.getNumClasses()!=dataSet.getNumClasses()){ throw new IllegalArgumentException("classifier.getNumClasses()!=dataSet.getNumClasses()"); } int numData = dataSet.getNumDataPoints(); double[][] probs = new double[dataSet.getNumDataPoints()][dataSet.getNumClasses()]; IntStream.range(0, dataSet.getNumDataPoints()).parallel() .forEach(i->probs[i] = classifier.predictClassProbs(dataSet.getRow(i))); double[] ap = new double[classifier.getNumClasses()]; for (int l=0;l<classifier.getNumClasses();l++){ int[] binaryLabels = new int[numData]; double[] marginals = new double[numData]; for (int i=0;i<numData;i++){ if (dataSet.getMultiLabels()[i].matchClass(l)){ binaryLabels[i] = 1; } marginals[i] = probs[i][l]; } ap[l] = AveragePrecision.averagePrecision(binaryLabels, marginals); } return ap; } /** * label MAP * marginals are estimated through support combinations * @param classifier * @param dataSet * @return */ public static double mapBySupport(MultiLabelClassifier.AssignmentProbEstimator classifier, MultiLabelClfDataSet dataSet, List<MultiLabel> combinations){ if (classifier.getNumClasses()!=dataSet.getNumClasses()){ throw new IllegalArgumentException("classifier.getNumClasses()!=dataSet.getNumClasses()"); } int numData = dataSet.getNumDataPoints(); double[][] probs = new double[dataSet.getNumDataPoints()][dataSet.getNumClasses()]; IntStream.range(0, dataSet.getNumDataPoints()).parallel() .forEach(i->{ double[] comProbs = classifier.predictAssignmentProbs(dataSet.getRow(i),combinations); probs[i] = Utils.marginals(combinations, comProbs, classifier.getNumClasses()); }); double sum = 0; for (int l=0;l<dataSet.getNumClasses();l++){ int[] binaryLabels = new int[numData]; double[] marginals = new double[numData]; for (int i=0;i<numData;i++){ if (dataSet.getMultiLabels()[i].matchClass(l)){ binaryLabels[i] = 1; } marginals[i] = probs[i][l]; } double averagePrecision = AveragePrecision.averagePrecision(binaryLabels, marginals); System.out.println("AP for label "+l+"="+averagePrecision); sum += averagePrecision; } return sum/dataSet.getNumClasses(); } public static double instanceMAP(MultiLabelClassifier.ClassProbEstimator classifier, MultiLabelClfDataSet dataSet){ return IntStream.range(0, dataSet.getNumDataPoints()).parallel().mapToDouble(i->{ int[] binaryLabels = new int[classifier.getNumClasses()]; MultiLabel multiLabel = dataSet.getMultiLabels()[i]; for (int l:multiLabel.getMatchedLabels()) { binaryLabels[l] = 1; } double[] probs = classifier.predictClassProbs(dataSet.getRow(i)); return AveragePrecision.averagePrecision(binaryLabels, probs); }).average().getAsDouble(); } public static double instanceMAP(MultiLabelClassifier.AssignmentProbEstimator classifier, MultiLabelClfDataSet dataSet, List<MultiLabel> combinations){ return IntStream.range(0, dataSet.getNumDataPoints()).parallel().mapToDouble(i->{ int[] binaryLabels = new int[classifier.getNumClasses()]; MultiLabel multiLabel = dataSet.getMultiLabels()[i]; for (int l:multiLabel.getMatchedLabels()) { binaryLabels[l] = 1; } double[] comProbs = classifier.predictAssignmentProbs(dataSet.getRow(i),combinations); double[] probs = Utils.marginals(combinations, comProbs, classifier.getNumClasses()); return AveragePrecision.averagePrecision(binaryLabels, probs); }).average().getAsDouble(); } public static double instanceMAP(double[][] marginals, MultiLabelClfDataSet dataSet){ return IntStream.range(0, dataSet.getNumDataPoints()).parallel().mapToDouble(i->{ int[] binaryLabels = new int[dataSet.getNumClasses()]; MultiLabel multiLabel = dataSet.getMultiLabels()[i]; for (int l:multiLabel.getMatchedLabels()) { binaryLabels[l] = 1; } return AveragePrecision.averagePrecision(binaryLabels, marginals[i]); }).average().getAsDouble(); } }
true
0d38ec677802809a7e10ba5e20992ece45dc53ac
Java
MartyHub/date
/src/main/java/org/sweet/date/range/DateRange.java
UTF-8
699
2.515625
3
[]
no_license
package org.sweet.date.range; import java.io.Serializable; import org.sweet.date.AbstractDate; public class DateRange<T extends AbstractDate<T>> implements Serializable { private static final long serialVersionUID = 3661456018582942058L; private final T start; private final T end; public DateRange(T start, T end) { this.start = start; this.end = end; } public T getStart() { return start; } public T getEnd() { return end; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('['); sb.append(start); sb.append(", "); sb.append(end); sb.append('['); return sb.toString(); } }
true
5a7fdd9b559bbe2d1e4d674f9dc9b461279d4c37
Java
Cestbo/MyBlog
/src/main/java/com/example/demo/service/UserService.java
UTF-8
785
2.140625
2
[]
no_license
package com.example.demo.service; import com.example.demo.mapper.UserMapper; import com.example.demo.pojo.GithubUser; import com.example.demo.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserMapper userMapper; public void UpdateOrAddUser(User user,String account_id) { //判断数据库中是否存在该用户,用account_id判断 User db_user=userMapper.getUserByAccountId(account_id); //不存在添加 if(db_user==null) { userMapper.insert(user); } //存在更新 else { userMapper.update(user); } } }
true
710b7ef263667653c615903f0c5fc5833c8fc3d5
Java
PicnicSupermarket/error-prone
/core/src/test/java/com/google/errorprone/bugpatterns/JdkObsoleteTest.java
UTF-8
11,124
2.265625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode.TEXT_MATCH; import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.CompilationTestHelper; import java.util.Enumeration; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link JdkObsolete}Test */ @RunWith(JUnit4.class) public class JdkObsoleteTest { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance(JdkObsolete.class, getClass()); @Test public void positive() { testHelper .addSourceLines( "Test.java", "import java.nio.file.Path;", "class Test {", " {", " // BUG: Diagnostic contains:", " new java.util.LinkedList<>();", " // BUG: Diagnostic contains:", " new java.util.Stack<>();", " // BUG: Diagnostic contains:", " new java.util.Vector<>();", " // BUG: Diagnostic contains:", " new java.util.Hashtable<>();", " // BUG: Diagnostic contains:", " new StringBuffer();", " // BUG: Diagnostic contains:", " new java.util.Hashtable<Object, Object>() {};", " }", "}") .doTest(); } @Test public void stringBuffer_appendReplacement() { testHelper .addSourceLines( "Test.java", "import java.util.regex.Matcher;", "class Test {", " void f(Matcher m) {", " StringBuffer sb = new StringBuffer();", " m.appendReplacement(sb, null);", " }", "}") .doTest(); } @Test public void stringBuffer_appendTail() { testHelper .addSourceLines( "Test.java", "import java.util.regex.Matcher;", "class Test {", " void f(Matcher m) {", " StringBuffer sb = new StringBuffer();", " m.appendTail(sb);", " }", "}") .doTest(); } @Test public void positiveExtends() { testHelper .addSourceLines( "Test.java", "import java.nio.file.Path;", "class Test {", " // BUG: Diagnostic contains:", " abstract class A implements java.util.Enumeration<Object> {}", " // BUG: Diagnostic contains:", " abstract class B implements java.util.SortedSet<Object> {}", " // BUG: Diagnostic contains:", " abstract class C implements java.util.SortedMap<Object, Object> {}", " // BUG: Diagnostic contains:", " abstract class D extends java.util.Dictionary<Object, Object> {}", "}") .doTest(); } @Test public void refactoring() { BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass()) .addInputLines( "in/Test.java", // "import java.util.*;", "class Test {", " Deque<Object> d = new LinkedList<>();", " List<Object> l = new LinkedList<>();", " {", " l = new LinkedList<>();", " }", " LinkedList<Object> ll = new LinkedList<>();", " List<Object> lll = new LinkedList<Object>() {{", " add(null); // yikes", " }};", "}") .addOutputLines( "out/Test.java", // "import java.util.*;", "class Test {", " Deque<Object> d = new ArrayDeque<>();", " List<Object> l = new ArrayList<>();", " {", " l = new ArrayList<>();", " }", " LinkedList<Object> ll = new LinkedList<>();", " List<Object> lll = new LinkedList<Object>() {{", " add(null); // yikes", " }};", "}") .doTest(TEXT_MATCH); } @Test public void stringBufferRefactoringTest() { BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass()) .addInputLines( "in/Test.java", // "class Test {", " String f() {", " StringBuffer sb = new StringBuffer();", " return sb.append(42).toString();", " }", "}") .addOutputLines( "out/Test.java", // "class Test {", " String f() {", " StringBuilder sb = new StringBuilder();", " return sb.append(42).toString();", " }", "}") .doTest(); } @Test public void stringBufferRefactoringTest_usingVar() { BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass()) .addInputLines( "in/Test.java", // "class Test {", " String f() {", " var sb = new StringBuffer();", " return sb.append(42).toString();", " }", "}") .addOutputLines( "out/Test.java", // "class Test {", " String f() {", " var sb = new StringBuilder();", " return sb.append(42).toString();", " }", "}") .doTest(); } /** A test input. */ public interface Lib { Enumeration<Integer> foos(); } @Test public void obsoleteOverride() { testHelper .addSourceLines( "Test.java", "import " + Lib.class.getCanonicalName() + ";", "import java.util.Enumeration;", "class Test implements Lib {", " public Enumeration<Integer> foos() {", " return new Enumeration<Integer>() {", " @Override public boolean hasMoreElements() { return false; }", " @Override public Integer nextElement() { return null; }", " };", " }", "}") .doTest(); } @Test public void additionalRefactorings() { BugCheckerRefactoringTestHelper.newInstance(JdkObsolete.class, getClass()) .addInputLines( "in/Test.java", // "import java.util.*;", "import java.util.function.*;", "class Test {", " Supplier<Deque<Object>> a = () -> new LinkedList<>();", " Supplier<Deque<Object>> b = () -> {", " return new LinkedList<>();", " };", " Supplier<Deque<Object>> c = LinkedList::new;", " Deque<Object> f() {", " return new LinkedList<>();", " }", " void g(Deque<Object> x) {}", " {", " g(new LinkedList<>());", " }", " {", " List<LinkedList<String>> xs = new ArrayList<>();", " List<List<String>> ys = new ArrayList<>();", " xs.add(new LinkedList<>());", " ys.add(new LinkedList<>());", " }", "}") .addOutputLines( "out/Test.java", // "import java.util.*;", "import java.util.function.*;", "class Test {", " Supplier<Deque<Object>> a = () -> new ArrayDeque<>();", " Supplier<Deque<Object>> b = () -> {", " return new ArrayDeque<>();", " };", " Supplier<Deque<Object>> c = ArrayDeque::new;", " Deque<Object> f() {", " return new ArrayDeque<>();", " }", " void g(Deque<Object> x) {}", " {", " g(new ArrayDeque<>());", " }", " {", " List<LinkedList<String>> xs = new ArrayList<>();", " List<List<String>> ys = new ArrayList<>();", " xs.add(new LinkedList<>());", " ys.add(new ArrayList<>());", " }", "}") .doTest(TEXT_MATCH); } @Test public void obsoleteMocking() { testHelper .addSourceLines( "Test.java", "import static org.mockito.Mockito.when;", "import " + Lib.class.getCanonicalName() + ";", "import java.util.Enumeration;", "class Test {", " void test(Lib lib) {", " when(lib.foos())", " .thenReturn(", " new Enumeration<Integer>() {", " public boolean hasMoreElements() {", " return false;", " }", " public Integer nextElement() {", " return null;", " }", " });", " }", "}") .doTest(); } @Test public void navigableSetRepro() { testHelper .addSourceLines( "Test.java", "import java.util.NavigableSet;", "import java.util.Optional;", "class Test {", " Optional<Object> fail1(Optional<NavigableSet<Object>> myOptionalSet) {", " return myOptionalSet.map(NavigableSet::first);", " }", " Optional<Object> fail2(Optional<NavigableSet<Object>> myOptionalSet) {", " return myOptionalSet.map(NavigableSet::last);", " }", "}") .doTest(); } @Test public void navigableMapInheritedMethod() { testHelper .addSourceLines( "Test.java", "import java.util.Map;", "import java.util.Set;", "import java.util.NavigableMap;", "class Test {", " void f(NavigableMap<String, Integer> m) {", " for (Integer e : m.values()) {", " }", " }", "}") .doTest(); } @Test public void indirect() { testHelper .addSourceLines( "Test.java", "import com.google.common.collect.SortedSetMultimap;", "import com.google.common.collect.TreeMultimap;", "class Test {", " void f() {", " SortedSetMultimap<String, String> myMultimap = TreeMultimap.create();", " String myValue = myMultimap.get(\"foo\").first();", " }", "}") .doTest(); } }
true
b8a8c1800d122aecbe97c277f16f82e2e544664a
Java
dongsantu/jinshuo-mall
/jinshuo-admin/src/main/java/com/jinshuo/mall/admin/web/test/gds/GdsAlbumController.java
UTF-8
1,804
2.015625
2
[]
no_license
package com.jinshuo.mall.admin.web.test.gds; import com.jinshuo.mall.admin.application.service.gds.IGdsAlbumService; import com.jinshuo.mall.admin.domain.gds.GdsAlbum; import com.jinshuo.mall.core.response.WrapperResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * 信息操作处理 * * @author dyh * @date 2020-08-12 */ @RestController @RequestMapping("/v1/wx/user/gdsAlbum") @Api(tags = "") @Slf4j public class GdsAlbumController { @Autowired private IGdsAlbumService gdsAlbumService; /** * 查询列表 */ @PostMapping("/listGdsAlbum") @ApiOperation(value = "列表", notes = "列表") public WrapperResponse listGdsAlbum(@Valid @RequestBody GdsAlbum qry) { return WrapperResponse.success(gdsAlbumService.selectGdsAlbumPage(qry)); } /** * 新增保存 */ @PostMapping("/addGdsAlbum") @ApiOperation(value = "新增", notes = "新增") public WrapperResponse addGdsAlbum(@Valid @RequestBody GdsAlbum gdsAlbum) { return WrapperResponse.success(gdsAlbumService.insertGdsAlbum(gdsAlbum)); } /** * 修改保存 */ @PostMapping("/editGdsAlbum") @ApiOperation(value = "修改", notes = "修改") public WrapperResponse editSaveGdsAlbum(@Valid @RequestBody GdsAlbum gdsAlbum) { return WrapperResponse.success(gdsAlbumService.updateGdsAlbum(gdsAlbum)); } /** * 删除 */ @PostMapping( "/removeGdsAlbum/{id}") @ApiOperation(value = "删除", notes = "删除") public WrapperResponse removeGdsAlbum(@PathVariable(value = "id") Long id) { return WrapperResponse.success(gdsAlbumService.deleteGdsAlbumById(id)); } }
true
67a52a84b3c479305c3e0e606125c2f6e5aa5dc0
Java
Jpruso4/Backend-Service-Desk
/src/main/java/com/serviceDesk/runner/application/controller/LoginController.java
UTF-8
1,351
2.03125
2
[]
no_license
package com.serviceDesk.runner.application.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.serviceDesk.runner.application.models.LoginModel; import com.serviceDesk.runner.application.models.ResponseMensajeDto; import com.serviceDesk.runner.application.service.ILoginService; import com.serviceDesk.runner.application.util.UrlsControladores; @RestController @RequestMapping(UrlsControladores.LOGIN_CONTROLLER) public class LoginController { private final ILoginService iLoginService; @Autowired public LoginController(ILoginService iLoginService) { this.iLoginService = iLoginService; } @PostMapping(value = "", produces = "application/json", consumes = "application/json") @CrossOrigin @ResponseStatus(code = HttpStatus.OK) public ResponseMensajeDto login (@Valid @RequestBody LoginModel loginModel) { return iLoginService.login(loginModel); } }
true
db0a670538d76245b322f029e49f1f9096126962
Java
MacroSong1996/springcloud
/demo-projects/sb-sqlite-multidb/src/main/java/com/boonya/sbsqlite/entity/XhWorkLog.java
UTF-8
1,270
1.984375
2
[ "Apache-2.0" ]
permissive
package com.boonya.sbsqlite.entity; public class XhWorkLog { private long id;//ID 编号自增 private String xh_work_log_data;// private String xh_work_log_content;// private String xh_work_log_send_time;// 上报时间 private String xh_work_log_type;// 日志类型 public long getId() { return id; } public void setId(long id) { this.id = id; } public String getXh_work_log_data() { return xh_work_log_data; } public void setXh_work_log_data(String xh_work_log_data) { this.xh_work_log_data = xh_work_log_data; } public String getXh_work_log_content() { return xh_work_log_content; } public void setXh_work_log_content(String xh_work_log_content) { this.xh_work_log_content = xh_work_log_content; } public String getXh_work_log_send_time() { return xh_work_log_send_time; } public void setXh_work_log_send_time(String xh_work_log_send_time) { this.xh_work_log_send_time = xh_work_log_send_time; } public String getXh_work_log_type() { return xh_work_log_type; } public void setXh_work_log_type(String xh_work_log_type) { this.xh_work_log_type = xh_work_log_type; } }
true
951c1c92f4e1f752ef5a9e3c9c802736b7f2f819
Java
gyumin-kim/objects-sample
/src/main/java/samples/ch04/Screening.java
UTF-8
1,108
2.9375
3
[]
no_license
package samples.ch04; import java.time.LocalDateTime; public class Screening { private Movie movie; private int sequence; private LocalDateTime whenScreened; public Screening(final Movie movie, final int sequence, final LocalDateTime whenScreened) { this.movie = movie; this.sequence = sequence; this.whenScreened = whenScreened; } public Money calculateFee(final int audienceCount) { switch (movie.getMovieType()) { case AMOUNT_DISCOUNT: if (movie.isDiscountable(whenScreened, sequence)) { return movie.calculateAmountDiscountFee().times(audienceCount); } break; case PERCENT_DISCOUNT: if (movie.isDiscountable(whenScreened, sequence)) { return movie.calculatePercentDiscountFee().times(audienceCount); } case NONE_DISCOUNT: return movie.calculateNoneDiscountFee().times(audienceCount); } return movie.calculateNoneDiscountFee().times(audienceCount); } }
true
600cd9d4a54338471c086cf20106a12f063ee7c2
Java
lonkiddingme/longshen
/douting_project/douting_core/src/main/java/com/cdvcloud/douting/service/impl/PublicServiceImpl.java
UTF-8
1,041
1.828125
2
[]
no_license
package com.cdvcloud.douting.service.impl; import com.cdvcloud.douting.common.CommonParameters; import com.cdvcloud.douting.common.ValidateCommonParam; import com.cdvcloud.douting.dao.PublicDao; import com.cdvcloud.douting.service.PublicService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; /** * @author SongYuanKun * @date 2017/11/4 */ @Service public class PublicServiceImpl extends BaseServiceImpl implements PublicService { @Autowired private PublicDao publicDao; /** * 更新排序字段 * * @param commonParameters * @param jsonMap * @return */ @Override public long updateWeight(CommonParameters commonParameters, Map<String, Object> jsonMap) { Map<String, Object> updateMap = new HashMap<String, Object>(16); updateMap.putAll(ValidateCommonParam.getFieldsMap(Arrays.asList("document", "key", "value", "ids"), jsonMap)); return publicDao.incValue(jsonMap); } }
true
8c6d71afe1d7d9349559898bb72ebb73aa08031d
Java
renkaigis/KeepCoding
/2017/09/08/ArrayBound.java
UTF-8
3,694
3.140625
3
[]
no_license
/** * 046:数组的下标界限(数组下标越界抛出异常) * <p> * 主程序很简单,烦的是为什么都要界面编程。 * 大致看了一下后面的程序,几乎都要使用界面。 * 有点要疯狂了!!! */ import java.awt.BorderLayout; import java.awt.EventQueue; import java.text.NumberFormat; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.JFormattedTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; public class ArrayBound extends JFrame { private JPanel contentPane; private JFormattedTextField codeField; private JTextArea textArea; /** * Launch the application. */ // 书中源码所使用的界面,感觉挺好! public static void main(String[] args) { try { UIManager .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Throwable e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { ArrayBound frame = new ArrayBound(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } // 原始的界面,有点丑~~ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // ArrayBound frame = new ArrayBound(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public ArrayBound() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 337, 285); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textArea = new JTextArea(); textArea.setLineWrap(true); textArea.setBounds(10, 83, 298, 156); contentPane.add(textArea); // 记得使用NumberFormat.getIntegerInstance()方法获取整数格式的对象 codeField = new JFormattedTextField(NumberFormat.getIntegerInstance()); codeField.setBounds(77, 52, 121, 21); contentPane.add(codeField); JButton btnNewButton = new JButton("\u786E\u5B9A"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_btnNewButton_actionPerformed(e); } }); btnNewButton.setBounds(208, 50, 93, 23); contentPane.add(btnNewButton); JLabel lblNewLabel = new JLabel("\u805A\u4F1A\u8DA3\u5473\u9898\uFF1A\u9009\u62E9 0-5 \u7F16\u53F7\u7684\u9898\u76EE"); lblNewLabel.setBounds(10, 21, 330, 15); contentPane.add(lblNewLabel); JLabel label = new JLabel("\u9898\u76EE\u7F16\u53F7\uFF1A"); label.setBounds(10, 54, 69, 15); contentPane.add(label); } private String[] infos = {"50元奖金", "唱一首歌", "学狗叫", "为大家讲一个笑话", "3万元奖金"}; protected void do_btnNewButton_actionPerformed(ActionEvent e) { int index = ((Number) codeField.getValue()).intValue(); try { textArea.setText(infos[index]); } catch (Exception e2) { textArea.setText("发生异常:\n" + e2.toString()); } } }
true
0e6f092dd532fa501d23b3b6a9ad4dacbfd588ce
Java
staverm/Java-Course-FER-2020
/hw14/src/main/java/hr/fer/zemris/java/p12/servlets/GlasanjeXlsServlet.java
UTF-8
3,048
2.765625
3
[]
no_license
package hr.fer.zemris.java.p12.servlets; import java.io.IOException; import java.util.List; 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 org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import hr.fer.zemris.java.p12.dao.DAOProvider; import hr.fer.zemris.java.p12.model.Poll; /** * Servlet that generates and returns as response an excel file (.xlsx) with * poll voting results. <br> * <br> * If the request parameter 'pollID' is set (ie. not null) the voting results * for the poll with that id are fetched from the persistence subsystem. Otherwise the voting results are read from a session * parameter 'options' (expected to be a list of options). <br> * This way the user has the option to provide the options list explicitly(by * session parameter 'options') or just provide a request parameter 'pollID' and * let the servlet to fetch the options list from persistence subsystem. * * @author staver * */ @WebServlet("/servleti/glasanje-xls") public class GlasanjeXlsServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Fetches from persistence subsystem a list of options for a poll with id read * from request parameter 'pollID'. If that parameter is null retrieves this * list from session parameter 'options'. This list is then used to create an * excel file which is sent as response. */ @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try (HSSFWorkbook hwb = new HSSFWorkbook()) { List<Poll.Option> options = null; if (req.getParameter("pollID") != null) { Poll poll = DAOProvider.getDao().getPollById(Long.parseLong(req.getParameter("pollID"))); options = poll.getOptions(); } else if (req.getSession().getAttribute("options") != null && req.getSession().getAttribute("options") instanceof List) { options = (List<Poll.Option>) req.getSession().getAttribute("options"); // assume list of options } else { return; } HSSFSheet sheet = hwb.createSheet("Sheet 1"); HSSFRow rowhead = sheet.createRow((short) 0); rowhead.createCell((short) 0).setCellValue("Opcija"); rowhead.createCell((short) 1).setCellValue("Broj glasova"); for (Integer i = 0; i < options.size(); i++) { HSSFRow row = sheet.createRow(i + 1); row.createCell((short) 0).setCellValue(options.get(i).getOptionTitle()); row.createCell((short) 1).setCellValue(options.get(i).getVotesCount()); } resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); resp.setHeader("Content-Disposition", "attachment; filename=\"rezultati.xlsx\""); hwb.write(resp.getOutputStream()); } catch (Exception ex) { System.out.println(ex); } } }
true
fd41d7983f839f338c0e4fd109a21b7eee1e5813
Java
ReddaHawk/virtuallabsbe
/src/main/java/it/polito/ai/es2/utility/ViewMessage.java
UTF-8
226
1.84375
2
[]
no_license
package it.polito.ai.es2.utility; import lombok.*; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ViewMessage { private String title; private String message; private String borderColour; }
true
89dbaea740810723dbafa943d35e0b225db7fb25
Java
luoyiqi/leanote-android-client
/app/src/main/java/com/zncm/leanote/ft/NotebooksFt.java
UTF-8
15,105
1.742188
2
[]
no_license
package com.zncm.leanote.ft; import android.app.Activity; import android.content.DialogInterface; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.LinearLayout; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.Theme; import com.cocosw.bottomsheet.BottomSheet; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.zncm.leanote.MyApplication; import com.zncm.leanote.R; import com.zncm.leanote.adapter.NoteBookAdapter; import com.zncm.leanote.data.Key; import com.zncm.leanote.data.Msg; import com.zncm.leanote.data.Note; import com.zncm.leanote.data.Notebooks; import com.zncm.leanote.services.NoteService; import com.zncm.leanote.services.NotebooksService; import com.zncm.leanote.services.ServiceFactory; import com.zncm.leanote.ui.MyAc; import com.zncm.leanote.ui.NoteBookAc; import com.zncm.leanote.utils.MySp; import com.zncm.leanote.utils.XUtil; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class NotebooksFt extends BaseListFt { private NoteBookAdapter mAdapter; private Activity ctx; private List<Notebooks> datas = null; private boolean onLoading = false; private boolean canEditable = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); ctx = (Activity) getActivity(); canEditable = ctx.getIntent().getBooleanExtra(Key.KEY_PARAM_BOOLEAN, false); emptyText.setText("日记本..."); addButton.setVisibility(View.GONE); datas = new ArrayList<Notebooks>(); mAdapter = new NoteBookAdapter(ctx) { @Override public void setData(final int position, MyViewHolder holder) { final Notebooks data = datas.get(position); if (XUtil.notEmptyOrNull(data.Title)) { holder.tvTitle.setVisibility(View.VISIBLE); holder.tvTitle.setText(data.Title + "(" + data.NumberNotes + ")"); } else { holder.tvTitle.setVisibility(View.GONE); } } }; listView.setAdapter(mAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @SuppressWarnings({"rawtypes", "unchecked"}) @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int curPosition = position - listView.getHeaderViewsCount(); Notebooks data = datas.get(curPosition); if (data == null) { return; } if (ctx instanceof MyAc) { MyAc tmp = (MyAc) ctx; tmp.curBook = data; tmp.bookChange(); } } } ); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) { if (canEditable) { bottomShow(position); } return true; } }); getData(false); return view; } private void bottomShow(final int position) { final Notebooks data = datas.get(position); new BottomSheet.Builder(ctx).title(data.Title).sheet(R.menu.bottom_notebook).listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case R.id.edit: initEtDlg(position, data); break; case R.id.delete: int numbernotes = data.NumberNotes; new MaterialDialog.Builder(ctx) .title("删除笔记本!") .content("笔记本下含有" + numbernotes + "篇笔记,确认删除?") .theme(Theme.LIGHT) .positiveText("删除") .negativeText("取消") .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); delNoteBook(data); dialog.dismiss(); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); } }) .show(); break; case R.id.set_default: MySp.setDefaultNoteBook(data.toString()); if (ctx instanceof NoteBookAc) { NoteBookAc tmp = (NoteBookAc) ctx; tmp.initTitle(); } break; } } }).show(); } void initEtDlg(final int pos, final Notebooks data) { LinearLayout view = new LinearLayout(ctx); view.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); final EditText editText = new EditText(ctx); XUtil.autoKeyBoardShow(editText); editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); editText.setLines(5); editText.setHint("输入..."); editText.setTextColor(getResources().getColor(R.color.black)); editText.setText(data.Title); editText.setSelection(data.Title.length()); editText.setBackgroundDrawable(new BitmapDrawable()); view.addView(editText); MaterialDialog md = new MaterialDialog.Builder(ctx) .customView(view) .positiveText("修改") .positiveColor(getResources().getColor(R.color.positive_color)) .negativeText("取消") .negativeColor(getResources().getColor(R.color.negative_color)) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); final String content = editText.getText().toString().trim(); if (!XUtil.notEmptyOrNull(content)) { XUtil.tShort("输入内容~"); XUtil.dismissShowDialog(dialog, false); return; } ServiceFactory.getService(NotebooksService.class).updateNotebook(MyApplication.getInstance().user.Token, data.NotebookId, content, null, data.Seq, data.Usn, new Callback<Msg>() { @Override public void success(Msg msg, Response response) { XUtil.tShort("修改笔记本:" + msg.ret(msg)); // if (msg.Ok) { data.Title = content; datas.set(pos, data); mAdapter.setItems(datas); // } } @Override public void failure(RetrofitError error) { } }); dialog.dismiss(); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); } }) .autoDismiss(false) .build(); md.setCancelable(false); md.show(); } public void initAddEtDlg() { LinearLayout view = new LinearLayout(ctx); view.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); final EditText editText = new EditText(ctx); XUtil.autoKeyBoardShow(editText); editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); editText.setLines(5); editText.setHint("笔记本名称"); editText.setTextColor(getResources().getColor(R.color.black)); editText.setBackgroundDrawable(new BitmapDrawable()); view.addView(editText); MaterialDialog md = new MaterialDialog.Builder(ctx) .customView(view) .positiveText("添加") .positiveColor(getResources().getColor(R.color.positive_color)) .negativeText("取消") .negativeColor(getResources().getColor(R.color.negative_color)) .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(final MaterialDialog dialog) { super.onPositive(dialog); String content = editText.getText().toString().trim(); if (!XUtil.notEmptyOrNull(content)) { XUtil.tShort("输入笔记本名称~"); XUtil.dismissShowDialog(dialog, false); return; } ServiceFactory.getService(NotebooksService.class).addNotebook(MyApplication.getInstance().user.Token, content, null, 0, new Callback<Msg>() { @Override public void success(Msg msg, Response response) { XUtil.tShort("添加笔记本:" + msg.ret(msg)); refresh(); } @Override public void failure(RetrofitError error) { } }); dialog.dismiss(); } @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); dialog.dismiss(); } }) .autoDismiss(false) .build(); md.setCancelable(false); md.show(); } private void delNoteBook(final Notebooks data) { ServiceFactory.getService(NotebooksService.class).deleteNotebook(MyApplication.getInstance().user.Token, data.NotebookId, data.Usn, new Callback<Msg>() { @Override public void success(Msg msg, Response response) { XUtil.tShort("删除笔记本:" + msg.ret(msg)); if (msg.Ok) { datas.remove(data); mAdapter.setItems(datas); } } @Override public void failure(RetrofitError error) { } }); } private void getData(boolean bSync) { try { //MyApplication.getInstance().user.Token //55015ea938f41165dd000110 datas = new ArrayList<>(); if (!bSync) { if (XUtil.notEmptyOrNull(MySp.getFullNoteBook())) { datas = new Gson().fromJson(MySp.getFullNoteBook(), new TypeToken<List<Notebooks>>() { }.getType()); } if (XUtil.listNotNull(datas)) { MyApplication.getInstance().fullNotebookses = datas; initView(); return; } } ServiceFactory.getService(NotebooksService.class).getNotebooks(MyApplication.getInstance().user.Token, new Callback<List<Notebooks>>() { @Override public void success(List<Notebooks> notebooks, Response response) { if (XUtil.listNotNull(notebooks)) { datas.addAll(notebooks); MyApplication.getInstance().fullNotebookses = datas; MySp.setFullNoteBook(notebooks.toString()); if (!XUtil.notEmptyOrNull(MySp.getDefaultNoteBook())) { MySp.setDefaultNoteBook(datas.get(datas.size() - 1).toString()); } } initView(); } @Override public void failure(RetrofitError error) { XUtil.debug("error:" + error); } }); } catch (Exception e) { e.printStackTrace(); } } private void initView() { mAdapter.setItems(datas); swipeLayout.setRefreshing(false); onLoading = false; listView.setCanLoadMore(false); listView.onLoadMoreComplete(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { } @Override public void onRefresh() { if (onLoading) { return; } refresh(); } private void refresh() { onLoading = true; swipeLayout.setRefreshing(true); getData(true); } @Override public void onLoadMore() { getData(false); } }
true
df404f1115c64bd29abfd7e6b74968f54e272834
Java
OnlixProg779/Aplicacion-admin-Almacen-de-Ropa-App-ShopClothes-
/src/vistaCuentas/JInternalFrameCuentasCheques.java
UTF-8
637
2.15625
2
[]
no_license
package vistaCuentas; import java.awt.EventQueue; import javax.swing.JInternalFrame; import controladorVistaCuentas.ControladorVentanaCuentasCheques; import javax.swing.JPanel; import java.awt.BorderLayout; public class JInternalFrameCuentasCheques extends JInternalFrame { private PanelCheques panel; public PanelCheques getPanel() { return panel; } public JInternalFrameCuentasCheques(ControladorVentanaCuentasCheques controlador) { setBounds(100, 100, 604, 413); setTitle("CHEQUES"); panel = new PanelCheques(); getContentPane().add(panel, BorderLayout.CENTER); panel.setControlador(controlador); } }
true
b58e14066d19b2c71572f6fbf9c1f7c0f2c98847
Java
bryaneibon/Budget-Manager
/src/Budget_Manager/stage1/BudgetManager.java
UTF-8
1,856
3.53125
4
[]
no_license
package Budget_Manager.stage1; /** * In this Project, we'll use the Strategy Design Pattern because it will be * easier to add new features for the next steps, without having to change completely the logic. * * Description - Stage 1: * First, let’s implement the counting of your purchases. * It’s much easier to analyze when your expenses are presented as a list. * Read data from the console and at the end show the list of all purchases and its total amount. * * It should be displayed as follows: Total: $23.00 * * Your program should process every line the user inputs. * To end the input, the user should type End-of-file symbol that tells * your operating system that no more input will be provided. * It's Ctrl+D on Linux and Mac and Ctrl+Z on Windows. * * Input: * Almond 250gm $35.43 * LEGO DUPLO Town Farm Animals $10.10 * Sensodyne Pronamel Toothpaste $19.74 * Hershey's milk chocolate bars $8.54 * Gildan LT $8.61 * * Output: * Almond 250gm $35.43 * LEGO DUPLO Town Farm Animals $10.10 * Sensodyne Pronamel Toothpaste $19.74 * Hershey's milk chocolate bars $8.54 * Gildan LT $8.61 * * Total: $82.42 */ public interface BudgetManager { void totalSpent(); } class BudgetManagerContext { private BudgetManager budgetManager; void setBudgetManager (BudgetManager budgetManager){ this.budgetManager = budgetManager; } void totalSpent(){ this.budgetManager.totalSpent(); } } class Main { public static void main(String[] args) { BudgetManagerContext myBudgetManager = new BudgetManagerContext(); // set the method that will be used for the budget management... myBudgetManager.setBudgetManager(new Budget_Manager.stage1.TotalSpent()); myBudgetManager.totalSpent(); } }
true
43e110d07b79743a2be2ed8206232cf695b3d65e
Java
cxy1686901657/JavaDesignMode
/Principle/src/com/qc/principle/singleresponsibility/SingleResponsibility1.java
UTF-8
760
3.78125
4
[]
no_license
package com.qc.principle.singleresponsibility; /** * @author qc * @date 2019/8/8 * @description 单一职责 * @model 设计原则 * @project JavaDesignMode */ public class SingleResponsibility1 { public static void main(String[] args) { // TODO Auto-generated method stub Vehicle vehicle = new Vehicle(); vehicle.run("摩托车"); vehicle.run("汽车"); vehicle.run("飞机"); } } // 交通工具类 // 方式1 // 1. 在方式1 的run方法中,违反了单一职责原则 // 2. 解决的方案非常的简单,根据交通工具运行方法不同,分解成不同类即可 class Vehicle { public void run(String vehicle) { System.out.println(vehicle + " 在公路上运行...."); } }
true
43dd0e9abdc443bfd3740ce55b96388017ffe5c9
Java
Niyathi3011/MovieRating
/app/src/main/java/movierating/repositories/MovieRepository.java
UTF-8
571
2.578125
3
[]
no_license
package movierating.repositories; import movierating.models.Movie; import movierating.models.User; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MovieRepository { private Map<String, Movie> movies; public MovieRepository() { this.movies = new HashMap<>(); } public Map<String, Movie> getMovies() { return movies; } @Override public String toString() { return "MovieRepository{" + "movies=" + movies + '}'; } }
true
38033c6da8eacd5b970ac2413bc26a1e9459f473
Java
AAccqiang/order-16-12-31
/app/src/main/java/com/example/administrator/orderapp/adapter/SuheduleAdapter.java
UTF-8
4,785
1.960938
2
[]
no_license
package com.example.administrator.orderapp.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.TextView; import com.example.administrator.orderapp.R; import com.example.administrator.orderapp.activity.OrderScheduleDetailActivity; import com.example.administrator.orderapp.entry.Order; import com.example.administrator.orderapp.util.SharedPreferUtil; import org.w3c.dom.Text; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.ButterKnife; /** * Created by Administrator on 2017/1/4 0004. */ public class SuheduleAdapter extends BaseExpandableListAdapter { private List<String> groupList; private List<List<Order>> childredList; private Context context; private LayoutInflater mLayoutInflater; public SuheduleAdapter(Context context,List<String> groupList,List<List<Order>> childredList) { this.context = context; this.groupList = groupList; this.childredList = childredList; mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void clearList(){ groupList.clear(); notifyDataSetChanged(); } private void removeList(int i){ groupList.remove(i); notifyDataSetChanged(); } @Override public int getGroupCount() { return groupList.size(); } @Override public int getChildrenCount(int i) { return 1; } @Override public Object getGroup(int i) { return groupList.get(i); } @Override public Object getChild(int i, int i1) { return childredList.get(i).get(i1); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) { view = mLayoutInflater.inflate(R.layout.layout_suhedule,null); TextView tvOrderId = (TextView) view.findViewById(R.id.tv_orderId); tvOrderId.setText(groupList.get(i)); String name = SharedPreferUtil.getName(context); TextView tvName = (TextView) view.findViewById(R.id.tv_name); tvName.setText(name); //设置订单的日期 String data = groupList.get(i); String dataStr = data.substring(0,4)+ "-"; dataStr = dataStr + data.substring(4,6) + "-"; dataStr += data.substring(6,8); TextView tvDate = (TextView) view.findViewById(R.id.tv_date); tvDate.setText(dataStr); //设置桌号 String tableNum = data.substring(12,15); TextView tvTable = (TextView) view.findViewById(R.id.tv_tableNum); tvTable.setText(tableNum); Button btnQuery = (Button) view.findViewById(R.id.btn_query); btnQuery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, OrderScheduleDetailActivity.class); intent.putExtra("thisOrderId",groupList.get(i)); Log.e("thisOrderId",groupList.get(i)); context.startActivity(intent); } }); return view; } @Override public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) { view = mLayoutInflater.inflate(R.layout.layout_suhedule_item,null); TextView tvPeople = (TextView) view.findViewById(R.id.tv_PeopleNum); TextView tvMenuNum = (TextView) view.findViewById(R.id.tv_menuNum); TextView tvMenuPlay = (TextView) view.findViewById(R.id.tv_menu_pay); List<Order> orders = childredList.get(0); for(Order order : orders){ if(groupList.get(i).equals(order.getOrderId())){ tvPeople.setText("客人共:"+order.getVisitorNum()+"人"); tvMenuNum.setText("菜单共:" + order.getMenuNum() +"份 (计算了已加份的)"); tvMenuPlay.setText("总价格:"+order.getPayNum()+"元"); } } return view; } @Override public boolean isChildSelectable(int i, int i1) { return false; } }
true
b9c8720a8899514a804f3a9ffd2256febb047ba6
Java
hibacha/Parking
/src/main/java/com/nash/app/XpathAxis.java
UTF-8
976
2.109375
2
[]
no_license
package com.nash.app; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; public class XpathAxis { Logger logger = LoggerFactory.getLogger(XpathAxis.class); @Test public void testXpath(){ WebDriver driver=new ChromeDriver(); driver.get("http://localhost:8080/wodegrid/xpath.html"); List<WebElement> elements = driver.findElements(By.cssSelector("tr:nth-child(1)")); List<WebElement> eles = driver.findElements(By.xpath("(//tr)[2]/preceding::tr")); logger.info("size:"+eles.size()); for(WebElement element:eles){ String tagStr="<"+element.getTagName()+">"+element.getText()+"</"+element.getTagName()+">"; logger.info(tagStr); } driver.quit(); } }
true
6cddff5dcdaff7690f7f6174c1565d185d0a8244
Java
hieugomeister/ASU
/CST200/Deliverables/WEEK2/Greggy2.java
UTF-8
2,657
4.0625
4
[]
no_license
import java.util.Scanner; //Needed this class for input public class Greggy2 { //------------------------------------------------------ //Design and implement an application that reads an integer //value representing a year from the user. The purpose of //the program is to determine if the year is a leap year //(and therefore has 29 days in February) in the Gregorian //calendar. A year is a leap year if it is divisible by 4, //unless it is also divisible by 100 but not 400. For example, //the year 2003 is not a leap year, but 2004 is. The year 1900 //is not a leap year because it is divisible by 100, but the //year 2000 is a leap year because even though it is divisible //by 100, it is also divisible by 400. Produce an error message //for any input value less than 1582 (the year the Gregorian //calendar was adopted). Allows multiple entries. // //------------------------------------------------------ public static void main(String[] args) { final int GREGORIAN_YEAR = 1582; // Constant to compare to int x1=0,x2=0; boolean isLeapyear = false; //variables for calculating distance of 2 points Scanner scan = new Scanner(System.in);//Keyboard input System.out.println("Enter the year in question (must be greater than or equal to 1582)"); System.out.print("Enter 9999 to quit: "); while((x1 = scan.nextInt()) != 9999) { while(x1 < GREGORIAN_YEAR) { System.out.println("Error, the year must be greater than or equal to 1582"); System.out.println("Enter the year in question (must be greater than or equal to 1582)"); System.out.print("Enter 9999 to quit: "); x1 = scan.nextInt(); if(x1 == 9999) { System.out.println("Good bye!!!"); System.exit(0); //Break out of the loop } } if ((x1 % 4) == 0) //First test, fail this then game is over { //Check for other conditions //Must be either passing both 100 and 400 check //or failing both 100 and 400 check in order to be //a leap year if((((x1 % 100) == 0) && ((x1 % 400) == 0)) || (((x1 % 100) != 0) && ((x1 % 400) != 0))) { isLeapyear = true; } else { isLeapyear = false; } } else //Clearly not a leap year { isLeapyear = false; } if(isLeapyear) //Display meassage based on isLeapyear logic System.out.println("The year " + x1 + " is a leap year."); else System.out.println("The year " + x1 + " is not a leap year."); System.out.println("Enter the year in question (must be greater than or equal to 1582)"); System.out.print("Enter 9999 to quit: "); } System.out.println("Good bye!!!"); } }
true
75cab6c3e1c102eaf7cc50a99902a3eadc4dd4be
Java
taquocthao/clothes-store-management
/src/main/java/com/tathao/shop/utils/Constant.java
UTF-8
1,674
1.804688
2
[]
no_license
package com.tathao.shop.utils; public class Constant { public static class Path { public static final String PATH_MAN = "/nam"; public static final String PATH_WOMEN = "/nu"; public static final String PATH_TSHIRT = "/ao-thun"; public static final String PATH_SHIRT = "/ao-so-mi"; public static final String PATH_JEANS = "/quan-jeans"; public static final String PATH_COAT = "/ao-khoac"; } public static class Data { public static final String HOSTNAME = "localhost"; public static final String USERNAME = "root"; public static final String PASSWORD = ""; public static final String DATABASE_NAME = "clothes_shop_management"; } public static class Number { public static final int ZERO = 0; public static final int LIMIT_RECORD = 12; public static final int CATEGORY_MAN_TSHIRT_ID = 1; public static final int CATEGORY_MAN_SHIRT_ID = 2; public static final int CATEGORY_MAN_COAT_ID = 3; public static final int CATEGORY_MAN_JEANS_ID = 4; public static final int CATEGORY_MAN_SHORTS_ID = 5; public static final int CATEGORY_MAN_PANTS_ID = 6; public static final int CATEGORY_MAN_SHOES_ID = 7; public static final int CATEGORY_MAN_THONGS_ID = 8; public static final int CATEGORY_WOMAN_TSHIRT_ID = 9; public static final int CATEGORY_WOMAN_SHIRT_ID = 10; public static final int CATEGORY_WOMAN_COAT_ID = 11; public static final int CATEGORY_WOMAN_JEANS_ID = 12; public static final int CATEGORY_WOMAN_SHOES_ID = 13; public static final int CATEGORY_WOMAN_THONGS_ID = 14; public static final int CATEGORY_WOMAN_SKIRT_ID = 15; public static final int CATEGORY_WOMAN_DRESS_ID = 16; } }
true
f3481ac4dced0938cb785c3f669b8423108d68cd
Java
elyselturner/BROILR-Week-One
/app/src/main/java/com/example/broilr/MainActivity.java
UTF-8
2,446
2.421875
2
[]
no_license
package com.example.broilr; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.Stack; public class MainActivity extends Activity { Button mLikeButton; Button mDislikeButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLikeButton = (Button) findViewById(R.id.like_button); mDislikeButton = (Button) findViewById(R.id.dislike_button); mDislikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast dislikeToast = Toast.makeText(MainActivity.this, R.string.dislike_toast, Toast.LENGTH_SHORT); showCustomToast(dislikeToast); } }); mLikeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast likeToast = Toast.makeText(MainActivity.this, R.string.like_toast, Toast.LENGTH_SHORT); showCustomToast(likeToast); } }); // Add in food profile fragment somehow // } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void showCustomToast(Toast toast) { toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 500); LinearLayout toastLayout = (LinearLayout) toast.getView(); TextView toastTV = (TextView) toastLayout.getChildAt(0); toastTV.setTextSize(30); toast.show(); } }
true
24a10b06955e7dadf2eeb99da16238a4789e2ffe
Java
GiovaniGuizzo/HITO
/src/hyperheuristics/statistics/EffectSize.java
UTF-8
4,132
2.890625
3
[]
no_license
package hyperheuristics.statistics; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Scanner; public class EffectSize { public static final String NEGLIGIBLE = "negligible"; public static final String SMALL = "small"; public static final String MEDIUM = "medium"; public static final String LARGE = "large"; public static HashMap<String, HashMap<String, Double>> computeEffectSize(HashMap<String, double[]> values) throws IOException, InterruptedException { HashMap<String, HashMap<String, Double>> result = new HashMap<>(); StringBuilder script = new StringBuilder(); script.append("require(\"effsize\")\n"); for (Map.Entry<String, double[]> entrySet : values.entrySet()) { String group = entrySet.getKey(); double[] groupValues = entrySet.getValue(); script.append(group).append(" <- c("); for (double value : groupValues) { script.append(value).append(","); } script.deleteCharAt(script.length() - 1).append(")\n"); } String[] groupArray = (String[]) values.keySet().toArray(new String[0]); for (int i = 0; i < groupArray.length - 1; i++) { String groupA = groupArray[i]; for (int j = i + 1; j < groupArray.length; j++) { String groupB = groupArray[j]; script.append("VD.A(").append(groupA).append(",").append(groupB).append(")\n"); } } script.append("q()"); File inputFile = File.createTempFile("script", ".R"); File outputFile = File.createTempFile("output", ".R"); inputFile.deleteOnExit(); outputFile.deleteOnExit(); new FileWriter(inputFile).append(script).flush(); ProcessBuilder builder = new ProcessBuilder(); builder.command(System.getProperty("os.name").contains("win") ? "R.exe" : "R", "--slave", "-f", inputFile.getAbsolutePath()); builder.redirectOutput(outputFile); builder.start().waitFor(); Scanner scanner = new Scanner(outputFile); List<Double> comparisonValues = new ArrayList<>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("A estimate:")) { String[] split = line.split(" "); Double doubleValue = Double.parseDouble(split[2]); if (doubleValue.isNaN()) { doubleValue = 0.0; } comparisonValues.add(doubleValue); } } Iterator<Double> iterator = comparisonValues.iterator(); for (int i = 0; i < groupArray.length - 1; i++) { String groupA = groupArray[i]; for (int j = i + 1; j < groupArray.length; j++) { String groupB = groupArray[j]; HashMap<String, Double> groupAMap = result.get(groupA); if (groupAMap == null) { groupAMap = new HashMap<>(); result.put(groupA, groupAMap); } HashMap<String, Double> groupBMap = result.get(groupB); if (groupBMap == null) { groupBMap = new HashMap<>(); result.put(groupB, groupBMap); } Double value = iterator.next(); groupAMap.put(groupB, value); groupBMap.put(groupA, 1 - value); } } inputFile.delete(); outputFile.delete(); return result; } public static String interpretEffectSize(double effectSize) { effectSize = StrictMath.abs(effectSize - 0.5) * 2; if (effectSize < 0.147) { return NEGLIGIBLE; } else if (effectSize < 0.33) { return SMALL; } else if (effectSize < 0.474) { return MEDIUM; } else { return LARGE; } } }
true
7a035f27d9ba9cab6b00f84fcb3b85baf75a3c49
Java
c-peckham/school
/Java/Java_Exercise_O1.java
UTF-8
1,487
4.1875
4
[]
no_license
//Demo class for Exercise O1 class Demo { private double val1; // the first data member private double val2; // the second data member public void setValues(double num1, double num2) { val1 = num1; val2 = num2; } public double getValue1(void) { return (val1); } public double getValue2(void) { return (val2); } public double getAverage(void) { return( (valu1 + valu2) / 2); } } // Use methods defined in Demo, to use number manipulation functions import java.util.Scanner; public class ExerciseO1 { static Demo addDemo(Demo item1, Demo item2) { Demo Sum = new Demo(); Sum.setValues(item1.getValue1() + item2.getValue2(), item1.getValue1() + item2.getValue2()); return Sum; } static void incrDemo2(Demo item) { item.setValues(item.getValue1() + 5, item.getValue2() + 5); } public static void main(String args[]) { Demo demo = new Demo(); Scanner input = new Scanner(System.in); System.out.println("Enter val1"); double num1 = input.nextDouble(); System.out.println("Enter val2"); double num2 = input.nextDouble(); demo.setValues(num1, num2); System.out.println("Average = " + demo.getAverage()); Demo obj1 = new Demo(); obj1.setValues(5, 7); Demo obj2 = new Demo(); obj2.setValues(14, 9); Demo objR = addDemo(obj1,obj2); incrDemo2(obj1); System.out.println("objR = " + objR.getValue1() + objR.getValue2()); System.out.println("obj1 = " + obj1.getValue1() + obj1.getValue2()); } }
true