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
c3a00a6313625984e823f2049dbc232febb8fb17
Java
foozy74/sony-WorkflowGs
/serializers/src/main/java/com/gs/photos/genavro/GenerateAvroSchema.java
UTF-8
2,562
2.203125
2
[]
no_license
package com.gs.photos.genavro; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.reflect.ReflectData; import com.fasterxml.jackson.databind.JsonMappingException; import com.google.common.reflect.ClassPath; public class GenerateAvroSchema { public static void main(String[] args) { final ClassLoader loader = Thread.currentThread() .getContextClassLoader(); try { List<Schema> schemas = new ArrayList<>(); for (final ClassPath.ClassInfo info : ClassPath.from(loader) .getTopLevelClasses()) { if (info.getName() .startsWith("com.workflow.model.events") || info.getName() .startsWith("com.workflow.model.Hbase") || info.getName() .startsWith("com.workflow.model.files") || info.getName() .startsWith("com.workflow.model.Exchange") || info.getName() .startsWith("com.workflow.model.Collection") || info.getName() .startsWith("com.workflow.model.storm")) { final Class<?> clazz = info.load(); if (!clazz.isInterface()) { try { System.out.println("... adding " + clazz + " to avro schema"); Schema schema = ReflectData.get() .getSchema(clazz); schemas.add(schema); } catch (Exception e) { e.printStackTrace(); } } } } Schema schema = Schema.createUnion(schemas); String asJson = schema.toString(true); File f = new File("src/main/resources/gs-avro-schema.avsc"); System.out.println("......... Dumping schema in " + f.getAbsolutePath()); DataOutputStream dos = new DataOutputStream(new FileOutputStream(f)); dos.write(asJson.getBytes(Charset.forName("ISO-8859-1"))); dos.close(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
true
086e835178043d3bbb9745bb9c3725c4ce06636c
Java
marcosvscampos/quarkus-microservice-test
/src/test/java/com/freitas/microservice_products/util/Tests.java
UTF-8
274
1.523438
2
[]
no_license
package com.freitas.microservice_products.util; public class Tests { public static final String UNIT = "unit"; public static final String SERVICE = "service"; public static final String CONTRACT = "contract"; public static final String INTEGRATION = "integration"; }
true
5d52377aab1e9c818a57848e8a7c9d5b89025f24
Java
adityagupta1089/Codeforces-Solutions
/solved/P1245B.java
UTF-8
1,757
3.328125
3
[]
no_license
import java.util.Scanner; public class P1245B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int a = in.nextInt(); //R int b = in.nextInt(); //P int c = in.nextInt(); //S in.nextLine(); String s = in.nextLine(); int w = 0; char[] ans = new char[s.length()]; int i = 0; for (char ch : s.toCharArray()) { if (ch == 'R' && b > 0) { ans[i] = 'P'; b--; w++; } if (ch == 'P' && c > 0) { ans[i] = 'S'; c--; w++; } if (ch == 'S' && a > 0) { ans[i] = 'R'; a--; w++; } i++; } if (w >= Math.round(n / 2.0)) { System.out.println("YES"); for (char ch : ans) { if (ch == 'P' || ch == 'S' || ch == 'R') { System.out.print(ch); } else if (a > 0) { a--; System.out.print('R'); } else if (b > 0) { b--; System.out.print('P'); } else { c--; System.out.print('S'); } } System.out.println(); } else { System.out.println("NO"); } } } }
true
7f67bde5be30c424123100cbbb3cfdc6f3acf059
Java
cookieci/NDKStudy
/app4/src/main/java/com/xcc/app4/MyJniThread2.java
UTF-8
374
1.796875
2
[]
no_license
package com.xcc.app4; /** * Created by Administrator on 2017/4/24. */ //javah -d jni -classpath E:\AndroidStudioWork\NDKStudy\app4\build\intermediates\classes\debug com.xcc.app4.MyJniThread2 public class MyJniThread2 { static { System.loadLibrary("myThread"); } public native static void startThread(); public native static void startThread2(); }
true
6871a0eeae9d50260b6538e98ba0c7e5819b0899
Java
kaurpushpinder/water-order-app
/src/main/java/com/rubiconwater/app/ui/service/BookingService.java
UTF-8
813
2.375
2
[]
no_license
package com.rubiconwater.app.ui.service; import java.time.LocalDateTime; import java.util.List; import com.rubiconwater.app.ui.model.OrderDto; public interface BookingService { /** * create new order with given order details, * condition that requested time does not overlap existing orders * @param orderDetails * @return */ OrderDto createBooking(OrderDto order); /** * Get all orders based on request parameters * @param farmerId * @param date * @return */ List<OrderDto> getOrders(String farmerId, LocalDateTime date); /** * Cancel an existing order, * condition that Order is not yet started * @param orderId * @return */ void cancelOrder(String orderId); /** * get orders by id * @param orderId * @return */ OrderDto getOrderById(String orderId); }
true
4649585bba312bcd6a902ff2988739121b4d6625
Java
makyo-old/possibility-partial
/java/POSsibility/src/main/java/com/mjs_svc/possibility/models/Group.java
UTF-8
767
2.390625
2
[]
no_license
package com.mjs_svc.possibility.models; import java.util.*; /** * * @author Matthew */ public class Group { private int id; private String name; private Set permissions = new HashSet(), users = new HashSet(); public Set getUsers() { return users; } public void setUsers(Set users) { this.users = users; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getPermissions() { return permissions; } public void setPermissions(Set permissions) { this.permissions = permissions; } }
true
edff534e7d9002bc82d3e47ddc0c7509826f117f
Java
qiulingyun/Leetcode
/Leetcode/src/main/java/QLY/Leetcode/list/SortList.java
UTF-8
1,167
3.765625
4
[]
no_license
package QLY.Leetcode.list; import java.util.ArrayList; import java.util.Arrays; /** * https://leetcode-cn.com/problems/sort-list/ * 148. 排序链表 * 给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。 */ public class SortList { private static final class Pair{ public ListNode ref; public int value; public Pair(ListNode ref, int value) { this.ref = ref; this.value = value; } } public ListNode sortList(ListNode head) { if (head == null || head.next == null) return head; ArrayList<Pair> list = new ArrayList<>(); for (ListNode node = head; node != null; node = node.next){ list.add(new Pair(node, node.val)); } Pair[] pairs = list.toArray(new Pair[list.size()]); Arrays.sort(pairs, (l, r)-> l.value - r.value); ListNode newHead = pairs[0].ref; ListNode tail = newHead; for (int i = 1; i < pairs.length; i++) { tail.next = pairs[i].ref; tail = pairs[i].ref; } tail.next = null; return newHead; } }
true
83be724f5209d4bd3abc25db2554f1b103065ba9
Java
OmerHavakook/ArknoidOOP
/ass5/src/sprites/Background.java
UTF-8
5,062
3.21875
3
[]
no_license
package sprites; import java.awt.Color; import biuoop.DrawSurface; import gamefiles.GameLevel; /** * A Background class. * * @author Omer Havakook <darhavakook@gmail.com> */ public class Background implements Sprite { private int levelNum; int checker = 0; int x = 30, y = 30; /** * Basic Constructor. */ public Background(int ln) { this.levelNum = ln; } /** * draw this on give drawsurface. * * @param d * the drawsurface to draw on. */ @Override public void drawOn(DrawSurface d) { if (this.levelNum == 1) { this.draw1(d); } else if (this.levelNum == 2) { this.draw2(d); } else if (this.levelNum == 3) { this.draw3(d); } else { this.draw4(d); } } /** * notify this obj that timepass. * * @param dt * the speed change dt. */ @Override public void timePassed() { if (this.levelNum == 1) { this.checker += 1; } return; } /** * draw level 1. * * @param d * the draw surface. */ public void draw1(DrawSurface d) { d.setColor(Color.BLACK); d.fillRectangle((int) 0, (int) 0, (int) GameLevel.WIDTH, (int) GameLevel.HEIGHT); d.setColor(Color.BLUE); d.drawCircle(GameLevel.WIDTH / 2, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30), 40); d.drawCircle(GameLevel.WIDTH / 2, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30), 60); d.drawCircle(GameLevel.WIDTH / 2, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30), 80); d.drawCircle(GameLevel.WIDTH / 2, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30), 100); d.drawLine(GameLevel.WIDTH / 2 - 120, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30), GameLevel.WIDTH / 2 + 120, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30)); d.drawLine(GameLevel.WIDTH / 2, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30) - 120, GameLevel.WIDTH / 2, (int) (GameLevel.HEIGHT * 0.3 + GameLevel.HEIGHT / 30) + 120); } /** * draw level 2. * * @param d * the draw surface. */ public void draw2(DrawSurface d) { d.setColor(new Color(255, 255, 153)); for (int i = 0; i < 90; i++) { d.drawLine((int) (GameLevel.WIDTH * 0.2), (int) (0.2 * GameLevel.HEIGHT), GameLevel.WIDTH * 6 / 7 - i * 10, (int) (0.4 * GameLevel.HEIGHT)); } d.setColor(new Color(255, 178, 172)); d.fillCircle((int) (0.2 * GameLevel.WIDTH), (int) (0.2 * GameLevel.HEIGHT), 70); d.setColor(new Color(255, 255, 102)); d.fillCircle((int) (0.2 * GameLevel.WIDTH), (int) (0.2 * GameLevel.HEIGHT), 60); d.setColor(new Color(255, 255, 153)); d.fillCircle((int) (0.2 * GameLevel.WIDTH), (int) (0.2 * GameLevel.HEIGHT), 50); } /** * draw level 3. * * @param d * the draw surface. */ public void draw3(DrawSurface d) { d.setColor(new Color(224, 224, 224)); d.fillRectangle((int) 0, (int) 0, (int) GameLevel.WIDTH, (int) GameLevel.HEIGHT); d.setColor(new Color(32, 32, 32)); d.fillRectangle(100, 430, 98, 170); d.setColor(new Color(224, 224, 224)); int x = 0; int y = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 5; j++) { d.fillRectangle(105 + x, 437 + y, 12, 22); x += 19; } x = 0; y += 30; } d.setColor(new Color(50, 50, 50)); d.fillRectangle(140, 390, 20, 40); d.setColor(new Color(70, 70, 70)); d.fillRectangle(145, 240, 10, 150); d.setColor(new Color(255, 255, 0)); d.fillCircle(150, 240, 10); d.setColor(Color.red); d.fillCircle(150, 240, 7); d.setColor(new Color(224, 224, 224)); d.fillCircle(150, 240, 3); } /** * draw level 4. * * @param d * the draw surface. */ public void draw4(DrawSurface d) { d.setColor(new Color(0, 128, 255)); d.fillRectangle((int) 0, (int) 0, (int) GameLevel.WIDTH, (int) GameLevel.HEIGHT); d.setColor(new Color(224, 224, 224)); d.fillCircle(95, 395, 22); d.fillCircle(115, 410, 24); d.fillCircle(550, 470, 20); d.fillCircle(570, 485, 22); int x = 0; for (int i = 0; i < 10; i++) { d.drawLine(550 + x, 470, 520 + x, 600); d.drawLine(95 + x, 395, 65 + x, 600); x += 9; } d.setColor(new Color(192, 192, 192)); d.fillCircle(125, 385, 25); d.fillCircle(580, 460, 25); d.setColor(new Color(160, 160, 160)); d.fillCircle(145, 410, 27); d.fillCircle(168, 390, 28); d.fillCircle(600, 485, 27); d.fillCircle(622, 465, 28); } }
true
5dd4b0aa4a0b0e6f2c6f295dcc6d2c6b4306b02b
Java
lordofall/algo
/src/com/pack/contest/Leet_195_01_TP.java
UTF-8
1,628
3.78125
4
[]
no_license
package com.pack.contest; import java.util.HashSet; import java.util.Set; /* *ACCEPTED Path crossing Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return True if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return False otherwise. Input: path = "NES" Output: false Explanation: Notice that the path doesn't cross any point more than once. Input: path = "NESWW" Output: true Explanation: Notice that the path visits the origin twice. 1 <= path.length <= 10^4 path will only consist of characters in {'N', 'S', 'E', 'W} */ public class Leet_195_01_TP { public static void main(String[] args) { Leet_195_01_TP o = new Leet_195_01_TP(); System.out.println(o.isPathCrossing("NESWW")); //t /*System.out.println(o.isPathCrossing("NES"));//f System.out.println(o.isPathCrossing("NEES"));//f System.out.println(o.isPathCrossing("NEESWN"));*/ } public boolean isPathCrossing(String path) { Set<String> visited = new HashSet<>(); int x = 0; int y = 0; visited.add(x+""+y); for(int i = 0; i < path.length(); i++) { if(path.charAt(i) == 'N') { y++; } else if(path.charAt(i) == 'S') { y--; } else if(path.charAt(i) == 'E') { x++; } else if(path.charAt(i) == 'W') { x--; } String currentPosition = x+""+y; if(visited.contains(currentPosition)) return true; visited.add(currentPosition); } return false; } }
true
8e56942d417c364a9a0022f03a25119d8f38dbe2
Java
ArneCools/Fill
/src/be/kdg/fill/view/game/GamePresenter.java
UTF-8
5,674
2.359375
2
[]
no_license
package be.kdg.fill.view.game; import be.kdg.fill.model.*; import be.kdg.fill.view.levelCompleted.LevelCompletedPresenter; import be.kdg.fill.view.levelCompleted.LevelCompletedView; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.Node; import javafx.scene.input.MouseDragEvent; import javafx.scene.input.MouseEvent; import javafx.stage.Modality; import javafx.stage.Stage; public class GamePresenter implements NavigationObject { private Game model; private GameView view; private boolean mouseDown = false; private final NavigationObject parent; public GamePresenter(Game model, GameView view, NavigationObject parent) { this.model = model; this.view = view; this.parent = parent; if (model.isCreateLevel()) { view.getBtnHint().setDisable(true); view.getBtnExit().setText("Back"); } addEventHandlers(); } private void addEventHandlers() { for (int i = 0; i < view.getBlocks().length; i++) { for (int j = 0; j < view.getBlocks()[0].length; j++) { int finalJ = j; int finalI = i; view.addEventFilter(MouseEvent.DRAG_DETECTED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { view.startFullDrag(); } }); view.getBlocks()[i][j].setOnMouseDragEntered(new EventHandler<MouseDragEvent>() { @Override public void handle(MouseDragEvent event) { model.handleDrag(finalI, finalJ); updateView(); if (model.checkIfWon()) gameWon(); } }); view.getBlocks()[i][j].setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { model.handleDrag(finalI, finalJ); updateView(); if (model.checkIfWon()) gameWon(); } }); } } view.getBtnHint().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (LevelData.getHintsAvailable() > 0) { LevelData.useHint(); model.showHint(); view.updateHints(); updateView(); } } }); view.getBtnExit().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { model.resetGrid(); returnWithTransition(); } }); view.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { view.updateScreen(); } }); view.heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { view.updateScreen(); } }); } public void updateView() { view.updateGrid(model.getGrid()); view.updatePath(model.getPath(), model.getHintPath()); view.updateScreen(); } @Override public void returnToPreviousScreen() { parent.backToThisScreen(view); } @Override public void backToThisScreen(Node node) { parent.backToThisScreen(node); } private void gameWon() { if (model.isCreateLevel()) { returnWithTransition(); return; } view.transition(false); view.getTransition().setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { endLevel(); } }); } private void endLevel() { model.getLevel().setCompleted(); LevelCompletedView levelCompletedView = new LevelCompletedView(); LevelModel levelModel = new LevelModel(model.getLevel().getDifficulty()); LevelCompletedPresenter levelCompletedPresenter = new LevelCompletedPresenter(levelCompletedView, levelModel, this); view.getScene().setRoot(levelCompletedView); } private void returnWithTransition() { view.transition(false); view.getTransition().setOnFinished(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { returnToPreviousScreen(); } }); } public void loadNextLevel(Node node) { if (model.getLevel().getLevelNumber() < LevelData.getLevels(model.getLevel().getDifficulty()).size()) { GameView gameView = new GameView(LevelData.getLevels(model.getLevel().getDifficulty()).get(model.getLevel().getLevelNumber()).getGrid()); Game game = new Game(LevelData.getLevels(model.getLevel().getDifficulty()).get(model.getLevel().getLevelNumber()), false); GamePresenter gamePresenter = new GamePresenter(game, gameView, this); node.getScene().setRoot(gameView); } else { backToThisScreen(node); } } }
true
2d85b0b72bcb6c4186342363d0a99f6e1cf8cc47
Java
clreolve/Proy2P_Bajana_Andrade_Townsend
/src/main/java/com/neoterux/proyecto2p/model/Continent.java
UTF-8
5,172
2.890625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.neoterux.proyecto2p.model; import com.neoterux.proyecto2p.App; import javafx.application.Platform; import javafx.scene.control.Alert; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * <h1>Continent</h1> * Esta clase representa a los datos de los continentes. * * @author neoterux */ public class Continent { /** * Lista que contiene los contienentes cargados de archivos. */ private static List<Continent> continentes; private static final Logger logger = LogManager.getLogger(Continent.class); /** * Nombre del continente */ private String name; /** * Lista con los paises pertenecientes a este continente */ private final List<Country> countries; /** * Crea un nuevo objeto continente * * @param name nombre del continente */ public Continent(String name) { countries = new ArrayList<>(); this.name = name; } /** * Carga los continentes a partir del archivo continentes.txt. * * @return lista con los continentes. */ public static List<Continent> loadContinents() { if (continentes == null){ var lst = new ArrayList<Continent>(); var file = Paths.get(App.FILES_PATH.toString(), "continentes.txt").toFile(); try (var reader = new BufferedReader(new FileReader(file), 1024)) { reader.lines().forEach(it -> lst.add(new Continent(it))); }catch (FileNotFoundException fnf) { logger.error("no se encontro el archivo continentes.txt.", fnf); new Alert(Alert.AlertType.ERROR, "Archivo continentes.txt no se encuentra en la carpeta data, cerrando.").showAndWait(); Platform.exit(); }catch (IOException ioe) { logger.error("Error at reading file continentes.txt ", ioe); } catch (Exception e){ logger.error("Unknow Exception when trying to read continentes.txt", e); } continentes = lst; loadCountries(); } return continentes; } @Override public String toString(){ return this.getName(); } @Override public boolean equals(Object o){ if ( o == this ) return true; if (o instanceof Continent){ return this.getName().equals(((Continent) o).getName()); } return false; } /** * @return the name */ public String getName() { return name; } /** * @return the countries */ public List<Country> getCountries() { return countries; } /** * Carga los paises del archivo paises.csv */ private static void loadCountries() { var file = Path.of(App.FILES_PATH.toString(), "paises.csv").toFile(); try (var reader = new BufferedReader(new FileReader(file))) { var continentMap = new HashMap<String,Continent>(); continentes.forEach(cont-> continentMap.put(cont.getName().toLowerCase(), cont)); reader.lines() .skip(1) // Skip header of .csv file .map(line -> line.split("[|]"))// Split .forEach(data ->{ /* * data[0]: Continent name * data[1]: Country name */ var c = continentMap.getOrDefault(data[0].toLowerCase(), null); if (c != null) { c.getCountries().add(new Country(data[1])); }else{ var nullContinent = new Continent(""); continentes.add(nullContinent); nullContinent.getCountries().add(new Country(data[1])); } }); }catch (FileNotFoundException fnf) { logger.error("File paises.csv not found in folder data", fnf); } catch(IOException ioe) { logger.error("Error when trying to read paises.csv ", ioe); }catch (Exception e){ logger.error("Unknow error when reading paises.csv", e); } } }
true
1c8c5afb98cc290a4c561c47d745d7e2a690d30d
Java
EdgarEmmanuel/DESIGN_PATTERN_ABSTRACT_FACTORY
/src/products/HouseBalance.java
UTF-8
133
1.835938
2
[]
no_license
package products; public class HouseBalance extends House{ @Override public int getPrix() { return 1000000; } }
true
1a55174092bd3b30f7e3431358acdc15cb621ec3
Java
naka921nox/naka921nox
/DesignPattern2/src/jp/strategy/Main.java
UTF-8
993
3.734375
4
[]
no_license
package jp.strategy; public class Main { public static void main (String[] srgs) { // 引数もらうところ横着 Player p1 = new Player("Bob", new WinningStrategy(314)); Player p2 = new Player("Emmy", new WinningStrategy(15)); for(int i = 0; i < 10000; i++) { Hand nextHand1 = p1.nextHand(); Hand nextHand2 = p2.nextHand(); if (nextHand1.isStrongerThan(nextHand2)) { System.out.println("winner;" + p1); p1.win(); p2.lose(); } else if (nextHand2.isStrongerThan(nextHand1)) { System.out.println("winner;" + p2); p2.win(); p1.lose(); } else { System.out.println("EVEN"); p1.even(); p2.even(); } } System.out.println("TOTAL:"); System.out.println(p1.toString()); System.out.println(p2.toString()); } }
true
08e1d16387ab1181d0a4df2cbc0d11c464b7e9fa
Java
JiaLuo/snl_factory
/app/src/main/java/com/shinaier/laundry/snlfactory/offlinecash/ui/activity/OfflineMemberAddActivity.java
UTF-8
28,867
1.539063
2
[]
no_license
package com.shinaier.laundry.snlfactory.offlinecash.ui.activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.common.network.FProtocol; import com.common.utils.ToastUtil; import com.common.viewinject.annotation.ViewInject; import com.shinaier.laundry.snlfactory.R; import com.shinaier.laundry.snlfactory.base.activity.ToolBarActivity; import com.shinaier.laundry.snlfactory.main.UserCenter; import com.shinaier.laundry.snlfactory.network.Constants; import com.shinaier.laundry.snlfactory.network.entity.MerchantCardListEntities; import com.shinaier.laundry.snlfactory.network.entity.PrintRechargeEntity; import com.shinaier.laundry.snlfactory.network.entity.UploadAddPhotoEntity; import com.shinaier.laundry.snlfactory.network.parser.Parsers; import com.shinaier.laundry.snlfactory.offlinecash.entities.PrintEntity; import com.shinaier.laundry.snlfactory.offlinecash.view.OnDateSetListener; import com.shinaier.laundry.snlfactory.offlinecash.view.TimePickerDialog; import com.shinaier.laundry.snlfactory.offlinecash.view.Type; import com.shinaier.laundry.snlfactory.util.ViewInjectUtils; import com.shinaier.laundry.snlfactory.view.CommonDialog; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.IdentityHashMap; /** * 新增会员 * Created by 张家洛 on 2017/7/28. */ public class OfflineMemberAddActivity extends ToolBarActivity implements View.OnClickListener, OnDateSetListener { public static final int SCAN_SUCCESS = 0x5; private static final int REQUEST_CODE_RECHARGE_PRINT = 0x7; private static final int IS_SUCCESS = 0x8; private static final int IS_FAIL = 0x9; private static final int REQUEST_CODE_MERCHANT_CARD_LIST = 0x10; private static final int REQUEST_CODE_ADD_MEMBER_PERSONAL = 0x11; @ViewInject(R.id.ed_input_member_name) private EditText edInputMemberName; @ViewInject(R.id.sex_man) private TextView sexMan; @ViewInject(R.id.sex_women) private TextView sexWomen; @ViewInject(R.id.tv_member_mobile) private TextView tvMemberMobile; @ViewInject(R.id.tv_member_birth) private TextView tvMemberBirth; @ViewInject(R.id.ed_input_member_address) private EditText edInputMemberAddress; @ViewInject(R.id.ed_input_member_mark) private EditText edInputMemberMark; @ViewInject(R.id.iv_member_normal_discount) private ImageView ivMemberNormalDiscount; @ViewInject(R.id.iv_member_nine_discount) private ImageView ivMemberNineDiscount; @ViewInject(R.id.iv_member_eight_discount) private ImageView ivMemberEightDiscount; @ViewInject(R.id.cash_pay_selector) private ImageView cashPaySelector; @ViewInject(R.id.wx_pay_selector) private ImageView wxPaySelector; @ViewInject(R.id.ali_pay_selector) private ImageView aliPaySelector; @ViewInject(R.id.confirm_pay) private TextView confirmPay; @ViewInject(R.id.left_button) private ImageView leftButton; @ViewInject(R.id.tv_member_normal) private TextView tvMemberNormal; @ViewInject(R.id.tv_member_gold) private TextView tvMemberGold; @ViewInject(R.id.tv_member_diamond) private TextView tvMemberDiamond; @ViewInject(R.id.member_normal_recharge_money) private TextView memberNormalRechargeMoney; @ViewInject(R.id.member_gold_recharge_money) private TextView memberGoldRechargeMoney; @ViewInject(R.id.member_diamond_recharge_money) private TextView memberDiamondRechargeMoney; // @ViewInject(R.id.member_normal_discount) 普通折扣暂时不要 // private TextView memberNormalDiscount; @ViewInject(R.id.member_gold_discount) private TextView memberGoldDiscount; @ViewInject(R.id.member_diamond_discount) private TextView memberDiamondDiscount; @ViewInject(R.id.member_name) private TextView memberName; @ViewInject(R.id.rl_member_sex) private RelativeLayout rlMemberSex; @ViewInject(R.id.rl_member_birth) private RelativeLayout rlMemberBirth; @ViewInject(R.id.rl_member_discount) private RelativeLayout rlMemberDiscount; @ViewInject(R.id.rl_member_recharge_money) private RelativeLayout rlMemberRechargeMoney; @ViewInject(R.id.ll_member_recharge_type) private LinearLayout llMemberRechargeType; @ViewInject(R.id.ll_member_recharge_normal) private LinearLayout llMemberRechargeNormal; @ViewInject(R.id.ll_member_recharge_gold) private LinearLayout llMemberRechargeGold; @ViewInject(R.id.ll_member_recharge_diamonds) private LinearLayout llMemberRechargeDiamonds; @ViewInject(R.id.ed_input_discout_num) private EditText edInputDiscoutNum; @ViewInject(R.id.ed_input_money_num) private EditText edInputMoneyNum; SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); TimePickerDialog mDialogYearMonthDay; private String memberBirth; private boolean isAliPay,isWxPay,isCashPay,isNineDiscount,isEightDiscount,isNormalDiscount,isClickTime,isMan,isWoman = false; private String user; // 自定dialog private CommonDialog dialog; // private String memberCode; //会员卡号 private int memberType; //会员类型 1 是个人会员 2 是企业会员 private String phoneNum; private String moneyNum; private PrintRechargeEntity printRechargeEntity; private PrintEntity printEntity = new PrintEntity(); private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case IS_SUCCESS: byte[] bytes = (byte[]) msg.obj; Bitmap qrCodeBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); if (qrCodeBitmap != null){ Intent intent = new Intent(OfflineMemberAddActivity.this,PrintActivity.class); intent.putExtra("extra_from",OfflineMemberRechargeActivity.FROM_MEMBER_RECHARGE_ACT); intent.putExtra("print_entity",printEntity); intent.putExtra("qrCode_bitmap",qrCodeBitmap); startActivity(intent); ToastUtil.shortShow(OfflineMemberAddActivity.this,"支付成功"); if (dialog.isShowing()){ dialog.dismiss(); } finish(); } break; case IS_FAIL: break; default: break; } } }; private MerchantCardListEntities merchantCardListEntities; private String inputMemberName; private String inputMemberAddress; private String inputMemberMark; private String inputDiscountNum; private String inputMoneyNum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.offline_member_add_act); ViewInjectUtils.inject(this); Intent intent = getIntent(); // memberCode = intent.getStringExtra("member_code"); //从会员管理页面传下来会员卡号 memberType = intent.getIntExtra("member_type", 0);//从会员管理页面传下来 1 是个人会员 2是企业会员 phoneNum = intent.getStringExtra("phone_num"); //从会员管理页面传下来手机号 if (memberType == 1 || memberType == 0){ // 默认没有点击企业会员还是个人会员 loadDiscountData(); } initView(); } private void loadDiscountData() { IdentityHashMap<String,String> params = new IdentityHashMap<String, String>(); params.put("token", UserCenter.getToken(this)); requestHttpData(Constants.Urls.URL_POST_MERCHANT_CARD_LIST,REQUEST_CODE_MERCHANT_CARD_LIST, FProtocol.HttpMethod.POST,params); } private void initView() { setCenterTitle("新增会员"); initLoadingView(this); setLoadingStatus(LoadingStatus.LOADING); if (memberType == 2){ //如果是企业会员没有折扣接口 直接隐藏 setLoadingStatus(LoadingStatus.GONE); } // tvMemberNum.setText(memberCode); if (memberType == 1 || memberType == 0){ //会员信息变更:进去没有“变更”按钮 文档错误的问题修改 memberName.setText("姓名"); rlMemberSex.setVisibility(View.VISIBLE); //个人会员 性别的行显示 sexMan.setOnClickListener(this); sexWomen.setOnClickListener(this); rlMemberBirth.setVisibility(View.VISIBLE); //个人会员 生日的行显示 tvMemberBirth.setOnClickListener(this); rlMemberDiscount.setVisibility(View.GONE); // 企业会员 折扣行隐藏 rlMemberRechargeMoney.setVisibility(View.GONE);//企业会员 充值金额隐藏 llMemberRechargeType.setVisibility(View.VISIBLE); //会员类型行显示 // TODO: 2017/12/27 特殊会员这里暂时删除 xml文件还没有删除 llMemberRechargeNormal.setVisibility(View.GONE); //普通会员充值行显示 llMemberRechargeGold.setVisibility(View.VISIBLE); //黄金会员充值行显示 llMemberRechargeDiamonds.setVisibility(View.VISIBLE); //钻石会员充值行显示 ivMemberNormalDiscount.setOnClickListener(this); ivMemberNineDiscount.setOnClickListener(this); ivMemberEightDiscount.setOnClickListener(this); }else if (memberType == 2){ memberName.setText("企业名称"); rlMemberSex.setVisibility(View.GONE);//个人会员 性别的行隐藏 rlMemberBirth.setVisibility(View.GONE);//个人会员 生日的行隐藏 rlMemberDiscount.setVisibility(View.VISIBLE);// 企业会员 折扣行显示 rlMemberRechargeMoney.setVisibility(View.VISIBLE);//企业会员 充值金额显示 llMemberRechargeType.setVisibility(View.GONE);//会员类型行隐藏 llMemberRechargeNormal.setVisibility(View.GONE); //普通会员充值行隐藏 llMemberRechargeGold.setVisibility(View.GONE); //黄金会员充值行隐藏 llMemberRechargeDiamonds.setVisibility(View.GONE); //钻石会员充值行隐藏 }else { memberName.setText(""); } tvMemberMobile.setText(phoneNum); confirmPay.setOnClickListener(this); cashPaySelector.setOnClickListener(this); wxPaySelector.setOnClickListener(this); aliPaySelector.setOnClickListener(this); leftButton.setOnClickListener(this); if (!isMan && !isWoman){ sexWomen.setSelected(true); } //初始化时间选择器 mDialogYearMonthDay = new TimePickerDialog.Builder() .setType(Type.YEAR_MONTH_DAY) .setCallBack(this) .build(); dialog = new CommonDialog(this); } @Override protected void parseData(int requestCode, String data) { super.parseData(requestCode, data); switch (requestCode){ case REQUEST_CODE_MERCHANT_CARD_LIST: if (data != null){ merchantCardListEntities = Parsers.getMerchantCardListEntities(data); setLoadingStatus(LoadingStatus.GONE); if (merchantCardListEntities != null){ if (merchantCardListEntities.getCode() == 0){ if (merchantCardListEntities.getResult() != null && merchantCardListEntities.getResult().size() > 0){ //设置普通会员信息 // tvMemberNormal.setText(storeInfoEntity.getCards().get(0).getCardName()); // if (storeInfoEntity.getCards().get(0).getDiscount().equals("10.0")){ // memberNormalDiscount.setText("无折扣"); // }else { // memberNormalDiscount.setText(storeInfoEntity.getCards().get(0).getDiscount() + "折"); // } // memberNormalRechargeMoney.setText("充值" + storeInfoEntity.getCards().get(0).getPrice()); //设置黄金会员信息 tvMemberGold.setText(merchantCardListEntities.getResult().get(0).getCardName()); memberGoldDiscount.setText(merchantCardListEntities.getResult().get(0).getDiscount() + "折"); memberGoldRechargeMoney.setText("充值" + merchantCardListEntities.getResult().get(0).getPrice()); //设置钻石会员信息 tvMemberDiamond.setText(merchantCardListEntities.getResult().get(1).getCardName()); memberDiamondDiscount.setText(merchantCardListEntities.getResult().get(1).getDiscount() + "折"); memberDiamondRechargeMoney.setText("充值" + merchantCardListEntities.getResult().get(1).getPrice()); } }else { ToastUtil.shortShow(this, merchantCardListEntities.getMsg()); } }else { setLoadingStatus(LoadingStatus.EMPTY); } }else { setLoadingStatus(LoadingStatus.EMPTY); } break; case REQUEST_CODE_ADD_MEMBER_PERSONAL: if (data != null){ UploadAddPhotoEntity uploadAddPhotoEntity = Parsers.getUploadAddPhotoEntity(data); if (uploadAddPhotoEntity.getCode() == 0){ dialog.setContent("加载中"); dialog.show(); memberRecharge(uploadAddPhotoEntity.getResult()); }else { ToastUtil.shortShow(this,uploadAddPhotoEntity.getMsg()); } } break; case REQUEST_CODE_RECHARGE_PRINT: if (data != null){ printRechargeEntity = Parsers.getPrintRechargeEntity(data); if (printRechargeEntity != null){ if (printRechargeEntity.getCode() == 0){ if (printRechargeEntity.getResult() != null){ setRechargePrint(); } }else { ToastUtil.shortShow(this, printRechargeEntity.getMsg()); } } } break; } } /** * 打印接口 * @param rechargeId 充值id */ private void memberRecharge(String rechargeId) { IdentityHashMap<String,String> params = new IdentityHashMap<>(); params.put("token",UserCenter.getToken(this)); params.put("record_id",rechargeId); requestHttpData(Constants.Urls.URL_POST_RECHARGE_PRINT,REQUEST_CODE_RECHARGE_PRINT, FProtocol.HttpMethod.POST,params); } //设置打印页面的数据 private void setRechargePrint() { PrintEntity.RechargePrintEntity rechargePrintEntity = printEntity.new RechargePrintEntity(); rechargePrintEntity.setTradeSn(printRechargeEntity.getResult().getTradeSn()); rechargePrintEntity.setUmobile(printRechargeEntity.getResult().getUmobile()); rechargePrintEntity.setAmount(printRechargeEntity.getResult().getAmount()); rechargePrintEntity.setGive(printRechargeEntity.getResult().getGive()); rechargePrintEntity.setMaddress(printRechargeEntity.getResult().getMaddress()); rechargePrintEntity.setPhone_number(printRechargeEntity.getResult().getPhoneNumber()); rechargePrintEntity.setMid(printRechargeEntity.getResult().getMid()); rechargePrintEntity.setMname(printRechargeEntity.getResult().getmName()); rechargePrintEntity.setEmployee(printRechargeEntity.getResult().getEmployee()); rechargePrintEntity.setGateway(printRechargeEntity.getResult().getGateway()); printEntity.setRechargePrintEntity(rechargePrintEntity); String qrcodeUrl = printRechargeEntity.getResult().getQrcode(); asyncGetImage(qrcodeUrl); //从图片链接 byte数组,然后转成bitmap对象 } private void asyncGetImage(String qrcodeUrl) { OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder().get() .url(qrcodeUrl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { e.printStackTrace(); } @Override public void onResponse(Response response) throws IOException { Message message = handler.obtainMessage(); if (response.isSuccessful()) { message.what = IS_SUCCESS; message.obj = response.body().bytes(); handler.sendMessage(message); } else { handler.sendEmptyMessage(IS_FAIL); } } }); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.confirm_pay: inputMemberName = edInputMemberName.getText().toString(); inputMemberAddress = edInputMemberAddress.getText().toString(); inputMemberMark = edInputMemberMark.getText().toString(); inputDiscountNum = edInputDiscoutNum.getText().toString(); inputMoneyNum = edInputMoneyNum.getText().toString(); if (memberType == 1 || memberType == 0){ if (!TextUtils.isEmpty(inputMemberName)){ if (isNormalDiscount || isNineDiscount || isEightDiscount){ if (isCashPay || isWxPay || isAliPay){ if (isCashPay){ confirmAdd(""); }else { startActivityForResult(new Intent(this,ScanActivity.class),SCAN_SUCCESS); } }else { ToastUtil.shortShow(this,"请选择支付方式"); } }else { ToastUtil.shortShow(this,"请选择充值会员类型"); } }else { ToastUtil.shortShow(this,"请输入名字"); } }else { if (!TextUtils.isEmpty(inputMemberName)){ if (!TextUtils.isEmpty(inputDiscountNum)){ double dDiscountNum = Double.parseDouble(inputDiscountNum); if (dDiscountNum >= 1 && dDiscountNum <= 10){ if (!TextUtils.isEmpty(inputMoneyNum)){ if (isCashPay || isWxPay || isAliPay){ if (isCashPay){ confirmAdd(""); }else { startActivityForResult(new Intent(this,ScanActivity.class),SCAN_SUCCESS); } }else { ToastUtil.shortShow(this,"请选择支付方式"); } }else { ToastUtil.shortShow(this,"请输入充值金额"); } }else { ToastUtil.shortShow(this,"您输入的折扣不正确"); } }else { ToastUtil.shortShow(this,"请输入折扣"); } }else { ToastUtil.shortShow(this,"请输入名字"); } } break; case R.id.sex_man: if (sexMan.isSelected()){ sexMan.setSelected(false); }else { sexMan.setSelected(true); if (sexWomen.isSelected()){ sexWomen.setSelected(false); } isMan = true; isWoman = false; } break; case R.id.sex_women: if (sexWomen.isSelected()){ sexWomen.setSelected(false); }else { sexWomen.setSelected(true); if (sexMan.isSelected()){ sexMan.setSelected(false); } isWoman = true; isMan = false; } break; case R.id.tv_member_birth: isClickTime = true; mDialogYearMonthDay.show(getSupportFragmentManager(), "year_month_day"); break; case R.id.iv_member_normal_discount: if (ivMemberNormalDiscount.isSelected()){ ivMemberNormalDiscount.setSelected(false); }else { ivMemberNormalDiscount.setSelected(true); isNormalDiscount = true; isNineDiscount = false; isEightDiscount = false; if (ivMemberNineDiscount.isSelected() || ivMemberEightDiscount.isSelected()){ ivMemberNineDiscount.setSelected(false); ivMemberEightDiscount.setSelected(false); } } break; case R.id.iv_member_nine_discount: if (ivMemberNineDiscount.isSelected()){ ivMemberNineDiscount.setSelected(false); }else { ivMemberNineDiscount.setSelected(true); isNineDiscount = true; isNormalDiscount = false; isEightDiscount = false; if (ivMemberNormalDiscount.isSelected() || ivMemberEightDiscount.isSelected()){ ivMemberNormalDiscount.setSelected(false); ivMemberEightDiscount.setSelected(false); } } break; case R.id.iv_member_eight_discount: if (ivMemberEightDiscount.isSelected()){ ivMemberEightDiscount.setSelected(false); }else { ivMemberEightDiscount.setSelected(true); isEightDiscount = true; isNineDiscount = false; isNormalDiscount = false; if (ivMemberNormalDiscount.isSelected() || ivMemberNineDiscount.isSelected()){ ivMemberNormalDiscount.setSelected(false); ivMemberNineDiscount.setSelected(false); } } break; case R.id.cash_pay_selector: if (cashPaySelector.isSelected()){ cashPaySelector.setSelected(false); }else { cashPaySelector.setSelected(true); isCashPay = true; isWxPay = false; isAliPay = false; if (wxPaySelector.isSelected() || aliPaySelector.isSelected()){ wxPaySelector.setSelected(false); aliPaySelector.setSelected(false); } } break; case R.id.wx_pay_selector: if (wxPaySelector.isSelected()){ wxPaySelector.setSelected(false); }else { wxPaySelector.setSelected(true); isWxPay = true; isCashPay = false; isAliPay = false; if (cashPaySelector.isSelected() || aliPaySelector.isSelected()){ cashPaySelector.setSelected(false); aliPaySelector.setSelected(false); } } break; case R.id.ali_pay_selector: if (aliPaySelector.isSelected()){ aliPaySelector.setSelected(false); }else { aliPaySelector.setSelected(true); isAliPay = true; isCashPay = false; isWxPay = false; if (cashPaySelector.isSelected() || wxPaySelector.isSelected()){ cashPaySelector.setSelected(false); wxPaySelector.setSelected(false); } } break; case R.id.left_button: finish(); break; } } @Override public void onDateSet(TimePickerDialog timePickerView, long millseconds) { memberBirth = getDateToString(millseconds); tvMemberBirth.setText(memberBirth); } //格式化时间 public String getDateToString(long time) { Date d = new Date(time); return sf.format(d); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode){ case SCAN_SUCCESS: if (resultCode == RESULT_OK){ if (data != null){ // setLoadingStatus(LoadingStatus.LOADING); dialog.setContent("加载中"); dialog.show(); String payCode = data.getStringExtra("pay_code"); confirmAdd(payCode); } } break; } } private void confirmAdd(String payCode) { String url = ""; dialog.setContent("加载中"); dialog.show(); IdentityHashMap<String,String> params = new IdentityHashMap<>(); params.put("token",UserCenter.getToken(this)); params.put("umobile",phoneNum); params.put("uname",inputMemberName); params.put("reg_from","2"); if (isCashPay){ params.put("gateway","CASH"); params.put("auth_code","1"); }else if (isWxPay){ params.put("gateway","WechatPay_Pos"); params.put("auth_code",payCode); }else { params.put("gateway","Alipay_AopF2F"); params.put("auth_code",payCode); } params.put("addr",inputMemberAddress); params.put("remark",inputMemberMark); if (memberType == 1 || memberType == 0){ if (isMan){ params.put("sex","1"); }else if (isWoman){ params.put("sex","2"); }else { params.put("sex","2"); } if (isClickTime){ params.put("birthday",memberBirth); }else { params.put("birthday","1980-01-01"); } if (isNineDiscount){ params.put("cid",merchantCardListEntities.getResult().get(0).getId()); }else { params.put("cid",merchantCardListEntities.getResult().get(1).getId()); } url = Constants.Urls.URL_POST_ADD_MEMBER_PERSONAL; }else { params.put("cdiscount",inputDiscountNum); params.put("amount",inputMoneyNum); url = Constants.Urls.URL_POST_ADD_MEMBER_COMPANY; } requestHttpData(url,REQUEST_CODE_ADD_MEMBER_PERSONAL, FProtocol.HttpMethod.POST,params); } }
true
4f647982408b20b318f798ff849df1622495f44f
Java
YILIN-U/spring-cloud
/cloud-consumerconsul-order80/src/main/java/com/wx/springcloud/controller/OrderConController.java
UTF-8
728
1.929688
2
[]
no_license
package com.wx.springcloud.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/order") public class OrderConController { public static final String INVOKE_URL="http://consul-payment-server"; @Autowired RestTemplate restTemplate; @GetMapping("/consul") public String paymentInfo() { String result=restTemplate.getForObject(INVOKE_URL+"/payment/consul",String.class); return result; } }
true
735c382d1c2bac951c644e7daf6003e05813a534
Java
mouday/Mo-Blog
/blog-api/src/main/java/com/mouday/blogapi/controller/BlogController.java
UTF-8
1,892
2.171875
2
[]
no_license
package com.mouday.blogapi.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import com.mouday.blogapi.exception.BaseException; import com.mouday.blogapi.pojo.Blog; import com.mouday.blogapi.result.ResultCode; import com.mouday.blogapi.result.ResultController; import com.mouday.blogapi.service.BlogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; @ResultController public class BlogController { @Autowired BlogService blogService; @GetMapping("/blog") public Blog getBlog(@RequestParam Integer id) { return blogService.getBlog(id); } @DeleteMapping("/blog") public void deleteBlog(@RequestParam Integer id) { int ret = blogService.deleteById(id); if(ret == 0){ throw new BaseException(ResultCode.RECORD_NOT_EXIST); } } @GetMapping("/blogs") public Map<String, Object> getBlogs( @RequestParam(required = false, defaultValue = "1") Integer page, @RequestParam(required = false, defaultValue = "10") Integer size, @RequestParam(required = false) Integer dynastyId ) { IPage<Blog> iPage = blogService.getBlogList(page, size, dynastyId); Map<String, Object> map = new HashMap<>(); map.put("list", iPage.getRecords()); map.put("total", iPage.getTotal()); return map; } @PostMapping("/blog") public Blog saveBlog(@RequestBody Blog blog){ return blogService.saveBlog(blog); } @PostMapping("/blogStatus") public void saveBlogStatus(@RequestBody Blog blog){ int ret = blogService.updateShowStatusById(blog.getId(), blog.getIsShow()); if(ret == 0){ throw new BaseException(ResultCode.RECORD_NOT_EXIST); } } }
true
8182389a70a252323f58f83a4c6fead35708944f
Java
humanyiyi/WT_CSVparser
/src/main/java/com/udbac/parser/log4j/Log4jUtil.java
UTF-8
206
1.960938
2
[]
no_license
package com.udbac.parser.log4j; import org.apache.log4j.Logger; public class Log4jUtil { Logger logger = Logger.getLogger(Log4jUtil.class); public void sqlError(String sql){ logger.error(sql); } }
true
9b342da62365dbb28051856ae61d959fd5a8cc8a
Java
miktemk/AcousterCommons
/org.acouster.android/src/org/acouster/android/ui/GameActivity.java
UTF-8
6,296
2.25
2
[]
no_license
package org.acouster.android.ui; import org.acouster.DebugUtil; import org.acouster.Game; import org.acouster.GameContext; import org.acouster.GameEvent; import org.acouster.android.R; import org.acouster.android.ui.AndroidGamePanel; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.Window; import android.view.WindowManager; import com.google.ads.AdRequest; import com.google.ads.AdView; public class GameActivity extends BaseActivity implements GameContext { protected AndroidGamePanel gamePanel; protected Game game; private boolean threadActivityControlFreakKilled = false; protected Bundle bundle; /** Called when the activity is first created. */ @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); this.bundle = bundle; if (showAds) { Log.v(DebugUtil.TAG, "GameActivity: showAds"); setContentView(R.layout.game_panel_ads); AdView adView = (AdView)findViewById(R.id.adView); adView.loadAd(new AdRequest()); gamePanel = (AndroidGamePanel)findViewById(R.id.gamePanel); gamePanel.requestFocus(); } else if (flashlightEnabled) { Log.v(DebugUtil.TAG, "GameActivity: flashlightEnabled"); setContentView(R.layout.game_panel_flashlight); // we need to set cam surface so that flashlight cam can use it SurfaceView surface = (SurfaceView)findViewById(R.id.preview); setUpCamera(surface); gamePanel = (AndroidGamePanel)findViewById(R.id.gamePanel); gamePanel.requestFocus(); } else { Log.v(DebugUtil.TAG, "GameActivity: default new GamePanel"); gamePanel = new AndroidGamePanel(this); setContentView(gamePanel); gamePanel.requestFocus(); } } /** word of advice: never put shit on production that calls this function... */ protected void displayHints() { gamePanel.displayHints(); } /** called before setGame if you want the game to take manual control of the threading */ public void manualThreadControl() { gamePanel.setUseThread(false); } /** call manualThreadControl before this IF(!!!!!) you want the Game to control the thread instead of thread running all the time */ public void setGame(Game game) { this.game = game; gamePanel.setGame(game); game.setContext(this); recoverLostSettings(bundle); } public void activateFullscreen() { // Set full screen view getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); } protected void setThreadActivityControlFreakEnabled(boolean flag) { threadActivityControlFreakKilled = !flag; } @Override protected void onAccelerometerCoordsChanged(float mSensorX, float mSensorY) { //Log.v(DebugUtil.TAG, "onAccelerometerCoordsChanged"); super.onAccelerometerCoordsChanged(mSensorX, mSensorY); if (game != null) game.onAccelerometerChange(mSensorX, mSensorY); } // =================== pause/resume/destroy events ================================== // @Override // protected void onStart() { // super.onStart(); // Log.v(DebugUtil.TAG, "onStart thread " + this); // } // protected void onStop() { // super.onStart(); // Log.v(DebugUtil.TAG, "onStop thread " + this); // } // @Override // protected void onRestart() { // super.onResume(); // Log.v(DebugUtil.TAG, "onRestart thread " + this); // } @Override protected void onResume() { super.onResume(); Log.v(DebugUtil.TAG, "onResume thread " + this); gamePanel.startThread(); } @Override protected void onPause() { super.onPause(); Log.v(DebugUtil.TAG, "onPause thread " + this); if (!threadActivityControlFreakKilled) gamePanel.pauseThread(); } @Override public void onDestroy() { super.onDestroy(); Log.v(DebugUtil.TAG, "onDestroy thread " + this); // Don't forget to shutdown! gamePanel.killThread(); if (game != null) game.dispose(); } @Override public void onBackPressed() { if (game.backButtonPressed()) super.onBackPressed(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Log.v("======>", "onSaveInstanceState"); if (game != null) { outState.putIntArray(Game.BUNDLE_KEY_SCREEN_STACK, game.getInnerScreenStack()); outState.putString(Game.BUNDLE_KEY_GAME_JSON, game.getBundleValues()); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); //Log.v("======>", "onRestoreInstanceState"); recoverLostSettings(savedInstanceState); } private void recoverLostSettings(Bundle bundle) { if (bundle == null) return; if (game == null) return; if (bundle.containsKey(Game.BUNDLE_KEY_SCREEN_STACK)) game.setInnerScreenStack(bundle.getIntArray(Game.BUNDLE_KEY_SCREEN_STACK)); if (bundle.containsKey(Game.BUNDLE_KEY_GAME_JSON)) game.restoreBundleValues(bundle.getString(Game.BUNDLE_KEY_GAME_JSON)); } // =================== GameContext methods ================================== @Override public int getContextHeight() { return gamePanel.getHeight(); } @Override public int getContextWidth() { return gamePanel.getWidth(); } @Override public int getContextDiagonal() { return gamePanel.getHeight() + gamePanel.getWidth(); } @Override public void handleMessage(GameEvent message) { if (message.is(Game.DIRECTIVE_KILL_ACTIVITY)) killActivity(); } @Override public void triggerRepaint() { gamePanel.triggerRepaint(); } @Override public void killActivity() { finish(); } @Override public void forceStartThread() { gamePanel.startThread_force(); } @Override public void forceStopThread() { gamePanel.pauseThread(); } }
true
43620a883b5b73cc7d7236f6d1733c791015c309
Java
pnabbefeld/ApacheHttpdConfigurator
/src/main/java/de/epdv/tools/configurator/httpd/conf/NamedMultiValue.java
UTF-8
666
2.046875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package de.epdv.tools.configurator.httpd.conf; import java.util.List; /** * * @author peter */ public class NamedMultiValue { private final String name; private final List<ActivableValue> values; public NamedMultiValue(String name, List<ActivableValue> values) { this.name = name; this.values = values; } public String getName() { return name; } public List<ActivableValue> getValues() { return values; } }
true
f5f321b04c71678219a9213bf5e5c0f5a57966a7
Java
Jabberwaka/AndroidApp
/app/src/main/java/com/example/tyler/trafficapp/Camera.java
UTF-8
1,001
2.546875
3
[]
no_license
package com.example.tyler.trafficapp; public class Camera { private String cameraName; private String cameraId; private String cameraLong; private String cameraLat; public Camera(String name, String id, String longitude, String lat) { this.cameraName = name; this.cameraId = id; this.cameraLat = lat; this.cameraLong = longitude; } public String getCameraName() { return cameraName; } public String getCameraId() { return cameraId; } public String getCameraLong() { return cameraLong; } public String getCameraLat() { return cameraLat; } public void setCameraName(String name) { this.cameraName = name; } public void setCameraId(String id) { this.cameraId = id; } public void setCameraLong(String longitude) { this.cameraLong = longitude; } public void setCameraLat(String lat) { this.cameraLat = lat; } }
true
c1d7eac340907f737505f8bff5628a9ca9d18e2c
Java
dorel1958/basicopp
/src/dorel/basicopp/excelreport/Report.java
UTF-8
10,278
2.171875
2
[]
no_license
package dorel.basicopp.excelreport; import dorel.basicopp.datatypes.Numere; import dorel.basicopp.excelreport.FisExcel.TipFisExcel; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.Map; import javax.swing.JOptionPane; import org.apache.poi.hssf.usermodel.HSSFWorkbook; //import org.apache.poi.hssf.util.CellRangeAddress; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.WorkbookUtil; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Report { private final TipFisExcel tipFisExcel; //private final String numeFisDef; //- apare insa in Constructor!!! private final String numeFisExcel; //private String pathExcelExe = "\"C:\\Program Files (x86)\\Microsoft Office\\OFFICE11\\excel.exe\""; private String pathExcelExe = "\"C:\\Program Files (x86)\\Microsoft Office\\Office15\\excel.exe\""; Map<String, String> mCommon; String[] columnNames; List<String[]> lDate; private Workbook wb; private Sheet sheet; private int currentRow; // public void setPathExcelExe(String path) { pathExcelExe = path; } //<editor-fold defaultstate="collapsed" desc="Constructor"> public Report(String numeFisDef, String numeFisExcel, TipFisExcel tipFisExcel, Map<String, String> mCommon, String[] columnNames, List<String[]> lDate) { //this.numeFisDef = numeFisDef; this.numeFisExcel = numeFisExcel; this.tipFisExcel = tipFisExcel; this.mCommon = mCommon; this.columnNames = columnNames; this.lDate = lDate; currentRow = 0; } public Report(String numeFisExcel, TipFisExcel tipFisExcel) { //this.numeFisDef = ""; this.numeFisExcel = numeFisExcel; this.tipFisExcel = tipFisExcel; this.mCommon = null; this.columnNames = null; this.lDate = null; currentRow = 0; } //</editor-fold> public void addRow(int skipRows, int fromX, String[] content) { int currentX = fromX; currentRow += skipRows; Row row = sheet.createRow(currentRow); DataFormat format = wb.createDataFormat(); CellStyle integerStyle = wb.createCellStyle(); integerStyle.setDataFormat(format.getFormat("0")); currentRow += 1; if (content == null) { return; } for (String cellContent : content) { if (cellContent != null) { if (cellContent.startsWith("=")) { // celulele ce incep cu = sunt formule row.createCell(currentX).setCellFormula(cellContent.substring(1)); } else { if (Numere.isInteger(cellContent)) { Cell cell = row.createCell(currentX); //cell.setCellStyle(integerStyle); cell.setCellValue(Integer.parseInt(cellContent)); } else { if (Numere.isLong(cellContent)) { Cell cell = row.createCell(currentX); cell.setCellStyle(integerStyle); cell.setCellValue(Long.parseLong(cellContent)); } else { if (Numere.isNumeric(cellContent)) { Cell cell = row.createCell(currentX); cell.setCellValue(Double.parseDouble(cellContent)); } else { Cell cell = row.createCell(currentX); cell.setCellValue(cellContent); } } } } } currentX += 1; } } //<editor-fold defaultstate="collapsed" desc="Formatare celule"> public void autoSizeColumns(List<Integer> lista) { for (int ncol : lista) { sheet.autoSizeColumn(ncol); } } public void bold(int firstRow, int lastRow, int firstColumn, int lastColumn) { Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle oldStyle; CellStyle style; Row row; Cell cell; for (int i = firstRow; i <= lastRow; i++) { row = sheet.getRow(i); if (row == null) { row = sheet.createRow(i); } for (int j = firstColumn; j <= lastColumn; j++) { cell = row.getCell(j); if (cell == null) { cell = row.createCell(j); } oldStyle = cell.getCellStyle(); style = wb.createCellStyle(); style.cloneStyleFrom(oldStyle); style.setFont(font); cell.setCellStyle(style); } } } public void drawConturLine(short borderLine, int firstRow, int lastRow, int firstColumn, int lastColumn) { CellStyle oldStyle; CellStyle style; Row row; Cell cell; // line Top row = sheet.getRow(firstRow); if (row == null) { row = sheet.createRow(firstRow); } for (int i = firstColumn; i <= lastColumn; i++) { cell = row.getCell(i); if (cell == null) { cell = row.createCell(i); } oldStyle = cell.getCellStyle(); style = wb.createCellStyle(); style.cloneStyleFrom(oldStyle); style.setBorderTop(borderLine); cell.setCellStyle(style); } // line Bottom row = sheet.getRow(lastRow); if (row == null) { row = sheet.createRow(lastRow); } for (int i = firstColumn; i <= lastColumn; i++) { cell = row.getCell(i); if (cell == null) { cell = row.createCell(i); } oldStyle = cell.getCellStyle(); style = wb.createCellStyle(); style.cloneStyleFrom(oldStyle); style.setBorderBottom(borderLine); cell.setCellStyle(style); } // linie Left for (int i = firstRow; i <= lastRow; i++) { row = sheet.getRow(i); if (row == null) { row = sheet.createRow(i); } // linie Left cell = row.getCell(firstColumn); if (cell == null) { cell = row.createCell(firstColumn); } oldStyle = cell.getCellStyle(); style = wb.createCellStyle(); style.cloneStyleFrom(oldStyle); style.setBorderLeft(borderLine); cell.setCellStyle(style); // linie Right cell = row.getCell(lastColumn); if (cell == null) { cell = row.createCell(lastColumn); } oldStyle = cell.getCellStyle(); style = wb.createCellStyle(); style.cloneStyleFrom(oldStyle); style.setBorderRight(borderLine); cell.setCellStyle(style); } } public void mergeCells(int firstRow, int lastRow, int firstColumn, int lastColumn, boolean centrat) { // 0 based if (centrat) { Row row = sheet.getRow(firstRow); if (row == null) { row = sheet.createRow(firstRow); } Cell cell = row.getCell(firstColumn); if (cell == null) { cell = row.createCell(firstColumn); } CellStyle oldStyle = cell.getCellStyle(); CellStyle style = wb.createCellStyle(); style.cloneStyleFrom(oldStyle); style.setAlignment(CellStyle.ALIGN_CENTER); cell.setCellStyle(style); } sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstColumn, lastColumn)); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Operatii fisier Excel"> public void genExcel(String sheetName) { if (tipFisExcel == TipFisExcel.xls) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); } String safeName = WorkbookUtil.createSafeSheetName(sheetName); sheet = wb.createSheet(safeName); } public boolean writeToFile() { return writeToFile(numeFisExcel); } public boolean writeToFile(String newNumeFisExcel) { // salvare pe disc FileOutputStream fileOut; try { fileOut = new FileOutputStream(newNumeFisExcel); wb.write(fileOut); fileOut.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error Report.writeToFile:" + ex.getLocalizedMessage()); return false; } return true; } public void viewFisExcel() { try { Process p = Runtime.getRuntime().exec(pathExcelExe + " " + numeFisExcel); // String mesaj = ""; // int resp = p.waitFor(); // if (resp == 0) { // mesaj+="corect\n"; // BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); // String line = reader.readLine(); // while (line != null) { // line = reader.readLine(); // mesaj+=line+"\n"; // } // } else { // mesaj+="eroare\n"; // } //JOptionPane.showMessageDialog(null, "Continua ... mesaj=" + mesaj); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error - Report.viewFisExcel: " + ex.getLocalizedMessage()); } } public void print() { // creaza un fisier gol genExcel("Sheet"); writeToFile(); viewFisExcel(); } //</editor-fold> }
true
935e482b3de65e0ba415c9223da2d42581b6dfd7
Java
QuexerDev/ServerNet
/ServerAPI/src/main/java/me/quexer/server/serverapi/commands/CheckCMD.java
UTF-8
1,400
2.421875
2
[]
no_license
package me.quexer.server.serverapi.commands; import me.quexer.api.quexerapi.misc.uuid.UUIDFetcher; import me.quexer.server.serverapi.ServerAPI; import me.quexer.server.serverapi.callbacks.CheckPlayerCallback; import me.quexer.server.spigotserverperms.models.Group; import org.bukkit.entity.Player; public class CheckCMD { private ServerAPI plugin; public CheckCMD(ServerAPI plugin) { this.plugin = plugin; plugin.onCommand("check", (sender, command, s, args) -> { Player player = (Player) sender; Group group = plugin.getGroupManager().getPlayer(player.getUniqueId().toString()).getGroup(); if(group.hasPermission(9)) { if (args.length == 1) { UUIDFetcher.getUUID(args[0], targetUUID -> { if (targetUUID == null) { sender.sendMessage(plugin.getPrefix() + "§cDieser Spieler existiert nicht!"); return; } new CheckPlayerCallback(plugin, targetUUID.toString(), ((Player) sender).getUniqueId().toString(), (Player) sender).accept((Player) sender); }); } else { player.sendMessage(plugin.getError()+"§7Benutze§8: §c/check <Spieler>"); } } return true; }); } }
true
0f8feaa85f513dee8476bb096d5f799f34a39a52
Java
sgros/activity_flow_plugin
/TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/JADX/src/main/java/org/telegram/p004ui/C1543-$$Lambda$GroupStickersActivity$Z_OfWFCln7TEpsXJNMwvYTvczmA.java
UTF-8
767
1.507813
2
[]
no_license
package org.telegram.p004ui; import org.telegram.tgnet.TLRPC.TL_error; /* compiled from: lambda */ /* renamed from: org.telegram.ui.-$$Lambda$GroupStickersActivity$Z_OfWFCln7TEpsXJNMwvYTvczmA */ public final /* synthetic */ class C1543-$$Lambda$GroupStickersActivity$Z_OfWFCln7TEpsXJNMwvYTvczmA implements Runnable { private final /* synthetic */ GroupStickersActivity f$0; private final /* synthetic */ TL_error f$1; public /* synthetic */ C1543-$$Lambda$GroupStickersActivity$Z_OfWFCln7TEpsXJNMwvYTvczmA(GroupStickersActivity groupStickersActivity, TL_error tL_error) { this.f$0 = groupStickersActivity; this.f$1 = tL_error; } public final void run() { this.f$0.lambda$null$6$GroupStickersActivity(this.f$1); } }
true
afa86f8db477cb0797060be04826bee13faa1f0b
Java
zengxuezhen/SPLS
/SPLSBackStage/src/main/java/com/zl/service/impl/OperationLogServiceImpl.java
UTF-8
692
2.125
2
[]
no_license
package com.zl.service.impl; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zl.dao.OperationLogDao; import com.zl.pojo.OperationLog; import com.zl.service.OperationLogService; /* * 操作日志service层接口实现类 * */ @Service public class OperationLogServiceImpl implements OperationLogService { @Autowired private OperationLogDao od; /* * 调用dao层接口,OperationLog表添加数据 * */ @Override public int addOperationLog(OperationLog operationLog) { operationLog.setCreateTime(new Date()); int line=od.insertOperationLog(operationLog); return line; } }
true
0645ec84575d12992d5865749e75d11e5ac62406
Java
iwanttobesenior/pet
/src/main/java/training/patterns/command/User.java
UTF-8
637
3.375
3
[]
no_license
package training.patterns.command; /** * {@code class} as Invoker */ class User { private final Command startCommand; private final Command stopCommand; private final Command resetCommand; public User(Command startCommand, Command stopCommand, Command resetCommand) { this.startCommand = startCommand; this.stopCommand = stopCommand; this.resetCommand = resetCommand; } public void starComputer() { startCommand.execute(); } public void stopComputer() { stopCommand.execute(); } public void resetComputer() { resetCommand.execute(); } }
true
6429c3846338d69b45cb480e15e00b207edd4f1b
Java
tied/cures-condec-jira
/src/test/java/de/uhd/ifi/se/decision/management/jira/recommendation/decisionguidance/rdfsource/TestRDFSourceRecommender.java
UTF-8
3,074
1.984375
2
[ "MIT" ]
permissive
package de.uhd.ifi.se.decision.management.jira.recommendation.decisionguidance.rdfsource; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import de.uhd.ifi.se.decision.management.jira.TestSetUp; import de.uhd.ifi.se.decision.management.jira.model.KnowledgeElement; import de.uhd.ifi.se.decision.management.jira.model.KnowledgeGraph; import de.uhd.ifi.se.decision.management.jira.model.KnowledgeType; import de.uhd.ifi.se.decision.management.jira.model.Link; import de.uhd.ifi.se.decision.management.jira.testdata.KnowledgeElements; public class TestRDFSourceRecommender extends TestSetUp { private final static String PROJECTKEY = "TEST"; private final static String NAME = "TESTSOURCE"; private final static String SERVICE = "http://dbpedia.org/sparql"; private static final String PREFIX = "PREFIX dbo: <http://dbpedia.org/ontology/>" + "PREFIX dct: <http://purl.org/dc/terms/>" + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>" + "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"; private final static String QUERY = PREFIX + " select distinct ?subject ?url count(?link) where { " + "%variable% dbo:genre ?genre. " + "?subject dbo:genre ?genre. " + "?subject foaf:isPrimaryTopicOf ?url. " + "?subject dbo:wikiPageExternalLink ?link.} GROUP BY ?subject ?url "; private final static int TIMEOUT = 50000; private RDFSource rdfSource; @Before public void setUp() { init(); } @Test public void testRDFSourceWithStringInput() { RDFSourceRecommender rdfSourceInputString = new RDFSourceRecommender("TEST", rdfSource); rdfSourceInputString.setKnowledgeSource(new RDFSource(NAME, SERVICE, QUERY, TIMEOUT, "Lizenz=dbo:license")); assertEquals(34, rdfSourceInputString.getRecommendations("MySQL").size()); assertEquals(0, rdfSourceInputString.getRecommendations("").size()); assertEquals(0, rdfSourceInputString.getRecommendations((String) null).size()); rdfSourceInputString.setKnowledgeSource(new RDFSource(NAME, "WRONG SERVICE", "INVALID QUERY", TIMEOUT, "")); assertEquals(0, rdfSourceInputString.getRecommendations("Does not matter").size()); } @Test public void testRDFSourceWithKnowledgeElement() { KnowledgeElement alternative = new KnowledgeElement(); alternative.setType(KnowledgeType.ALTERNATIVE); alternative.setSummary("MySQL"); alternative.setId(123); Link link = new Link(KnowledgeElements.getTestKnowledgeElement(), alternative); KnowledgeGraph graph = KnowledgeGraph.getInstance(PROJECTKEY); graph.addEdge(link); RDFSourceRecommender rdfSourceInputString = new RDFSourceRecommender("TEST", rdfSource); rdfSourceInputString.setKnowledgeSource(new RDFSource(NAME, SERVICE, QUERY, TIMEOUT, "")); assertEquals(34, rdfSourceInputString.getRecommendations(KnowledgeElements.getTestKnowledgeElement()).size()); assertEquals(0, rdfSourceInputString.getRecommendations((String) null).size()); assertEquals(0, rdfSourceInputString.getRecommendations(new KnowledgeElement()).size()); } }
true
2aaf0cec9b71ac6189713a4bc886d215dfbe48ff
Java
crjcarlos1/FirebaseExample
/app/src/main/java/com/cralos/firebase2/RegisterAndLogIn/resetPassword/interactors/ResetPasswordInteractorImpl.java
UTF-8
1,795
2.546875
3
[]
no_license
package com.cralos.firebase2.RegisterAndLogIn.resetPassword.interactors; import androidx.annotation.NonNull; import com.cralos.firebase2.RegisterAndLogIn.resetPassword.interfaces.ResetPasswordInteractor; import com.cralos.firebase2.RegisterAndLogIn.resetPassword.interfaces.ResetPasswordPresenter; import com.cralos.firebase2.RegisterAndLogIn.resetPassword.utils.ResetPasswordUtils; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; public class ResetPasswordInteractorImpl implements ResetPasswordInteractor { private ResetPasswordPresenter presenter; private FirebaseAuth firebaseAuth; public ResetPasswordInteractorImpl(ResetPasswordPresenter presenter) { this.presenter = presenter; firebaseAuth = FirebaseAuth.getInstance(); } @Override public void resetPassword(String email) { if (ResetPasswordUtils.validateEmail(email)) { resetPassWithFirebase(email); } else { presenter.setMessageToView("Correo no válido"); } } private void resetPassWithFirebase(String email) { //establecemos idioma del correo que nos llegara para reestablecer el pass firebaseAuth.setLanguageCode("es"); firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { presenter.setMessageToView("Se envío un correo para reestablecer tu contraseña"); } else { presenter.setMessageToView(task.getException().getMessage()); } } }); } }
true
9025eddcbc4b3b06dad2f3ce04dac5526075f7be
Java
paop2016/Beats
/src/wang/beats/dao/Friend.java
UTF-8
731
2.5
2
[]
no_license
package wang.beats.dao; public class Friend { private int name; private int imgId; private String similar; private boolean isChecked; public boolean isChecked() { return isChecked; } public Friend( int imgId,int name,String similar) { super(); this.name = name; this.imgId = imgId; this.similar = similar; } public void setChecked(boolean isChecked) { this.isChecked = isChecked; } public int getName() { return name; } public void setName(int name) { this.name = name; } public int getImgId() { return imgId; } public void setImgId(int imgId) { this.imgId = imgId; } public String getSimilar() { return similar; } public void setSimilar(String similar) { this.similar = similar; } }
true
a5a036a46c8792cafddb241f60041f5185ae2495
Java
BarbaraEMCandido/Java
/exercicios_dia_3/QuantidadeParEImpar.java
ISO-8859-1
517
3.734375
4
[]
no_license
package exercicos_dia_3; import java.util.Scanner; public class QuantidadeParEImpar { public static void main(String args[]) { Scanner leia = new Scanner(System.in); int contPar = 0, contImpar = 0, x, i; for (i = 1; i <= 10; i++) { System.out.println("Digite um nmero: "); x = leia.nextInt(); if (x%2 == 0) { contPar++; } else { contImpar++; } } System.out.println("Foram digitados " + contPar + " nmeros pares e " + contImpar + " nmeros mpares." ); } }
true
a8f9e502b76b2d86866f8ea45396164a4f76018a
Java
s1ovak/hybris-commerce
/bin/custom/questions/src/org/training/facades/impl/DefaultQuestionFacade.java
UTF-8
1,566
2.3125
2
[]
no_license
package org.training.facades.impl; import de.hybris.platform.commercefacades.product.data.ProductData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.training.facades.QuestionFacade; import org.training.model.QuestionModel; import org.training.service.QuestionService; import questions.data.QuestionData; import java.util.stream.Collectors; @Component public class DefaultQuestionFacade implements QuestionFacade { private QuestionService questionService; @Autowired public DefaultQuestionFacade(QuestionService questionService) { this.questionService = questionService; } @Override public ProductData getProductDataWithQuestions(String productCode) { ProductData productData = new ProductData(); productData.setQuestions( questionService.getQuestionsByProduct(productCode).stream() .map(this::getQuestionData) .collect(Collectors.toList())); return productData; } private QuestionData getQuestionData(QuestionModel questionModel) { QuestionData questionData = new QuestionData(); questionData.setId(questionModel.getCode()); questionData.setQuestion(questionModel.getQuestion()); questionData.setAnswer(questionModel.getAnswer()); questionData.setQuestionCustomer(questionModel.getQuestionCustomer()); questionData.setAnswerCustomer(questionModel.getAnswerCustomer()); return questionData; } }
true
e6d16fde1c8d374645e522e1d7619f7f71ec3210
Java
2jerry/Android_Application
/app/src/main/java/andoridtown/org/application/MainActivity.java
UTF-8
1,266
2.15625
2
[]
no_license
package andoridtown.org.application; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public static final int REQUEST_CODE_ORDER = 100; public static final int REQUEST_CODE_CUSTOMER = 101; public static final int REQUEST_CODE_MANAGE = 102; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button orderBtn = (Button)findViewById(R.id.orderBtn); orderBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(),OrderActivity.class); intent.putExtra("titleMsg","주문 등록"); startActivityForResult(intent,REQUEST_CODE_ORDER); } }); Button customerBtn = (Button)findViewById(R.id.customerBtn); Button manageBtn = (Button)findViewById(R.id.manageBtn); } }
true
e79af346ad18d5fd405e0571c64ba6fbab9e731b
Java
doublekilled0062/leetcode
/src/LeetCode203.java
UTF-8
892
3.5625
4
[]
no_license
/** * 203. 移除链表元素 * * 删除链表中等于给定值 val 的所有节点。 * * 示例: * * 输入: 1->2->6->3->4->5->6, val = 6 * 输出: 1->2->3->4->5 */ public class LeetCode203 { public ListNode removeElements(ListNode head, int val) { if(head == null){ return null; } ListNode p = head; while (p.next != null){ if(p.next.val == val){ p.next = p.next.next; }else { p = p.next; } } return head.val == val ? head.next : head; } public static void main(String[] args) { int n = 0; for(int i = 2; i < 3000; i++){ if(i % 2 == 0 || i % 3 == 0 || i % 5 == 0){ n++; if(n == 1500){ System.out.println(i); } } } } }
true
e4725d2fc90029e66f1405cfadd3698c58a5c2ad
Java
xiaozhiliaoo/concurrency-practice
/cpj/src/main/java/chapter3/ParticleCanvas.java
UTF-8
780
3.203125
3
[]
no_license
package chapter3; import java.awt.*; /** * @author lili * @date 2020/5/30 21:16 * @description * @notes */ public class ParticleCanvas extends Canvas { private Particle[] particles = new Particle[0]; ParticleCanvas(int size) { setSize(new Dimension(size, size)); } // Intended to be called by applet synchronized void setParticles(Particle[] ps) { if (ps == null) throw new IllegalArgumentException("Cannot set null"); particles = ps; } protected synchronized Particle[] getParticles() { return particles; } public void paint(Graphics g) { // override Canvas.paint Particle[] ps = getParticles(); for (int i = 0; i < ps.length; ++i) ps[i].draw(g); } }
true
1e4f4d727e67ff29d14afa75de6a325d9dc7e0e1
Java
jodson/MusicOrganizer
/src/gui/PainelImagem.java
UTF-8
2,537
2.8125
3
[]
no_license
package gui; import java.awt.BorderLayout; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.imageio.stream.ImageInputStream; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import Facade.Facade; public class PainelImagem extends JPanel { private GridBagConstraints gbc; private JRadioButton radioURL; private JRadioButton radioArquivo; private Image imagemOriginal = null; private Facade facade; public PainelImagem() { gbc = new GridBagConstraints(); facade = Facade.getInstace(); initComponents(); } private void initComponents(){ Image imagem = getScaledImage(imagemOriginal, 150, 150); Box boxRadios = Box.createVerticalBox(); ButtonGroup grupoRadios = new ButtonGroup(); radioURL = new JRadioButton("pegar da URL",true); radioArquivo = new JRadioButton("pegar de um arquivo",false); grupoRadios.add(radioURL); grupoRadios.add(radioArquivo); boxRadios.add(radioURL); boxRadios.add(radioArquivo); this.setBorder(BorderFactory.createTitledBorder("Imagem")); this.setLayout(new BorderLayout()); this.add(new JLabel(new ImageIcon(imagem)),BorderLayout.CENTER); this.add(boxRadios,BorderLayout.SOUTH); } public void updateValues(byte[] image) { this.removeAll(); try { if (image != null) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image); ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream); imagemOriginal = ImageIO.read(imageInputStream); initComponents(); }else{ } } catch (IOException e) { e.printStackTrace(); } } private Image getScaledImage(Image imagemOriginal, int largura, int altura) { BufferedImage resizedImg = new BufferedImage(largura, altura, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(imagemOriginal, 0, 0,largura, altura, null); g2.dispose(); return resizedImg; } public JRadioButton getRadioURL() { return radioURL; } public JRadioButton getRadioArquivo() { return radioArquivo; } }
true
3af49f6547d8bb4db6d825e4fd25b9aea24ea392
Java
duha5h/oop
/src/oop/OOP.java
UTF-8
903
3.203125
3
[]
no_license
package oop; /** * * @author duhash */ public class OOP { public static void main(String[] args) { // TODO code application logic here Room room = new MyRoom("Duha"); room.setNumberOfWindow(1); System.out.println("Owner of this room is " + room.getOwner()); room.mainCore(); room.decoration(); room.clean(); System.out.println(""); room = new MyBrotherRoom("Ahmad & Osaid"); room.setNumberOfWindow(2); System.out.println("Owner of this room is " + room.getOwner()); room.mainCore(); room.decoration(); room.clean(); System.out.println(""); room = new MyMomRoom("Mom & Dad"); room.setNumberOfWindow(1); System.out.println("Owner of this room is " + room.getOwner()); room.mainCore(); room.decoration(); room.clean(); } }
true
43135eb31c97e607a911b06178ff27967b2eb98a
Java
ramyatannniru/000ggs-spring
/jdbc.application/src/main/java/com/gsd/spring/jdbc/application/App.java
UTF-8
626
2.203125
2
[]
no_license
package com.gsd.spring.jdbc.application; import java.util.List; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.bean.Employee; import com.spring.bean.EmployeeDao; /** * Hello world! * */ public class App { public static void main( String[] args ) { ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); EmployeeDao dao=context.getBean("eDao",EmployeeDao.class); dao.createEmployee(new Employee(1,"ramya")); System.out.println(dao.getAllEmployee().toString()); } }
true
96cedfb9f09a3e1504e7d17f415918c1007d2fe7
Java
Xemplar/Resource
/gdx-game/src/com/xemplar/games/android/resource/model/World.java
UTF-8
3,556
2.671875
3
[]
no_license
package com.xemplar.games.android.resource.model; import com.xemplar.games.android.resource.tiles.*; import com.badlogic.gdx.utils.*; import com.badlogic.gdx.math.*; import com.xemplar.games.android.resource.entities.*; public class World { private Array<Rectangle> collisionRects = new Array<Rectangle>(); private Array<Player> players = new Array<Player>(); private Level level; private Jaxon jaxon; public Array<Rectangle> getCollisionRects() { return collisionRects; } public Jaxon getJaxon(){ return (Jaxon) getPlayer(0); } public Player getPlayer(int index) { return players.get(index); } public Level getLevel() { return level; } public Array<Entity> getEntities(){ return level.getEntities(); } public Tile getTile(Vector2 pos){ Array<Tile> blocks = getTiles(level.getWidth(), level.getHeight()); for(Tile block : blocks){ if(block.getBounds().contains(pos)){ return block; } } return null; } public Tile getOvelayTile(Vector2 pos){ Array<Tile> blocks = getTiles(level.getWidth(), level.getHeight()); for(Tile block : blocks){ if(block.getBounds().contains(pos)){ return block; } } return null; } public Array<Tile> getTiles(int width, int height) { int x = (int)jaxon.getPosition().x - width; int y = (int)jaxon.getPosition().y - height; if (x < 0) { x = 0; } if (y < 0) { y = 0; } int x2 = x + 2 * width; int y2 = y + 2 * height; if (x2 > level.getWidth()) { x2 = level.getWidth() - 1; } if (y2 > level.getHeight()) { y2 = level.getHeight() - 1; } Array<Tile> tiles = new Array<Tile>(); Tile tile = null; for (int col = x; col <= x2; col++) { for (int row = y; row <= y2; row++) { if(col >= level.getWidth()) continue; if(row >= level.getHeight()) continue; tile = level.getTiles()[col + row * level.getWidth()]; if (tile != null) { tiles.add(tile); } } } return tiles; } public Array<Tile> getOverlayTiles(int width, int height) { int x = (int)jaxon.getPosition().x - width; int y = (int)jaxon.getPosition().y - height; if (x < 0) { x = 0; } if (y < 0) { y = 0; } int x2 = x + 2 * width; int y2 = y + 2 * height; if (x2 > level.getWidth()) { x2 = level.getWidth() - 1; } if (y2 > level.getHeight()) { y2 = level.getHeight() - 1; } Array<Tile> tiles = new Array<Tile>(); Tile tile = null; for (int col = x; col <= x2; col++) { for (int row = y; row <= y2; row++) { if(col >= level.getWidth()) continue; if(row >= level.getHeight()) continue; tile = level.getOverlayTiles()[col + row * level.getWidth()]; if (tile != null) { tiles.add(tile); } } } return tiles; } public World(int levelNum){ level = new GeneratedLevel(levelNum); jaxon = new Jaxon(level.jaxonStart); players.add(jaxon); } }
true
7164bc37988d77c3beff6e51bc1e9995dc9cf67b
Java
abchow/pathstore-all
/pathstore/src/main/java/pathstore/client/PathStoreClientAuthenticatedCluster.java
UTF-8
8,227
1.882813
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 pathstore.client; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import lombok.Getter; import lombok.NonNull; import org.json.JSONObject; import pathstore.authentication.credentials.ClientCredential; import pathstore.authentication.credentials.DeploymentCredential; import pathstore.authentication.grpc.PathStoreClientInterceptor; import pathstore.common.ApplicationLeaseCache; import pathstore.common.Constants; import pathstore.common.PathStoreProperties; import pathstore.system.logging.PathStoreLogger; import pathstore.system.logging.PathStoreLoggerFactory; import pathstore.util.ClusterCache; import pathstore.util.Pair; import pathstore.util.SchemaInfo; import java.util.Optional; /** * This class is the front facing class users will use to connect to their local pathstore node with * their application name and the associated master password. */ public class PathStoreClientAuthenticatedCluster { /** Logger */ private static final PathStoreLogger logger = PathStoreLoggerFactory.getLogger(PathStoreClientAuthenticatedCluster.class); /** * Local saved instance of this class. Passes application name and master password from the * properties file * * @see PathStoreProperties#applicationName * @see PathStoreProperties#applicationMasterPassword */ @Getter(lazy = true) private static final PathStoreClientAuthenticatedCluster instance = initInstance( PathStoreProperties.getInstance().applicationName, PathStoreProperties.getInstance().applicationMasterPassword); /** * This function is used to initialize the connection to the local node. You can call this * function more than once and it won't re-call the local node for initialization * * @param applicationName the application name you're trying to connect with * @param masterPassword the master password associated with your application * @return a connection instance if valid credentials are passed. * @see #instance */ private static PathStoreClientAuthenticatedCluster initInstance( @NonNull final String applicationName, @NonNull final String masterPassword) { Pair<Optional<String>, Optional<SchemaInfo>> response = PathStoreServerClient.getInstance() .registerApplicationClient(applicationName, masterPassword); Optional<String> credentialsOptional = response.t1; Optional<SchemaInfo> schemaInfoOptional = response.t2; if (credentialsOptional.isPresent()) { String credentials = credentialsOptional.get(); JSONObject responseObject = new JSONObject(credentials); if (responseObject .getEnum( Constants.REGISTER_APPLICATION.STATUS_STATES.class, Constants.REGISTER_APPLICATION.STATUS) .equals(Constants.REGISTER_APPLICATION.STATUS_STATES.VALID)) { if (schemaInfoOptional .isPresent()) { // check to ensure that the schema info object is present SchemaInfo schemaInfo = schemaInfoOptional.get(); SchemaInfo.setInstance(schemaInfo); return new PathStoreClientAuthenticatedCluster( new ClientCredential( applicationName, responseObject.getString(Constants.REGISTER_APPLICATION.USERNAME), responseObject.getString(Constants.REGISTER_APPLICATION.PASSWORD), responseObject.getBoolean(Constants.REGISTER_APPLICATION.IS_SUPER_USER))); } else throw new RuntimeException( "Schema info fetched is not present, this is a server error. Please ensure that you don't have version mismatches between the server and the client. Also ensure that you're running a stable version of the code base as with development versions you should expect that some functions don't work as expected. If you're a developer this is thrown on the grpc endpoint registerApplicationClient"); } else throw new RuntimeException(responseObject.getString(Constants.REGISTER_APPLICATION.REASON)); } else throw new RuntimeException( "Credentials fetched are not present, this is a server error. Please ensure that you don't have version mismatches between the server and the client. Also ensure that you're running a stable version of the code base as with development versions you should expect that some functions don't work as expected. If you're a developer this is thrown on the grpc endpoint registerApplicationClient"); } /** Credential used to connect */ private final ClientCredential credential; /** Cluster connection using client credentials */ private final Cluster cluster; /** Raw session */ private final Session rawSession; /** PathStoreSession created using cluster */ private final PathStoreSession psSession; /** * @param clientCredential client credential passed from the local node that is used to * communicate via cassandra and GRPC */ private PathStoreClientAuthenticatedCluster(final ClientCredential clientCredential) { this.credential = clientCredential; // As of now the client is considered connected and properly ready to communicate with the local // node PathStoreClientInterceptor.getInstance().setCredential(clientCredential); // All operations to perform after connection is complete LocalNodeInfo localNodeInfoFromServer = PathStoreServerClient.getInstance().getLocalNodeId(); // setup all the values for ps properties PathStoreProperties.getInstance().NodeID = localNodeInfoFromServer.getNodeId(); PathStoreProperties.getInstance().CassandraIP = localNodeInfoFromServer.getCassandraIP(); PathStoreProperties.getInstance().CassandraPort = localNodeInfoFromServer.getCassandraPort(); this.cluster = ClusterCache.createCluster( new DeploymentCredential( clientCredential.getUsername(), clientCredential.getPassword(), PathStoreProperties.getInstance().CassandraIP, PathStoreProperties.getInstance().CassandraPort)); // setup application lease cache for the provided application name ApplicationLeaseCache.getInstance() .setLease( clientCredential.getSearchable(), new ApplicationLeaseCache.ApplicationLease( 0, PathStoreServerClient.getInstance() .getApplicationLeaseTime(clientCredential.getSearchable()))); this.rawSession = this.cluster.connect(); this.psSession = new PathStoreSession(this.rawSession); if (this.credential.isSuperUser()) SchemaInfo.getInstance().setSession(this.rawSession); } /** @return local node db session */ public PathStoreSession connect() { return this.psSession; } /** @return raw session iff the user is a super user */ public Session connectRaw() { if (!this.credential.isSuperUser()) throw new RuntimeException("Only super user clients can use the raw session"); return this.rawSession; } /** Close session and cluster */ public void close() throws InterruptedException { PathStoreServerClient.getInstance().shutdown(); logger.debug("Shutdown grpc connection to local node"); this.rawSession.close(); logger.debug("Closed cassandra session"); this.cluster.close(); logger.debug("Closed cassandra cluster connection"); } }
true
4e1d9f0aea9ed96957ad8fb4ac9faa2627ae899f
Java
luongvietvinh/MD2-java-Thuc-Hanh-1
/src/Accsermodifier_Static_method_Static_5/TH_1_1.java
UTF-8
449
2.53125
3
[]
no_license
package Accsermodifier_Static_method_Static_5; public class TH_1_1 { public static void main(String[] args) { TH_1_Static_Method.change(); TH_1_Static_Method s1 = new TH_1_Static_Method(111 , "vinhdzai"); TH_1_Static_Method s2 = new TH_1_Static_Method(222 , "số hai"); TH_1_Static_Method s3 = new TH_1_Static_Method(333 , "số ba"); s1.display(); s2.display(); s3.display(); } }
true
7940215626da0ca552453ab0050ad3e45a4bb238
Java
carrliitos/CS366
/MySQLDemo/SimpleQueryDemo.java
UTF-8
2,129
2.828125
3
[]
no_license
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class SimpleQueryDemo { static final String databasePrefix ="cs366-2207_salazarbc24"; static final String netID ="salazarbc24"; // Please enter your netId static final String hostName ="washington.uww.edu"; //140.146.23.39 or washington.uww.edu static final String databaseURL ="jdbc:mariadb://" + hostName + "/" + databasePrefix; static final String password="bs0288"; // please enter your own password private Connection connection = null; private Statement statement = null; private ResultSet resultSet = null; public void Connection(){ try { Class.forName("org.mariadb.jdbc.Driver"); System.out.println("databaseURL"+ databaseURL); connection = DriverManager.getConnection(databaseURL, netID, password); System.out.println("Successfully connected to the database"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } // end of Connection public void simpleQuery(String sqlQuery) { try { statement = connection.createStatement(); resultSet = statement.executeQuery(sqlQuery); ResultSetMetaData metaData = resultSet.getMetaData(); int columns = metaData.getColumnCount(); for (int i=1; i<= columns; i++) { System.out.print(metaData.getColumnName(i)+"\t"); } System.out.println(); while (resultSet.next()) { for (int i=1; i<= columns; i++) { System.out.print(resultSet.getObject(i)+"\t\t"); } System.out.println(); } } catch (SQLException e) { e.printStackTrace(); } } // end of simpleQuery method public static void main(String args[]) { SimpleQueryDemo demoObj = new SimpleQueryDemo(); demoObj.Connection(); String sqlQuery ="select sname from Student where level = 'JR';"; demoObj.simpleQuery(sqlQuery); } }
true
90684ee2481874329d447ecddf68981dbd9d7ebc
Java
lnaut/proproPogClap
/ResultsPanel.java
UTF-8
848
2.9375
3
[]
no_license
import javax.swing.*; import java.awt.*; public class ResultsPanel extends JPanel { /** * A panel that lets you add a new result to the standings file. * The layout has to be programmed here in the constructor. */ public ResultsPanel(AbstractLeague t){ super(); // // TODO Aufgabe 5 // Die folgenden Widgets sollen platziert werden // JComboBox<String> teamselector1 = new JComboBox<String>(t.getTeamNames()); JComboBox<String> teamselector2 = new JComboBox<String>(t.getTeamNames()); JTextField scoreField1 = new JTextField(3); JTextField scoreField2 = new JTextField(3); JLabel statusLabel = new JLabel("Window initialized."); JButton addButton = new JButton("Add Result"); // add your code here } }
true
98c3b656dca0c1d826d2d263732617d58afe57ff
Java
linelect/TestStaticImportsOrder
/src/com/company/Main.java
UTF-8
407
1.921875
2
[]
no_license
package com.company; import static com.company.data.Class.*; import static com.company.data.Class.Byte; import static com.company.zata.Class2.Long; import static com.company.zata.Class2.*; public class Main { public static void main(String[] args) { System.out.println(Byte); System.out.println(Field2); System.out.println(Long); System.out.println(Field4); } }
true
4c287b1737ca81123d41b760ddd01d663a842b7d
Java
automatiko-io/automatiko-engine
/codegen/src/test/java/io/automatiko/engine/codegen/tests/ProcessTestUtils.java
UTF-8
1,001
2.09375
2
[ "Apache-2.0" ]
permissive
package io.automatiko.engine.codegen.tests; import static org.assertj.core.api.Assertions.assertThat; import io.automatiko.engine.api.workflow.ProcessInstance; import io.automatiko.engine.workflow.AbstractProcessInstance; class ProcessTestUtils { static void assertState(ProcessInstance<?> processInstance, int state) { assertThat(processInstance).isInstanceOf(AbstractProcessInstance.class); AbstractProcessInstance<?> abstractProcessInstance = (AbstractProcessInstance<?>) processInstance; assertThat(abstractProcessInstance.status()) .withFailMessage("ProcessInstance [%s] Status - Expected: %s - Got: %s", processInstance.id(), state, processInstance.status()) .isEqualTo(state); assertThat(abstractProcessInstance.processInstance().getState()) .withFailMessage("LegacyProcessInstance [%s] Status - Expected: %s - Got: %s", processInstance.id(), state, ((AbstractProcessInstance<?>) processInstance).processInstance().getState()) .isEqualTo(state); } }
true
cb092061f91a0ff3356b8b31af2fba24a279caa0
Java
xkkoNotFound/TomcatTest
/simpleTomcat/src/com/xkko/web/servlet/GetRequestBody.java
UTF-8
1,210
2.453125
2
[]
no_license
package com.xkko.web.servlet; 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 java.io.BufferedReader; import java.io.IOException; @WebServlet("/aaa") public class GetRequestBody extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println("..."); // BufferedReader br = request.getReader(); // String line; // while ((line = br.readLine()) != null) { // System.out.println(line); // } System.out.println("..."); String username = request.getParameter("username"); System.out.println(username); System.out.println("..."); String[] hobbies = request.getParameterValues("hobby"); for (String hobby : hobbies) { System.out.println(hobby); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
true
8398c2e869a48bb6d70524675685363f597d2783
Java
victor-axelsson/ID2208
/src/se/kth/ns/jobservicecompany/Company.java
UTF-8
9,586
1.859375
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.01.28 at 12:29:53 PM CET // package se.kth.ns.jobservicecompany; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="companyName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="website"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[hH][tT]{2}[pP]://[wW]{3}.*"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="numberOfEmployees" type="{http://www.w3.org/2001/XMLSchema}integer"/> * &lt;element name="office"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="lat"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;minInclusive value="0"/> * &lt;maxInclusive value="180"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="lng"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;minInclusive value="0"/> * &lt;maxInclusive value="180"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="officeName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "companyName", "website", "numberOfEmployees", "office" }) @XmlRootElement(name = "company") public class Company { @XmlElement(required = true) protected String companyName; @XmlElement(required = true) protected String website; @XmlElement(required = true) protected BigInteger numberOfEmployees; @XmlElement(required = true) protected Company.Office office; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Gets the value of the companyName property. * * @return * possible object is * {@link String } * */ public String getCompanyName() { return companyName; } /** * Sets the value of the companyName property. * * @param value * allowed object is * {@link String } * */ public void setCompanyName(String value) { this.companyName = value; } /** * Gets the value of the website property. * * @return * possible object is * {@link String } * */ public String getWebsite() { return website; } /** * Sets the value of the website property. * * @param value * allowed object is * {@link String } * */ public void setWebsite(String value) { this.website = value; } /** * Gets the value of the numberOfEmployees property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getNumberOfEmployees() { return numberOfEmployees; } /** * Sets the value of the numberOfEmployees property. * * @param value * allowed object is * {@link BigInteger } * */ public void setNumberOfEmployees(BigInteger value) { this.numberOfEmployees = value; } /** * Gets the value of the office property. * * @return * possible object is * {@link Company.Office } * */ public Company.Office getOffice() { return office; } /** * Sets the value of the office property. * * @param value * allowed object is * {@link Company.Office } * */ public void setOffice(Company.Office value) { this.office = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="lat"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;minInclusive value="0"/> * &lt;maxInclusive value="180"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="lng"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}decimal"> * &lt;minInclusive value="0"/> * &lt;maxInclusive value="180"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="officeName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "lat", "lng" }) public static class Office { @XmlElement(required = true) protected BigDecimal lat; @XmlElement(required = true) protected BigDecimal lng; @XmlAttribute(name = "officeName") protected String officeName; /** * Gets the value of the lat property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getLat() { return lat; } /** * Sets the value of the lat property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setLat(BigDecimal value) { this.lat = value; } /** * Gets the value of the lng property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getLng() { return lng; } /** * Sets the value of the lng property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setLng(BigDecimal value) { this.lng = value; } /** * Gets the value of the officeName property. * * @return * possible object is * {@link String } * */ public String getOfficeName() { return officeName; } /** * Sets the value of the officeName property. * * @param value * allowed object is * {@link String } * */ public void setOfficeName(String value) { this.officeName = value; } } }
true
f553bcb75e234373fa5861da1e7240d3fa7b6da4
Java
Phalyst/dagacube
/src/main/java/rank/interactive/dagacube/repository/PlayerDetailsRepository.java
UTF-8
480
1.90625
2
[]
no_license
package rank.interactive.dagacube.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import rank.interactive.dagacube.model.PlayerDetails; import java.util.Optional; @Repository public interface PlayerDetailsRepository extends JpaRepository<PlayerDetails, Long>{ Optional<PlayerDetails> findByPlayerName(String playerName); }
true
5f0914409b96dae1b84597813b7ea2a1817506b0
Java
sindicate/solidstack.old
/src/funny/Symbol.java
UTF-8
1,251
3.25
3
[ "Apache-2.0" ]
permissive
package funny; import java.lang.ref.WeakReference; import java.util.WeakHashMap; public class Symbol { static private WeakHashMap<String,WeakReference<Symbol>> symbols = new WeakHashMap<String,WeakReference<Symbol>>(); static public Symbol apply( String name ) { synchronized( symbols ) { WeakReference<Symbol> symbol = symbols.get( name ); Symbol result; if( symbol != null ) { result = symbol.get(); if( result != null ) return result; // else: Symbol is lost, and the original key can't be retrieved, so we need to overwrite it completely symbols.remove( name ); // Needed because put() will not replace the key if it already exists } // else: Key is lost or never existed, which means that the symbol does not exist or never existed result = new Symbol( name ); symbols.put( name, new WeakReference<Symbol>( result ) ); return result; } } String name; private int hashCode; Symbol( String name ) { this.name = name; this.hashCode = name.hashCode(); } Symbol( String name, int hashCode ) { this.name = name; this.hashCode = hashCode; } @Override public String toString() { return this.name; } @Override public int hashCode() { return this.hashCode; } }
true
cd6e28463f286ce111f4bf89d6cf47906fe3e418
Java
iamhuwjones/hermes
/corvus-ebms-admin/src/main/java/hk/hku/cecid/ebms/admin/listener/MessageHistoryOraclePageletAdaptor.java
UTF-8
1,046
1.875
2
[ "BSD-2-Clause" ]
permissive
package hk.hku.cecid.ebms.admin.listener; import hk.hku.cecid.ebms.spa.EbmsProcessor; import hk.hku.cecid.ebms.spa.dao.MessageDAO; import hk.hku.cecid.ebms.spa.dao.MessageDVO; import hk.hku.cecid.ebms.spa.handler.MessageClassifier; import hk.hku.cecid.piazza.commons.dao.DAOException; import hk.hku.cecid.piazza.commons.util.PropertyTree; import hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor; import java.util.Iterator; /** * @author Donahue Sze * */ public class MessageHistoryOraclePageletAdaptor extends MessageHistoryPageletAdaptor { private Iterator findMessageWithPagination(MessageDVO data, MessageDAO messageDAO, int numberOfMessage, int offset,int displayLastInt, boolean isTime) throws DAOException{ if(!isTime){ // oracle only return messageDAO.findMessagesByHistory(data, numberOfMessage + offset, offset).iterator(); }else{ // oracle only return messageDAO.findMessagesByTime(displayLastInt,data, numberOfMessage + offset, offset).iterator(); } } }
true
7c590c5149f0dd8072d610646a1dc1f8ae0905d6
Java
valenciasitompul/HRProject
/src/controllers/EmployeesController.java
UTF-8
2,438
2.578125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import daos.EmployeesDAO; import icontrollers.IEmployeesController; import idaos.IEmployeesDAO; import java.sql.Connection; import java.util.List; import models.Employees; /** * * @author HARRY-PC */ public class EmployeesController implements IEmployeesController{ private IEmployeesDAO iemdao; public EmployeesController(Connection connection){ iemdao = new EmployeesDAO(connection); } @Override public List<Employees> getAll() { return iemdao.getAll(); } @Override public List<Employees> getById(String id) { return iemdao.getById(Integer.parseInt(id)); } public List<Employees> getByName(String name) { return iemdao.getByName(name); } @Override public List<Employees> search(String key) { return iemdao.search(key); } @Override public String insert(String id, String fname, String lname, String email, String pNumber, String hireDate, String jobId, String salary, String commissionPct, String managerId, String departmentId) { String result = ""; Employees emp = new Employees(Integer.parseInt(id),fname, lname, email, pNumber, hireDate, jobId, Integer.parseInt(salary), Integer.parseInt(commissionPct), Integer.parseInt(managerId), Integer.parseInt(departmentId)); if(iemdao.insert(emp)){ result = "Data berhasil disimpan"; }else{ result = "Maaf Data gagal disimpan"; } return result; } @Override public String update(String id, String salary) { String result = ""; Employees emp = new Employees(Integer.parseInt(id), Integer.parseInt(salary)); if(iemdao.update(emp)){ result = "Data berhasil diupdate"; }else{ result = "Maaf Data gagal diupdate"; } return result; } @Override public String delete(String id) { String result = ""; if(iemdao.delete(Integer.parseInt(id))){ result = "Data berhasil dihapus"; }else{ result = "maaf data gagal dihapus"; } return result; } }
true
3be32cf0dd528839b95ae874308c4407155dfd4e
Java
shaharyar-shamshi/ds-and-algo
/knapsackrecursion/src/knapsackrecursion/Knapsackrecursion.java
UTF-8
2,453
3.1875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package knapsackrecursion; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author shaharyar */ public class Knapsackrecursion { /** * @param args the command line arguments */ public static void main(String[] args) { FastReader in = new FastReader(); int item = in.nextInt(); int[] weight = new int[item]; int[] price = new int[item]; for (int i = 0; i < item; i++) { weight[i] = in.nextInt(); } for (int i = 0; i < item; i++) { price[i] = in.nextInt(); } int weightreq = in.nextInt(); Knapsackrecursion k = new Knapsackrecursion(); int ans = k.knapsack(weight, price, item, weightreq); System.out.println(ans); } int knapsack(int[] weight, int[] p, int item, int weightreq) { if (item == 0 || weightreq == 0) { return 0; } else { int inc = 0, exc = 0; if (weight[item - 1] <= weightreq) { inc = p[item - 1] + knapsack(weight, p, item - 1, weightreq - weight[item - 1]); } exc = 0 + knapsack(weight, p, item - 1, weightreq); if (inc > exc) { return inc; } else { return exc; } } } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
true
89fffcc50e3402bd9f8779466eef99ce97f3ebd7
Java
feralemos/geronimolemos
/Televisao/src/televisao/Televisao.java
UTF-8
5,183
2.734375
3
[]
no_license
package televisao; import javax.swing.JOptionPane; public class Televisao { public static void main(String[] args) { Ator a = new Ator(); int opcao = 0; while (opcao != 5) { opcao = Integer.parseInt(JOptionPane.showInputDialog("SELECIONE A OPERAÇÃO DESEJADA: \n" + "1 - Atividade ATOR\n" + "2 - Atividade NOVELA\n" + "3 - Atividade EMISSORA\n" + "4 - Atividade APRESENTADOR\n" + "5 - SAIR")); switch (opcao) { case 1: { a.setNome(JOptionPane.showInputDialog("Informe o seu nome:")); a.setNomeartistico(JOptionPane.showInputDialog("Informe o seu nome artístico:")); a.setDatadenascimento(JOptionPane.showInputDialog("Informe a sua data de nascimento:")); a.setEmail(JOptionPane.showInputDialog("Informe o seu e-mail:")); a.setNumeronovelas(Integer.parseInt(JOptionPane.showInputDialog("Informe o número de novelas trabalhadas"))); a.setSalariomensal(Double.parseDouble(JOptionPane.showInputDialog("Informe o seu salário mensal:"))); a.setNumeveneto(Integer.parseInt(JOptionPane.showInputDialog("Informe o número de eventos particpados este mês:"))); a.setCacheevento(Double.parseDouble(JOptionPane.showInputDialog("Informe o cache recebido por evento"))); JOptionPane.showMessageDialog(null, "Nome :" + a.getNome() + "\n Nome Artístico :" + a.getNomeartistico() + "\n Data de nascimento :" + a.getDatadenascimento() + "\n E-mail :" + a.getEmail() + "\nNúmero de trabalhos em novelas :" + a.getNumeronovelas() + "\n Status :" + a.statusator() + "\nGanho total no mês :" + a.calcularganhos()); break; } case 2: { a.setNome(JOptionPane.showInputDialog("Informe o nome da novela")); a.setTelespectadores(Integer.parseInt(JOptionPane.showInputDialog("Informe o número de telespectadores que assistiram a novela"))); a.setOpcao(JOptionPane.showInputDialog("De acordo com o conteúdo da novela, escolha a opção que se aplica melhor ao programa:" + "\n 1- Violência(NÃO) - Sexo (NÃO) - Drogas (NÃO) \n 2- Violência (SIM) - Sexo (NÃO) - Drogas (NÃO)" + "\n 3- Violência (SIM) - Sexo(SIM/NÃO) - Drogas (SIM) \n 4- Violência (SIM) - Sexo (SIM) - Drogas (SIM)")); JOptionPane.showMessageDialog(null, "Nome do programa:" + a.getNome() + "\nA classificação do programa é :" + a.novela() + "\n Pontos do IBOPE:" + a.audiencia()); break; } case 3: { a.setEmissoranome(JOptionPane.showInputDialog("Informe o nome da emissora")); a.setEmissoraendereco(JOptionPane.showInputDialog("Informe o endereço da emissora")); String abertafechada = JOptionPane.showInputDialog("Aberta ou fechada(SIM/NÃO)"); if (abertafechada.equals("SIM")) { a.setAberta(true); } else { a.setAberta(false); } String exibe; if (a.isAberta() == true) { exibe = "ABERTA"; } else { exibe = "FECHADA"; } JOptionPane.showMessageDialog(null, "Dados da emissora: \n" + "Nome:" + a.getEmissoranome() + "\n" + "Endereço:" + a.getEmissoraendereco() + "\n" + "Aberta ou fechada:" + exibe); break; } case 4: { a.setSalariomensal(Double.parseDouble(JOptionPane.showInputDialog("Informe o seu salário mensal:"))); a.setNumeveneto(Integer.parseInt(JOptionPane.showInputDialog("Informe o número de eventos particpados este mês:"))); a.setCacheevento(Double.parseDouble(JOptionPane.showInputDialog("Informe o cache recebido por evento"))); a.setNumeromerchant(Integer.parseInt(JOptionPane.showInputDialog("Informe o número de trabalhos publicitário feitos"))); a.setValormerchant(Double.parseDouble(JOptionPane.showInputDialog("Informe o valor cobrado pelos eventos publicitário"))); JOptionPane.showMessageDialog(null, "O salário total do apresentador é:" + a.apresentador()); break; } case 5:{ JOptionPane.showMessageDialog(null,"Até mais ver"); break; } default:{ JOptionPane.showMessageDialog(null,"Opção inválida!!!"); } } } } }
true
e50e4e20a4b9f5150ceca91da5d2b8e975006f5f
Java
leandroliveira/desafio-concrete
/src/main/java/com/app/desafioconcrete/api/service/impl/UserServiceImpl.java
UTF-8
4,501
2.390625
2
[]
no_license
package com.app.desafioconcrete.api.service.impl; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.UUID; import javax.validation.ConstraintViolationException; import org.apache.tomcat.util.ExceptionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.app.desafioconcrete.api.dto.LoginDTO; import com.app.desafioconcrete.api.dto.ProfileDTO; import com.app.desafioconcrete.api.dto.UserDTO; import com.app.desafioconcrete.api.entities.Phone; import com.app.desafioconcrete.api.entities.User; import com.app.desafioconcrete.api.exceptions.ExcecaoSessaoInvalida; import com.app.desafioconcrete.api.exceptions.ExcecaoTokenInexistente; import com.app.desafioconcrete.api.exceptions.ExcecaoUsuarioCadastrado; import com.app.desafioconcrete.api.exceptions.ExcecaoUsuarioInvalido; import com.app.desafioconcrete.api.repository.PhoneRepository; import com.app.desafioconcrete.api.repository.UserRepository; import com.app.desafioconcrete.api.service.UserService; @Service public class UserServiceImpl implements UserService{ @Autowired private UserRepository userRepository; @Autowired private PhoneRepository phoneRepository; @Override public UserDTO createUser(User pUser){ UserDTO userDTO = new UserDTO(); try { User user = userRepository.findByEmail(pUser.getEmail()); if(user != null) { throw new ExcecaoUsuarioCadastrado(); } pUser.setCriated(LocalDate.now()); pUser.setModified(LocalDateTime.now()); pUser.setLast_login(LocalDateTime.now()); pUser.generateToken(); //So criptografa o password se vier preenchido if(!pUser.getPassword().equals("")) { pUser.setPassword(this.getEncrypted(pUser.getPassword())); } user = userRepository.save(pUser); //linkamos os telefones com os usuarios if (pUser.getPhones() != null && !pUser.getPhones().isEmpty()) { for (Phone phone : pUser.getPhones()) { phone.setUser(user); } phoneRepository.saveAll(pUser.getPhones()); } BeanUtils.copyProperties(user, userDTO); return userDTO; } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { e.printStackTrace(); } return userDTO; } @Override public UserDTO loginUser(LoginDTO pLoginDTO) throws NoSuchAlgorithmException, UnsupportedEncodingException, ExcecaoUsuarioInvalido { User user = this.userRepository.findByEmail(pLoginDTO.getEmail()); if(user == null) { //Excecao mapeada no ResourceExceptionHandler para devolver o cod 401 throw new ExcecaoUsuarioInvalido(); } //Caso a senha esteja diferente do banco de dados if(!this.getEncrypted(pLoginDTO.getPassword()).equals(user.getPassword())){ //Excecao mapeada no ResourceExceptionHandler para devolver o cod 401 throw new ExcecaoUsuarioInvalido(); } user.setLast_login(LocalDateTime.now()); this.userRepository.save(user); UserDTO userDTO = new UserDTO(); BeanUtils.copyProperties(user, userDTO); return userDTO; } @Override public UserDTO getProfile(ProfileDTO pProfileDTO) throws ExcecaoTokenInexistente, ExcecaoSessaoInvalida{ User userByToken = this.userRepository.findByToken(UUID.fromString(pProfileDTO.getToken())); if(userByToken == null) { throw new ExcecaoTokenInexistente(); } User userById = this.userRepository.findById(UUID.fromString(pProfileDTO.getId())); if(userById != null) { if(userById.getToken().compareTo(userByToken.getToken()) != 0) { //Caso o token do usuario seja diferente do passado como parametro throw new ExcecaoTokenInexistente(); } else if(LocalDateTime.now().minusMinutes(30).compareTo(userById.getLast_login()) > 0) { //Caso a sessao tenha estourado o tempo throw new ExcecaoSessaoInvalida(); } } else { throw new ExcecaoTokenInexistente(); } UserDTO userDTO = new UserDTO(); BeanUtils.copyProperties(userById, userDTO); return userDTO; } //Encripta a senha passada como parametro no formato SHA-256 @Override public String getEncrypted(String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(pPassword.getBytes()); return UUID.nameUUIDFromBytes(md.digest()).toString(); } }
true
8639a33de9e85f983787cb5ee72282c71b367ce8
Java
lycfr/lq
/app/src/main/java/com/google/android/gms/location/places/internal/zzaq.java
UTF-8
990
1.71875
2
[]
no_license
package com.google.android.gms.location.places.internal; import android.os.RemoteException; import com.google.android.gms.common.api.Api; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.places.zzd; import com.google.android.gms.location.places.zze; final class zzaq extends zze<zzm> { private /* synthetic */ int zzbla; private /* synthetic */ int zzblb; private /* synthetic */ zzap zzblc; /* JADX INFO: super call moved to the top of the method (can break code semantics) */ zzaq(zzap zzap, Api api, GoogleApiClient googleApiClient, int i, int i2) { super(api, googleApiClient); this.zzblc = zzap; this.zzbla = i; this.zzblb = i2; } /* access modifiers changed from: protected */ public final /* synthetic */ void zza(Api.zzb zzb) throws RemoteException { ((zzm) zzb).zza(new zzd((zze) this), this.zzblc.zzbkY, this.zzbla, this.zzblb, this.zzblc.mIndex); } }
true
882c100487d2b5e363d48563a2fcbdaf4cb2d7a3
Java
BinSlashBash/xcrumby
/src-v2/com/squareup/okhttp/internal/huc/CacheAdapter.java
UTF-8
1,976
2.09375
2
[]
no_license
/* * Decompiled with CFR 0_110. */ package com.squareup.okhttp.internal.huc; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.squareup.okhttp.internal.InternalCache; import com.squareup.okhttp.internal.http.CacheStrategy; import com.squareup.okhttp.internal.huc.JavaApiConverter; import java.io.IOException; import java.net.CacheRequest; import java.net.CacheResponse; import java.net.ResponseCache; import java.net.URI; import java.net.URLConnection; import java.util.List; import java.util.Map; public final class CacheAdapter implements InternalCache { private final ResponseCache delegate; public CacheAdapter(ResponseCache responseCache) { this.delegate = responseCache; } private CacheResponse getJavaCachedResponse(Request request) throws IOException { Map<String, List<String>> map = JavaApiConverter.extractJavaHeaders(request); return this.delegate.get(request.uri(), request.method(), map); } @Override public Response get(Request request) throws IOException { CacheResponse cacheResponse = this.getJavaCachedResponse(request); if (cacheResponse == null) { return null; } return JavaApiConverter.createOkResponse(request, cacheResponse); } public ResponseCache getDelegate() { return this.delegate; } @Override public CacheRequest put(Response object) throws IOException { URI uRI = object.request().uri(); object = JavaApiConverter.createJavaUrlConnection((Response)object); return this.delegate.put(uRI, (URLConnection)object); } @Override public void remove(Request request) throws IOException { } @Override public void trackConditionalCacheHit() { } @Override public void trackResponse(CacheStrategy cacheStrategy) { } @Override public void update(Response response, Response response2) throws IOException { } }
true
80210dd360c481f1cb3fe4adbd3fa80d2a9ba462
Java
hakat0m/Chessboxing
/com.gumtree.android.beta/java/com/gumtree/android/common/http/CapiUrl.java
UTF-8
891
1.515625
2
[]
no_license
package com.gumtree.android.common.http; public final class CapiUrl { public static final String EDIT_AD = "users/%s/ads/%s"; public static final String LOCATION_URL_DEPTH = "locations/%s.json"; public static final String MANAGE_AD = "users/%s/ads/%s.json?_in=title,description,email,phone,poster-contact-email,price-frequency,neighborhood,category,locations,price,pictures,attributes,visible-on-map,poster-contact-name,features-active"; public static final String METADATA_POST = "ads/metadata/%s.json"; public static final String METADATA_POST_LIMIT = "ads/metadata/%s.json?_in=description"; public static final String POST_AD = "users/%s/ads"; public static final String SUGGESTION_ADS = "suggestions/ads.json"; private CapiUrl() { } public static String getUrl(String str, Object... objArr) { return String.format(str, objArr); } }
true
f5158f5385771b791884a182d4e5f466f9c9173b
Java
Skrallexxx/TheOldOne822Minecraftmods
/theoldone822/SimpleOresEW/Items/ItemExtendedSword.java
UTF-8
3,783
2.109375
2
[]
no_license
package theoldone822.SimpleOresEW.Items; import static theoldone822.SimpleOresEW.SimpleOresEW.extendedValues.increaseSwordDamage; import static theoldone822.SimpleOresEW.SimpleOresEW.extendedValues.increaseSwordDurability; import static theoldone822.SimpleOresEW.SimpleOresEW.extendedValues.increaseSwordMiningSpeed; import java.lang.reflect.Field; import theoldone822.SimpleOresEW.SimpleOresEW; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; public class ItemExtendedSword extends ItemSword { protected EnumToolMaterial ewToolMaterial; protected float exWeaponDamage; public ItemExtendedSword(int par1, EnumToolMaterial par2EnumToolMaterial) { super(par1, par2EnumToolMaterial); this.ewToolMaterial = par2EnumToolMaterial; setMaxDamage((int)(getMaxDamage() * increaseSwordDurability)); exWeaponDamage = 5 + par2EnumToolMaterial.getDamageVsEntity() * 2; } @Override public Multimap getItemAttributeModifiers() { Multimap multimap = HashMultimap.create(); multimap.put(SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(), new AttributeModifier(field_111210_e, "Weapon modifier", (double)this.exWeaponDamage, 0)); return multimap; } @Override public float getStrVsBlock(ItemStack par1ItemStack, Block par2Block) { return (int)(super.getStrVsBlock(par1ItemStack, par2Block) * increaseSwordMiningSpeed); } /** * Adds special effects to the Fyrite and Illumenite Swords. */ @Override public boolean hitEntity(ItemStack par1ItemStack, EntityLivingBase par2EntityLivingBase, EntityLivingBase par3EntityLivingBase) { if (itemID == SimpleOresEW.extendedfyriteSword.itemID) { par1ItemStack.damageItem(1, par3EntityLivingBase); par2EntityLivingBase.setFire(100); } if (itemID == SimpleOresEW.extendedillumeniteSword.itemID) { par1ItemStack.damageItem(1, par3EntityLivingBase); par3EntityLivingBase.addPotionEffect(new PotionEffect(Potion.nightVision.id, 3600)); par2EntityLivingBase.addPotionEffect(new PotionEffect(Potion.blindness.id, 60)); if (!(par2EntityLivingBase instanceof EntityPlayer)) { par2EntityLivingBase.addPotionEffect(new PotionEffect(Potion.moveSlowdown.id, 200, 3)); } } par1ItemStack.damageItem(1, par3EntityLivingBase); return true; } @Override public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10) { if (itemID == SimpleOresEW.extendedfyriteSword.itemID) { if (par7 == 0) { --par5; } if (par7 == 1) { ++par5; } if (par7 == 2) { --par6; } if (par7 == 3) { ++par6; } if (par7 == 4) { --par4; } if (par7 == 5) { ++par4; } if (!par2EntityPlayer.canPlayerEdit(par4, par5, par6, par7, par1ItemStack)) { return false; } else { int var11 = par3World.getBlockId(par4, par5, par6); if (var11 == 0) { par3World.playSoundEffect((double) par4 + 0.5D, (double) par5 + 0.5D, (double) par6 + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); par3World.setBlock(par4, par5, par6, Block.fire.blockID); } return true; } } return true; }}
true
704753dad7ae26e43b03afe44b26aaed16cc716c
Java
Aracelli/Apprende
/app/src/main/java/com/example/carolinabarria/apprende/Layout3.java
UTF-8
1,433
2.375
2
[]
no_license
package com.example.carolinabarria.apprende; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; public class Layout3 extends AppCompatActivity implements View.OnClickListener{ RadioButton rb_euro, rb_moneda, rb_dolar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout3); rb_euro = (RadioButton) findViewById(R.id.rb_euro); rb_moneda = (RadioButton) findViewById(R.id.rb_moneda); rb_dolar = (RadioButton) findViewById(R.id.rb_dolar); rb_euro.setOnClickListener(this); rb_moneda.setOnClickListener(this); rb_dolar.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.rb_euro: Intent intent = new Intent(Layout3.this,Puntaje.class); startActivity(intent); break; case R.id.rb_moneda: Intent intent1 = new Intent(Layout3.this, Puntaje.class); startActivity(intent1); break; case R.id.rb_dolar: Intent intent2 = new Intent(Layout3.this,Puntaje.class); startActivity(intent2); break; } } }
true
1ddbcd6bb99f79a08bed67a44a5d841e7a2d6151
Java
cau-se/theodolite
/theodolite-benchmarks/uc4-hazelcastjet/src/main/java/rocks/theodolite/benchmarks/uc4/hazelcastjet/Uc4ConfigurationKeys.java
UTF-8
618
1.648438
2
[ "Apache-2.0" ]
permissive
package rocks.theodolite.benchmarks.uc4.hazelcastjet; /** * Configuration Keys used for Hazelcast Jet Benchmark implementations. */ public class Uc4ConfigurationKeys { public static final String KAFKA_OUTPUT_TOPIC = "kafka.output.topic"; public static final String KAFKA_CONFIGURATION_TOPIC = "kafka.configuration.topic"; public static final String KAFKA_FEEDBACK_TOPIC = "kafka.feedback.topic"; public static final String EMIT_PERIOD_MS = "emit.period.ms"; public static final String GRACE_PERIOD_MS = "grace.period.ms"; public static final String TRIGGER_INTERVAL_MS = "trigger.interval.ms"; }
true
cea1e5e57b53da66f8f90eea8d6dfe3c1db0d0ca
Java
xeolabs/vglviewer
/src/main/java/com/neocoders/vglviewer/vglRenderer/VGLDocumentRenderer.java
UTF-8
3,032
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
package com.neocoders.vglviewer.vglRenderer; import com.neocoders.vglviewer.vglDocument.*; /** * Renders a VGLDocument. A VGLDocumentRenderer has a viewport, a window, and may be given a document and a rendering * strategy. When rendering, document elements intersecting the viewport are mapped to the window and rendered with the * rendering strategy, which is a user-supplied implementation of VGLAbstractRenderingStrategy. */ public class VGLDocumentRenderer { /** * Initialise renderer. The renderer has a default viewport of (0,0,1,1) and a window of (0,0,1,1). Until a VGLDocument * and a VGLRenderingStrategy has been supplied, render() will do nothing. */ public VGLDocumentRenderer() { renderContext = new RenderContext(); renderStrategy = null; document = null; gridLines = new GridLines(100); } /** Specify viewport. The renderer will then render only the elements which intersect the viewport. */ public void setViewport(VGLViewport viewport) { renderContext.setViewport(viewport); } /** Specify window on physical device in which to render document elements that intersect the viewport. */ public void setWindow(VGLWindow window) { renderContext.setWindow(window); } /** Specify a strategy with which to render document elements on the physical device. */ public void setRenderStrategy(VGLRenderingStrategy renderStrategy) { this.renderStrategy = renderStrategy; } /** Specify a document to render */ public void setDocument(VGLDocument document) { this.document = document; } /** * Render elements of the document that intersect the viewport in the window, using the rendering strategy. * Does nothing if no document or rendering strategy has been specified. */ public void render() { if (document == null || renderStrategy == null) { return; } try { VGLElementRenderer elementRenderer = new VGLElementRenderer(renderContext, renderStrategy); VGLViewport viewport = this.renderContext.getViewport(); document.visitElements( new VGLBoundary(viewport.xmin, viewport.ymin, viewport.xmax, viewport.ymax), elementRenderer); gridLines.render(renderContext, renderStrategy); } catch (Exception e) { e.printStackTrace(); } } /** * @clientCardinality 1 * @supplierCardinality 1 */ private RenderContext renderContext; /** * @clientCardinality 1 * @supplierCardinality 1 * @supplierRole renderStrategy */ private VGLRenderingStrategy renderStrategy; private VGLDocument document; private String statusMessage; /** * @supplierCardinality 1 * @link aggregationByValue */ private GridLines gridLines; /** * @clientCardinality 1 * @supplierCardinality 1 */ private VGLElementRenderer lnkElementRenderer; }
true
44d1e54c339b9aaab55997fad16f518b21cd8eed
Java
stuarthendren/Jung-Extensions
/jung-extensions/src/main/java/net/stuarthendren/jung/dendrogram/Dendrogram.java
UTF-8
694
2.875
3
[ "MIT" ]
permissive
package net.stuarthendren.jung.dendrogram; import java.util.Iterator; import net.stuarthendren.jung.partition.Partition; /** * A dendrogram encodes a hierarchical clustering of a set of objects. * * Each level of the clustering is a {@link Partition} of the set of objects (of type T). Each level must cover the * previous see {@link Partition#covers(Partition)}. * * @author Stuart Hendren * * @param <T> */ public interface Dendrogram<T> { /** * @return an iterator of the partitions starting from the partition that contains each object as a single cluster * and ending with the partition that contains a single cluster. */ Iterator<Partition<T>> getPartitions(); }
true
188062d7b70332e070e8c6fdf01104b05bf45a84
Java
BackupTheBerlios/myrian-svn
/archive/rhs/src/com/redhat/persistence/pdl/nodes/ObjectTypeNd.java
UTF-8
3,368
1.9375
2
[]
no_license
/* * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved. * * The contents of this file are subject to the CCM Public * License (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.redhat.com/licenses/ccmpl.html. * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language * governing rights and limitations under the License. * */ package com.redhat.persistence.pdl.nodes; /** * ObjectType * * @author Rafael H. Schloming &lt;rhs@mit.edu&gt; * @version $Revision: #3 $ $Date: 2004/05/02 $ **/ public class ObjectTypeNd extends Node { public final static String versionId = "$Id: //users/rhs/persistence/src/com/redhat/persistence/pdl/nodes/ObjectTypeNd.java#3 $ by $Author: rhs $, $DateTime: 2004/05/02 13:12:27 $"; public static final Field NAME = new Field(ObjectTypeNd.class, "name", IdentifierNd.class, 1, 1); public static final Field EXTENDS = new Field(ObjectTypeNd.class, "extends", TypeNd.class, 0, 1); public static final Field CLASS = new Field(ObjectTypeNd.class, "class", JavaClassNd.class, 0, 1); public static final Field ADAPTER = new Field(ObjectTypeNd.class, "adapter", JavaClassNd.class, 0, 1); public static final Field PROPERTIES = new Field(ObjectTypeNd.class, "properties", PropertyNd.class); public static final Field OBJECT_KEY = new Field(ObjectTypeNd.class, "objectKey", ObjectKeyNd.class, 0, 1); public static final Field REFERENCE_KEY = new Field(ObjectTypeNd.class, "referenceKey", ReferenceKeyNd.class, 0, 1); public static final Field UNIQUE_KEYS = new Field(ObjectTypeNd.class, "uniqueKeys", UniqueKeyNd.class); public static final Field AGGRESSIVE_LOAD = new Field(ObjectTypeNd.class, "aggressiveLoad", AggressiveLoadNd.class, 0, 1); public static final Field JOIN_PATHS = new Field(ObjectTypeNd.class, "joinPaths", JoinPathNd.class); public static final Field EVENTS = new Field(ObjectTypeNd.class, "events", EventNd.class); private boolean m_isVersioned; public void dispatch(Switch sw) { super.dispatch(sw); sw.onObjectType(this); } public String getQualifiedName() { return getFile().getModel().getName() + "." + getName().getName(); } public IdentifierNd getName() { return (IdentifierNd) get(NAME); } public void setVersioned() { m_isVersioned = true; } public boolean isVersioned() { return m_isVersioned; } public TypeNd getExtends() { return (TypeNd) get(EXTENDS); } public ReferenceKeyNd getReferenceKey() { return (ReferenceKeyNd) get(REFERENCE_KEY); } public ObjectKeyNd getObjectKey() { return (ObjectKeyNd) get(OBJECT_KEY); } private boolean m_returns = false; public boolean hasReturns() { return m_returns; } public void setReturns(boolean value) { m_returns = value; } public JavaClassNd getJavaClass() { return (JavaClassNd) get(CLASS); } public JavaClassNd getAdapterClass() { return (JavaClassNd) get(ADAPTER); } }
true
8cb76c967d6649396743328e935c3c90184f46ea
Java
DoergeEmanuel/FI11Java
/FI11Java/src/autohaus/View.java
UTF-8
5,984
2.484375
2
[]
no_license
package autohaus; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JList; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JComboBox; import javax.swing.JButton; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class View extends JFrame { private JPanel contentPane; private JList listBestellung; private JLabel labelLogo; private JLabel labelAuswahl; private JLabel labelModel; private JLabel labelFarbe; private JLabel labelPS; private JLabel labelExtras; private JComboBox comboBoxModell; private JComboBox comboBoxFarbe; private JComboBox comboBoxPs; private JComboBox comboBoxExtras; private JButton buttonBestaetigen; private JLabel labelPreisNetto; private JLabel labelMWSt; private JLabel labelPreisBrutto; private JLabel labelWertPreisNetto; private JLabel labelWertMWSt; private JLabel labelWertPreisBrutto; private JButton buttonBestellen; public View() { initialize(); setBounds(100, 100, 645, 432); } private void initialize() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); contentPane.add(getListBestellung()); contentPane.add(getLabelLogo()); contentPane.add(getLabelAuswahl()); contentPane.add(getLabelModel()); contentPane.add(getLabelFarbe()); contentPane.add(getLabelPS()); contentPane.add(getLabelExtras()); contentPane.add(getComboBoxModell()); contentPane.add(getComboBoxFarbe()); contentPane.add(getComboBoxPs()); contentPane.add(getComboBoxExtras()); contentPane.add(getButtonBestaetigen()); contentPane.add(getLabelPreisNetto()); contentPane.add(getLabelMWSt()); contentPane.add(getLabelPreisBrutto()); contentPane.add(getLabelWertPreisNetto()); contentPane.add(getLabelWertMWSt()); contentPane.add(getLabelWertPreisBrutto()); contentPane.add(getButtonBestellen()); } protected JList getListBestellung() { if (listBestellung == null) { listBestellung = new JList(); listBestellung.setBounds(281, 66, 320, 134); } return listBestellung; } private JLabel getLabelLogo() { if (labelLogo == null) { ImageIcon ico = new ImageIcon("Autohaus/Alset.png"); ico.setImage(ico.getImage().getScaledInstance(200, 60, Image.SCALE_DEFAULT)); labelLogo = new JLabel(ico); labelLogo.setBounds(10, 11, 138, 81); } return labelLogo; } private JLabel getLabelAuswahl() { if (labelAuswahl == null) { labelAuswahl = new JLabel("Ihre Auswahl:"); labelAuswahl.setFont(new Font("Tahoma", Font.BOLD, 12)); labelAuswahl.setBounds(281, 26, 131, 29); } return labelAuswahl; } private JLabel getLabelModel() { if (labelModel == null) { labelModel = new JLabel("Modell:"); labelModel.setBounds(10, 124, 60, 21); } return labelModel; } private JLabel getLabelFarbe() { if (labelFarbe == null) { labelFarbe = new JLabel("Farbe:"); labelFarbe.setBounds(10, 168, 39, 14); } return labelFarbe; } private JLabel getLabelPS() { if (labelPS == null) { labelPS = new JLabel("PS:"); labelPS.setBounds(10, 212, 46, 14); } return labelPS; } private JLabel getLabelExtras() { if (labelExtras == null) { labelExtras = new JLabel("Extras:"); labelExtras.setBounds(10, 256, 46, 14); } return labelExtras; } protected JComboBox getComboBoxModell() { if (comboBoxModell == null) { comboBoxModell = new JComboBox(); comboBoxModell.setBounds(74, 123, 164, 22); } return comboBoxModell; } protected JComboBox getComboBoxFarbe() { if (comboBoxFarbe == null) { comboBoxFarbe = new JComboBox(); comboBoxFarbe.setBounds(74, 164, 164, 22); } return comboBoxFarbe; } protected JComboBox getComboBoxPs() { if (comboBoxPs == null) { comboBoxPs = new JComboBox(); comboBoxPs.setBounds(74, 208, 164, 22); } return comboBoxPs; } protected JComboBox getComboBoxExtras() { if (comboBoxExtras == null) { comboBoxExtras = new JComboBox(); comboBoxExtras.setBounds(74, 252, 164, 22); } return comboBoxExtras; } protected JButton getButtonBestaetigen() { if (buttonBestaetigen == null) { buttonBestaetigen = new JButton("Auswahl best\u00E4tigen"); buttonBestaetigen.setBounds(10, 325, 228, 23); } return buttonBestaetigen; } private JLabel getLabelPreisNetto() { if (labelPreisNetto == null) { labelPreisNetto = new JLabel("Gesamtpreis netto:"); labelPreisNetto.setBounds(281, 239, 131, 31); } return labelPreisNetto; } private JLabel getLabelMWSt() { if (labelMWSt == null) { labelMWSt = new JLabel("19% MWSt:"); labelMWSt.setBounds(281, 281, 81, 29); } return labelMWSt; } private JLabel getLabelPreisBrutto() { if (labelPreisBrutto == null) { labelPreisBrutto = new JLabel("Bruttpreis:"); labelPreisBrutto.setBounds(281, 329, 81, 19); } return labelPreisBrutto; } private JLabel getLabelWertPreisNetto() { if (labelWertPreisNetto == null) { labelWertPreisNetto = new JLabel(""); labelWertPreisNetto.setBounds(411, 247, 60, 23); } return labelWertPreisNetto; } private JLabel getLabelWertMWSt() { if (labelWertMWSt == null) { labelWertMWSt = new JLabel(""); labelWertMWSt.setBounds(411, 288, 46, 14); } return labelWertMWSt; } private JLabel getLabelWertPreisBrutto() { if (labelWertPreisBrutto == null) { labelWertPreisBrutto = new JLabel(""); labelWertPreisBrutto.setBounds(411, 329, 46, 14); } return labelWertPreisBrutto; } private JButton getButtonBestellen() { if (buttonBestellen == null) { buttonBestellen = new JButton("Auto bestellen"); buttonBestellen.setBounds(481, 243, 120, 105); } return buttonBestellen; } }
true
653998695c142e20395095f7b52235449456fbbf
Java
bZez/MCLauncher
/src/main/java/com/kokakiwi/mclauncher/core/Launcher.java
UTF-8
12,379
2.046875
2
[]
no_license
package com.kokakiwi.mclauncher.core; import java.applet.Applet; import java.applet.AppletStub; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.VolatileImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import com.kokakiwi.mclauncher.LauncherFrame; import com.kokakiwi.mclauncher.utils.State; import com.kokakiwi.mclauncher.utils.Utils; public class Launcher extends Applet implements Runnable, AppletStub, MouseListener { private static final long serialVersionUID = -2433230602156426362L; private final LauncherFrame launcherFrame; public Applet applet; private Image bgImage; private int context = 0; private boolean active = false; private VolatileImage img; public GameUpdater updater; public GameLauncher launcher; public boolean pauseAskUpdate = false; private int percentage; private State state = State.INIT; private boolean hasMouseListener; public String subtaskMessage = ""; public Map<String, String> customParameters = new HashMap<String, String>(); public Launcher(LauncherFrame launcherFrame) { this.launcherFrame = launcherFrame; } @Override public void init() { if (applet != null) { applet.init(); return; } try { bgImage = ImageIO.read(Utils.getResourceAsStream("res/dirt.png")) .getScaledInstance(32, 32, 16); } catch (IOException e) { e.printStackTrace(); } if (launcherFrame.config.getString("server") != null) { customParameters.put("server", launcherFrame.config.getString("server")); } if (launcherFrame.config.getString("port") != null) { customParameters .put("port", launcherFrame.config.getString("port")); } if (launcherFrame.config.getString("latestversion") != null) { customParameters.put("latestVersion", launcherFrame.config.getString("latestVersion")); } if (launcherFrame.config.getString("downloadticket") != null) { customParameters.put("downloadTicket", launcherFrame.config.getString("downloadTicket")); } if (launcherFrame.config.getString("sessionid") != null) { customParameters.put("sessionID", launcherFrame.config.getString("sessionID")); } customParameters.put("username", launcherFrame.config .getString("userName") == null ? "Player" : launcherFrame.config.getString("userName")); // this.customParameters.put("stand-alone", "true"); updater = new GameUpdater(launcherFrame); launcher = new GameLauncher(launcherFrame); } public void mouseClicked(MouseEvent paramMouseEvent) { } public void mousePressed(MouseEvent me) { int x = me.getX() / 2; int y = me.getY() / 2; int w = getWidth() / 2; int h = getHeight() / 2; if (contains(x, y, (w / 2) - 56 - 8, h / 2, 56, 20)) { removeMouseListener(this); updater.shouldUpdate = true; pauseAskUpdate = false; hasMouseListener = false; } if (contains(x, y, (w / 2) + 8, h / 2, 56, 20)) { removeMouseListener(this); updater.shouldUpdate = false; pauseAskUpdate = false; hasMouseListener = false; } } public void mouseReleased(MouseEvent paramMouseEvent) { } public void mouseEntered(MouseEvent paramMouseEvent) { } public void mouseExited(MouseEvent paramMouseEvent) { } public void appletResize(int paramInt1, int paramInt2) { } public void run() { } @Override public void start() { if (applet != null) { applet.start(); return; } // Game Launch Thread t = new Thread() { @Override public void run() { updater.run(); launcher.run(); } }; t.setDaemon(true); t.start(); // Launcher Graphic Update t = new Thread() { @Override public void run() { while (applet == null) { Launcher.this.repaint(); try { Thread.sleep(10L); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.setDaemon(true); t.start(); } @Override public void stop() { if (applet != null) { active = false; applet.stop(); return; } } @Override public void destroy() { if (applet != null) { applet.destroy(); return; } } public void replace(Applet applet) { this.applet = applet; applet.setStub(this); applet.setSize(getWidth(), getHeight()); setLayout(new BorderLayout()); add(applet, "Center"); applet.init(); active = true; applet.start(); validate(); launcherFrame.setTitle(launcherFrame.config .getString("gameLauncher.gameName")); } @Override public void paint(Graphics g2) { if (applet != null) { return; } int w = getWidth() / 2; int h = getHeight() / 2; if ((img == null) || (img.getWidth() != w) || (img.getHeight() != h)) { img = createVolatileImage(w, h); } Graphics g = img.getGraphics(); for (int x = 0; x <= (w / 32); x++) { for (int y = 0; y <= (h / 32); y++) { g.drawImage(bgImage, x * 32, y * 32, null); } } if (pauseAskUpdate) { if (!hasMouseListener) { hasMouseListener = true; addMouseListener(this); } g.setColor(Color.LIGHT_GRAY); String msg = launcherFrame.locale .getString("updater.newUpdateAvailable"); g.setFont(new Font(null, 1, 20)); FontMetrics fm = g.getFontMetrics(); g.drawString(msg, (w / 2) - (fm.stringWidth(msg) / 2), (h / 2) - (fm.getHeight() * 2)); g.setFont(new Font(null, 0, 12)); fm = g.getFontMetrics(); g.fill3DRect((w / 2) - 56 - 8, h / 2, 56, 20, true); g.fill3DRect((w / 2) + 8, h / 2, 56, 20, true); msg = launcherFrame.locale.getString("updater.askUpdate"); g.drawString(msg, (w / 2) - (fm.stringWidth(msg) / 2), (h / 2) - 8); g.setColor(Color.BLACK); msg = launcherFrame.locale.getString("global.yes"); g.drawString(msg, ((w / 2) - 56 - 8 - (fm.stringWidth(msg) / 2)) + 28, (h / 2) + 14); msg = launcherFrame.locale.getString("global.no"); g.drawString(msg, (((w / 2) + 8) - (fm.stringWidth(msg) / 2)) + 28, (h / 2) + 14); } else { g.setColor(Color.LIGHT_GRAY); String msg = launcherFrame.locale.getString("updater.title"); if (updater.fatalError) { msg = "Failed to launch"; } g.setFont(new Font(null, 1, 20)); FontMetrics fm = g.getFontMetrics(); g.drawString(msg, (w / 2) - (fm.stringWidth(msg) / 2), (h / 2) - (fm.getHeight() * 2)); g.setFont(new Font(null, 0, 12)); fm = g.getFontMetrics(); msg = getDescriptionForState(); if (updater.fatalError) { msg = updater.fatalErrorDescription; subtaskMessage = ""; } g.drawString(msg, (w / 2) - (fm.stringWidth(msg) / 2), (h / 2) + (fm.getHeight() * 1)); msg = subtaskMessage; g.drawString(msg, (w / 2) - (fm.stringWidth(msg) / 2), (h / 2) + (fm.getHeight() * 2)); if (!updater.fatalError) { g.setColor(Color.black); g.fillRect(64, h - 64, (w - 128) + 1, 5); g.setColor(new Color(32768)); g.fillRect(64, h - 64, (percentage * (w - 128)) / 100, 4); g.setColor(new Color(2138144)); g.fillRect(65, (h - 64) + 1, ((percentage * (w - 128)) / 100) - 2, 1); } } g.dispose(); g2.drawImage(img, 0, 0, w * 2, h * 2, null); } private String getDescriptionForState() { if (state.getDescription() != null) { return state.getDescription(); } else { return launcherFrame.locale.getString("updater.states." + state.name()); } } @Override public void update(Graphics g) { paint(g); } private boolean contains(int x, int y, int xx, int yy, int w, int h) { return (x >= xx) && (y >= yy) && (x < (xx + w)) && (y < (yy + h)); } @Override public String getParameter(String name) { String custom = customParameters.get(name); if (custom != null) { return custom; } custom = launcherFrame.config.getString(name); if (custom != null) { return custom; } try { return super.getParameter(name); } catch (Exception e) { customParameters.put(name, null); } return null; } @Override public URL getDocumentBase() { try { return new URL( launcherFrame.config .getString("gameLauncher.documentBaseURL")); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } @Override public boolean isActive() { if (context == 0) { context = -1; try { if (getAppletContext() != null) { context = 1; } } catch (Exception localException) { } } if (context == -1) { return active; } return super.isActive(); } public void setPercentage(int percentage) { this.percentage = percentage; } public int getPercentage() { return percentage; } public void setState(int state) { this.state = State.values()[state - 1]; } public void setState(State state) { this.state = state; } public State getState() { return state; } }
true
a3ab377d298dd7b5a654cd5ed500a440544f6bf1
Java
Nahuel987/DesafioTresAndroid
/app/src/main/java/com/example/desafiotresandroid/FragmentoUno.java
UTF-8
3,672
2.234375
2
[]
no_license
package com.example.desafiotresandroid; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.Objects; /** * A simple {@link Fragment} subclass. * Use the {@link FragmentoUno#newInstance} factory method to * create an instance of this fragment. */ public class FragmentoUno extends Fragment { ImageView imagenDesafioLatam; //variables que recibiran los datos enviados desde la actividad TextView preguntaView,categoriaView,dificultadView; // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public FragmentoUno() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FragmentoUno. */ // TODO: Rename and change types and number of parameters public static FragmentoUno newInstance(String param1, String param2) { FragmentoUno fragment = new FragmentoUno(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } //constructor personalizado que recibira los datos desde la actividad public static FragmentoUno newInstance(String pregunta, String categoria, String dificultad) { //public static FragmentoUno newInstance(String pregunta, String categoria) { FragmentoUno fragment = new FragmentoUno(); Bundle arguments = new Bundle(); arguments.putString("PREGUNTA", pregunta); arguments.putString("CATEGORIA", categoria); arguments.putString("DIFICULTAD", dificultad); fragment.setArguments(arguments); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view=inflater.inflate(R.layout.fragment_fragmento_uno, container, false); final String pregunta = Objects.requireNonNull(getArguments()).getString("PREGUNTA"); final String categoria = Objects.requireNonNull(getArguments().getString("CATEGORIA")); final String dificultad = Objects.requireNonNull(getArguments().getString("DIFICULTAD")); inciciaVista(view); preguntaView.setText(pregunta); categoriaView.setText(categoria); dificultadView.setText(dificultad); return view; } private void inciciaVista(View view) { preguntaView = view.findViewById(R.id.txPregunta); categoriaView = view.findViewById(R.id.txCategoria); dificultadView = view.findViewById(R.id.txDificultad); } }//class
true
76005e4483786f2f38ec100ad968215ce4a201a0
Java
SvetoslavGekov/OOP_Tasks
/Vinetki2/src/people/Driver.java
UTF-8
3,341
3.25
3
[]
no_license
package people; import java.time.LocalDate; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import demo.Demo; import demo.GasStation; import demo.VehicleTypes; import vehicles.Vehicle; import vignettes.Vignette; import vignettes.VignetteDurations; public class Driver { //Fields private String name; private LinkedHashSet<Vehicle> vehicles = new LinkedHashSet<>(); private double money; private GasStation gasStation; //Contr public Driver(String name, double money, GasStation gasStation) { setName(name); setMoney(money); setGasStation(gasStation); System.out.println(this); } //Methods public void printAllCars() { for (Vehicle vehicle : vehicles) { if(vehicle.getType().equals(VehicleTypes.CAR) && vehicle.hasVignette()) { System.out.println(vehicle); } } } @Override public String toString() { return String.format("Name: %s Money: %.2f GasStation: %s", this.name, this.money, this.gasStation.getName()); } //Methods public void addVehicle(Vehicle veh) { if(veh != null) { this.vehicles.add(veh); } System.out.println(veh + " has been added to " + this.name + "'s garage"); } public void buyVignettesForAllVehicles() { for (int i = 1; i <= this.vehicles.size(); i++) { VignetteDurations[] vDurations = VignetteDurations.values(); VignetteDurations duration = vDurations[Demo.RNG(vDurations.length)]; this.buyVignetteForVehicle(i, duration); } } public void buyVignetteForVehicle(int vehicleNumber, VignetteDurations duration) { //Get vehicle Vehicle veh = getRandomVehicle(vehicleNumber); if(!veh.hasVignette()) { //Buy vignette System.out.println(String.format("%s would like to buy a vignette for %s", this, veh)); Vignette vehVignette = gasStation.sellVignette(veh, this, duration); //Stick vignette to vehicles System.out.println(this.placeVignetteOnVehicle(vehVignette, veh)); } else { System.out.println("Sorry " + veh + " has a vignette!"); } } private Vehicle getRandomVehicle(int vehicleNumber) { if(vehicleNumber > 0 && vehicleNumber <= this.vehicles.size()) { int counter = 0; Iterator<Vehicle> it = this.vehicles.iterator(); while(it.hasNext()) { counter++; Vehicle veh = it.next(); if(counter == vehicleNumber) { return veh; } } } return null; } public void printVehiclesWithoutVignettesForDate(LocalDate date) { System.out.println("======== VEHICLES WITH NO VIGNETTE FOR DATE " + date); for (Vehicle vehicle : vehicles) { if(!vehicle.hasVignetteForDate(date)) { System.out.println(vehicle); } } } private int placeVignetteOnVehicle(Vignette vignette, Vehicle veh) { veh.setVignette(vignette); return vignette.getPlacingDuration(); } //Setters private void setName(String name) { if(Demo.validStr(name)) { this.name = name; } } public void setMoney(double money) { if(money >= 0) {//Can be broke this.money = money; } } private void setGasStation(GasStation gasStation) { if(gasStation != null) { this.gasStation = gasStation; } } //Getters private String getName() { return name; } public double getMoney() { return money; } public Set<Vehicle> getVehicles() { return Collections.unmodifiableSet(this.vehicles); } }
true
a8dfea32ceabbf511e58d1bbae6ae3ae7175ab74
Java
lgrStyle/integration
/src/test/java/com/demo/integration/IntegrationApplicationTests.java
UTF-8
5,274
1.929688
2
[]
no_license
package com.demo.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import org.activiti.engine.FormService; import org.activiti.engine.HistoryService; import org.activiti.engine.IdentityService; import org.activiti.engine.RepositoryService; import org.activiti.engine.TaskService; import org.activiti.engine.history.HistoricDetail; import org.activiti.engine.history.HistoricFormProperty; import org.activiti.engine.history.HistoricProcessInstance; import org.activiti.engine.history.HistoricVariableInstance; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import com.demo.integration.entity.Student; import com.demo.integration.service.DemoService; @RunWith(SpringRunner.class) @SpringBootTest public class IntegrationApplicationTests { @Autowired private IdentityService identityService; @Autowired private RepositoryService repositoryService; @Autowired private FormService formService; @Autowired private TaskService taskService; @Autowired private HistoryService historyService; @Autowired private DemoService demoService; @Transactional public void allApproved() { String currentUser = "ming"; identityService.setAuthenticatedUserId(currentUser); ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leaveProcess").singleResult(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Map<String,String> variables = new HashMap<>(); Calendar calendar = Calendar.getInstance(); String startDate = sdf.format(calendar.getTime()); calendar.add(Calendar.DAY_OF_MONTH, 2); String endDate = sdf.format(calendar.getTime()); variables.put("startDate", startDate); variables.put("endDate", endDate); variables.put("reason", "调休"); ProcessInstance pi = formService.submitStartFormData(pd.getId(), variables); assertNotNull(pi); Task deptTask = taskService.createTaskQuery().taskCandidateGroup("deptLeader").singleResult(); variables = new HashMap<>(); variables.put("deptLeaderApprove", "true"); formService.submitTaskFormData(deptTask.getId(), variables); Task hrTask = taskService.createTaskQuery().taskCandidateGroup("hr").singleResult(); variables = new HashMap<>(); variables.put("hrApprove", "true"); formService.submitTaskFormData(hrTask.getId(), variables); Task reportBackTask = taskService.createTaskQuery().taskAssignee(currentUser).singleResult(); variables = new HashMap<>(); variables.put("reportBackDate", "2018-07-20"); formService.submitTaskFormData(reportBackTask.getId(), variables); HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().finished().singleResult(); assertNotNull(hpi); Map<String,Object> historyVariables = packageVariables(pi); assertEquals("ok", historyVariables.get("result")); } private Map<String,Object> packageVariables(ProcessInstance pi){ Map<String,Object> variables = new HashMap<>(); List<HistoricDetail> list = historyService.createHistoricDetailQuery().processInstanceId(pi.getProcessInstanceId()).list(); List<HistoricVariableInstance> varList = historyService.createHistoricVariableInstanceQuery().processInstanceId(pi.getProcessInstanceId()).list(); for(HistoricVariableInstance var : varList) { variables.put(var.getVariableName(),var.getValue()); System.out.println("variable: "+var.getVariableName()+"="+var.getValue()); } for(HistoricDetail historicDetail : list) { if(historicDetail instanceof HistoricFormProperty) { HistoricFormProperty field = (HistoricFormProperty) historicDetail; variables.put(field.getPropertyId(), field.getPropertyValue()); System.out.println("form field: taskId="+field.getTaskId()+","+field.getPropertyId()+"="+field.getPropertyValue()); } } return variables; } // @Test public void jpaDemo() { Student s = new Student(); s.setName("lgr"); demoService.save(s); System.out.println("已完成"); } @Test public void demo2() { Student s = demoService.findById(3); System.out.println(s.getName()); s.setName("333"); } }
true
76fea6c2d44a5186e7bd5a54bab78e131acce366
Java
nivkov2/spring-pet-clinic
/pet-clinic-data/src/test/java/com/petclinic/springpetclinic/services/springdatajpa/PetSDJpaServiceTest.java
UTF-8
1,853
2.234375
2
[]
no_license
package com.petclinic.springpetclinic.services.springdatajpa; import com.petclinic.springpetclinic.model.Pet; import com.petclinic.springpetclinic.repositories.PetRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashSet; import java.util.Optional; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class PetSDJpaServiceTest { @Mock PetRepository petRepository; @InjectMocks PetSDJpaService petSDJpaService; Pet pet; @BeforeEach void setUp() { pet = Pet.builder().id(1l).build(); } @Test void findAll() { Set<Pet> pets = new HashSet<>(); pets.add(Pet.builder().build()); pets.add(Pet.builder().build()); when(petRepository.findAll()).thenReturn(pets); assertEquals(pets.size(), ((Set<Pet>)petRepository.findAll()).size()); } @Test void findById() { when(petRepository.findById(anyLong())).thenReturn(Optional.of(pet)); assertNotNull(petRepository.findById(anyLong()).get()); } @Test void save() { petRepository.save(pet); verify(petRepository, times(1)).save(pet); } @Test void delete() { petRepository.delete(pet); verify(petRepository, times(1)).delete(pet); } @Test void deleteById() { petRepository.deleteById(anyLong()); verify(petRepository, times(1)).deleteById(anyLong()); } }
true
e0e022912e1ddd195c17f7533d48b96b842ac93d
Java
sgokul123/JavaBasics
/src/RepeatD.java
UTF-8
782
3.09375
3
[]
no_license
import java.util.Scanner; /* * Disc : Write a Program to find repeated digitd in Number * Auth : Sonawane Gokul * Date : 13/13/2016 */ public class RepeatD { public static void main(String args[]){ Scanner sc=new Scanner(System.in); int num,i,j,res,len=0,num2; System.out.println("Enter the Number :"); num=sc.nextInt(); num2=num; while(num>0){ num=num/10; len=len+1; } int arr[]=new int[len]; for(i=0;i<len;i++){ arr[i]=num2%10; num2=num2/10; } for(i=0;i<len-1;i++){ for(j=i+1;j<len;j++){ if(arr[i]==arr[j]){ arr[j]=0; } } } num=0; System.out.println("The Number withaut duplicate :"); for(j=0;j<len;j++){ if(arr[j]!=0) num=(num*10)+arr[j]; System.out.print(arr[j]); } RevercNum a=new RevercNum(num); } }
true
318f471f23f578b8c3339cabc90ca25eacbde02d
Java
wang-shun/groundwork-trunk
/groundwork-monitor-framework/core/src/main/org/jboss/portal/test/core/portlet/PortletRequestEncoderTestCase.java
UTF-8
11,121
1.609375
2
[]
no_license
/****************************************************************************** * JBoss, a division of Red Hat * * Copyright 2008, Red Hat Middleware, LLC, and individual * * contributors as indicated by the @authors tag. See the * * copyright.txt in the distribution for a full listing of * * individual contributors. * * * * This 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 2.1 of * * the License, or (at your option) any later version. * * * * This software 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 software; if not, write to the Free * * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * ******************************************************************************/ package org.jboss.portal.test.core.portlet; import org.jboss.portal.core.portlet.PortletRequestEncoder; import org.jboss.portal.core.portlet.PortletRequestDecoder; import org.jboss.portal.common.util.ParameterMap; import org.jboss.portal.common.util.Tools; import org.jboss.portal.portlet.ParametersStateString; import org.jboss.portal.portlet.cache.CacheLevel; import org.jboss.portal.Mode; import org.jboss.portal.WindowState; import junit.framework.TestCase; /** * @author <a href="mailto:julien@jboss.org">Julien Viet</a> * @version $Revision: 1.1 $ */ public class PortletRequestEncoderTestCase extends TestCase { /** . */ private ParameterMap params; /** . */ private PortletRequestEncoder encoder; public void setUp() throws Exception { params = new ParameterMap(); encoder = new PortletRequestEncoder(params); } public void tearDown() throws Exception { params = null; encoder = null; } public void testEncodeRender() { Blah blah = new Blah<Mode, WindowState>( Mode.VIEW, WindowState.NORMAL, PortletRequestDecoder.RENDER_PHASE, PortletRequestDecoder.MODE_PARAMETER, PortletRequestDecoder.WINDOW_STATE_PARAMETER, PortletRequestDecoder.MODE_MASK, PortletRequestDecoder.WINDOW_STATE_MASK) { protected void encodeBlah(ParametersStateString params, Mode view, WindowState normal) { encodeRender(params, view, normal); } }; // blah.test(); } public void testEncodeAction() { Blah blah = new Blah<Mode, WindowState>( Mode.VIEW, WindowState.NORMAL, PortletRequestDecoder.ACTION_PHASE, PortletRequestDecoder.MODE_PARAMETER, PortletRequestDecoder.WINDOW_STATE_PARAMETER, PortletRequestDecoder.MODE_MASK, PortletRequestDecoder.WINDOW_STATE_MASK) { protected void encodeBlah(ParametersStateString params, Mode view, WindowState normal) { encodeAction(params, view, normal); } }; // blah.test(); } public void testEncodeResource() { Blah blah = new Blah<String, CacheLevel>( "resource_id", CacheLevel.PAGE, PortletRequestDecoder.RESOURCE_PHASE, PortletRequestDecoder.RESOURCE_ID_PARAMETER, PortletRequestDecoder.CACHEABILITY_PARAMETER, PortletRequestDecoder.RESOURCE_ID_MASK, PortletRequestDecoder.CACHEABILITY_MASK) { protected void encodeBlah(ParametersStateString params, String view, CacheLevel normal) { encodeResource(params, view, normal); } }; // blah.test(); } private abstract class Blah<A,B> { /** . */ protected final A a; /** . */ protected final B b; /** . */ protected final int lifecycleValue; /** . */ protected final String aParamName; /** . */ protected final String bParamName; /** . */ protected final int aParamMask; /** . */ protected final int bParamMask; protected Blah(A a, B b, int lifecycleValue, String aParamName, String bParamName, int aParamMask, int bParamMask) { this.a = a; this.b = b; this.lifecycleValue = lifecycleValue; this.aParamName = aParamName; this.bParamName = bParamName; this.aParamMask = aParamMask; this.bParamMask = bParamMask; } protected abstract void encodeBlah(ParametersStateString params, A view, B normal); public void test() { ParametersStateString pp = ParametersStateString.create(); encodeBlah(pp, null, null); assertEquals(1, params.size()); _assertEquals(lifecycleValue, params.getValues(PortletRequestDecoder.META_PARAMETER)); // pp = ParametersStateString.create(); pp.setValue(PortletRequestDecoder.META_PARAMETER, "foo"); encodeBlah(pp, null, null); assertEquals(1, params.size()); _assertEquals(new String[]{Integer.toHexString(lifecycleValue),"foo"}, params.getValues(PortletRequestDecoder.META_PARAMETER)); // pp = ParametersStateString.create(); pp.setValue("foo", "bar"); encodeBlah(pp, null, null); assertEquals(2, params.size()); _assertEquals(lifecycleValue, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals("bar", params.getValues("foo")); // pp = ParametersStateString.create(); encodeBlah(pp, a, null); assertEquals(2, params.size()); _assertEquals(lifecycleValue | aParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(a, params.getValues(aParamName)); // pp = ParametersStateString.create(); pp.setValue(aParamName, "foo"); encodeBlah(pp, a, null); assertEquals(2, params.size()); _assertEquals(lifecycleValue | aParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(new String[]{a.toString(),"foo"}, params.getValues(aParamName)); // pp = ParametersStateString.create(); pp.setValue("foo", "bar"); encodeBlah(pp, a, null); assertEquals(3, params.size()); _assertEquals(lifecycleValue | aParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(a, params.getValues(aParamName)); _assertEquals("bar", params.getValues("foo")); // pp = ParametersStateString.create(); encodeBlah(pp, null, b); assertEquals(2, params.size()); _assertEquals(lifecycleValue | bParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(b, params.getValues(bParamName)); // pp = ParametersStateString.create(); pp.setValue(bParamName, "foo"); encodeBlah(pp, null, b); assertEquals(2, params.size()); _assertEquals(lifecycleValue | bParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(new String[]{b.toString(),"foo"}, params.getValues(bParamName)); // pp = ParametersStateString.create(); pp.setValue("foo", "bar"); encodeBlah(pp, null, b); assertEquals(3, params.size()); _assertEquals(lifecycleValue | bParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(b, params.getValues(bParamName)); _assertEquals("bar", params.getValues("foo")); // pp = ParametersStateString.create(); encodeBlah(pp, a, b); assertEquals(3, params.size()); _assertEquals(lifecycleValue | aParamMask | bParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(a, params.getValues(aParamName)); _assertEquals(b, params.getValues(bParamName)); // pp = ParametersStateString.create(); pp.setValue("foo", "bar"); encodeBlah(pp, a, b); assertEquals(4, params.size()); _assertEquals(lifecycleValue | aParamMask | bParamMask, params.getValues(PortletRequestDecoder.META_PARAMETER)); _assertEquals(a, params.getValues(aParamName)); _assertEquals(b, params.getValues(bParamName)); _assertEquals("bar", params.getValues("foo")); } } public void testEncodeNav() { encodeRender(null, null, null); assertEquals(0, params.size()); // encodeRender(null, Mode.VIEW, null); assertEquals(1, params.size()); _assertEquals(Mode.VIEW, params.getValues(PortletRequestDecoder.MODE_PARAMETER)); // encodeRender(null, null, WindowState.NORMAL); assertEquals(1, params.size()); _assertEquals(WindowState.NORMAL, params.getValues(PortletRequestDecoder.WINDOW_STATE_PARAMETER)); // encodeRender(null, Mode.VIEW, WindowState.NORMAL); assertEquals(2, params.size()); _assertEquals(Mode.VIEW, params.getValues(PortletRequestDecoder.MODE_PARAMETER)); _assertEquals(WindowState.NORMAL, params.getValues(PortletRequestDecoder.WINDOW_STATE_PARAMETER)); } private void encodeRender(ParametersStateString params, Mode view, WindowState normal) { encoder.encodeRender(params, view, normal); } private void encodeAction(ParametersStateString params, Mode view, WindowState normal) { encoder.encodeAction(null, params, view, normal); } private void encodeResource(ParametersStateString params, String resourceId, CacheLevel cacheability) { encoder.encodeResource(cacheability, resourceId, params); } void _assertEquals(int expected, String[] actual) { _assertEquals(new String[]{Integer.toHexString(expected)}, actual); } void _assertEquals(Object expected, String[] actual) { _assertEquals(new String[]{"" + expected}, actual); } void _assertEquals(String[] expected, String[] actual) { if (expected == null) { assertNull(actual); } else { assertNotNull((actual)); assertEquals(Tools.toList(expected), Tools.toList(actual)); } } }
true
d63f7835ba83f1ff4b7019c270737578b0c8c0db
Java
atship/schemely
/src/schemely/file/SchemeFileTypeLoader.java
UTF-8
403
1.9375
2
[ "MIT" ]
permissive
package schemely.file; import com.intellij.openapi.fileTypes.FileTypeConsumer; import com.intellij.openapi.fileTypes.FileTypeFactory; import org.jetbrains.annotations.NotNull; public class SchemeFileTypeLoader extends FileTypeFactory { public void createFileTypes(@NotNull FileTypeConsumer consumer) { consumer.consume(SchemeFileType.SCHEME_FILE_TYPE, SchemeFileType.SCHEME_EXTENSIONS); } }
true
bb0b2ca410625a29df82178ab32651e45507de5e
Java
yazid2016/com.incorporateapps.fakegps.fre
/src/com/google/android/gms/tagmanager/TagManager.java
UTF-8
5,488
1.625
2
[]
no_license
package com.google.android.gms.tagmanager; import android.content.Context; import android.net.Uri; import android.os.Build.VERSION; import android.os.Handler; import com.google.android.gms.common.api.PendingResult; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class TagManager { private static TagManager zzblm; private final Context mContext; private final DataLayer zzbhN; private final zzs zzbkh; private final TagManager.zza zzblj; private final zzct zzblk; private final ConcurrentMap zzbll; TagManager(Context paramContext, TagManager.zza paramzza, DataLayer paramDataLayer, zzct paramzzct) { if (paramContext == null) { throw new NullPointerException("context cannot be null"); } mContext = paramContext.getApplicationContext(); zzblk = paramzzct; zzblj = paramzza; zzbll = new ConcurrentHashMap(); zzbhN = paramDataLayer; zzbhN.zza(new TagManager.1(this)); zzbhN.zza(new zzd(mContext)); zzbkh = new zzs(); zzHt(); } public static TagManager getInstance(Context paramContext) { try { if (zzblm != null) { break label68; } if (paramContext == null) { zzbg.e("TagManager.getInstance requires non-null context."); throw new NullPointerException(); } } finally {} zzblm = new TagManager(paramContext, new TagManager.2(), new DataLayer(new zzw(paramContext)), zzcu.zzHo()); label68: paramContext = zzblm; return paramContext; } private void zzHt() { if (Build.VERSION.SDK_INT >= 14) { mContext.registerComponentCallbacks(new TagManager.3(this)); } } private void zzgp(String paramString) { Iterator localIterator = zzbll.keySet().iterator(); while (localIterator.hasNext()) { ((zzo)localIterator.next()).zzfR(paramString); } } public void dispatch() { zzblk.dispatch(); } public DataLayer getDataLayer() { return zzbhN; } public PendingResult loadContainerDefaultOnly(String paramString, int paramInt) { paramString = zzblj.zza(mContext, this, null, paramString, paramInt, zzbkh); paramString.zzGg(); return paramString; } public PendingResult loadContainerDefaultOnly(String paramString, int paramInt, Handler paramHandler) { paramString = zzblj.zza(mContext, this, paramHandler.getLooper(), paramString, paramInt, zzbkh); paramString.zzGg(); return paramString; } public PendingResult loadContainerPreferFresh(String paramString, int paramInt) { paramString = zzblj.zza(mContext, this, null, paramString, paramInt, zzbkh); paramString.zzGi(); return paramString; } public PendingResult loadContainerPreferFresh(String paramString, int paramInt, Handler paramHandler) { paramString = zzblj.zza(mContext, this, paramHandler.getLooper(), paramString, paramInt, zzbkh); paramString.zzGi(); return paramString; } public PendingResult loadContainerPreferNonDefault(String paramString, int paramInt) { paramString = zzblj.zza(mContext, this, null, paramString, paramInt, zzbkh); paramString.zzGh(); return paramString; } public PendingResult loadContainerPreferNonDefault(String paramString, int paramInt, Handler paramHandler) { paramString = zzblj.zza(mContext, this, paramHandler.getLooper(), paramString, paramInt, zzbkh); paramString.zzGh(); return paramString; } public void setVerboseLoggingEnabled(boolean paramBoolean) { if (paramBoolean) {} for (int i = 2;; i = 5) { zzbg.setLogLevel(i); return; } } public void zza(zzo paramzzo) { zzbll.put(paramzzo, Boolean.valueOf(true)); } public boolean zzb(zzo paramzzo) { return zzbll.remove(paramzzo) != null; } boolean zzp(Uri paramUri) { for (;;) { boolean bool; Object localObject2; try { localObject1 = zzcb.zzGU(); if (!((zzcb)localObject1).zzp(paramUri)) { break label229; } paramUri = ((zzcb)localObject1).getContainerId(); int i = TagManager.4.zzblo[localObject1.zzGV().ordinal()]; switch (i) { default: bool = true; return bool; } } finally {} Object localObject1 = zzbll.keySet().iterator(); if (((Iterator)localObject1).hasNext()) { localObject2 = (zzo)((Iterator)localObject1).next(); if (((zzo)localObject2).getContainerId().equals(paramUri)) { ((zzo)localObject2).zzfT(null); ((zzo)localObject2).refresh(); } } else { continue; localObject2 = zzbll.keySet().iterator(); while (((Iterator)localObject2).hasNext()) { zzo localzzo = (zzo)((Iterator)localObject2).next(); if (localzzo.getContainerId().equals(paramUri)) { localzzo.zzfT(((zzcb)localObject1).zzGW()); localzzo.refresh(); } else if (localzzo.zzGd() != null) { localzzo.zzfT(null); localzzo.refresh(); } } continue; label229: bool = false; } } } } /* Location: * Qualified Name: com.google.android.gms.tagmanager.TagManager * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
c1eee28bb1ab9fce2fdd1667d9d23a4a9ad0d2e6
Java
lothrimondWDZ/ekosmiec
/src/main/java/pl/ekosmiec/dao/ContainersTypesDao.java
UTF-8
193
1.671875
2
[]
no_license
package pl.ekosmiec.dao; import java.util.List; import pl.ekosmiec.entities.ContainersTypes; public interface ContainersTypesDao { public List<ContainersTypes> getAllContainersTypes(); }
true
c8220c8040f5237fb74e4271a5d5c565725c9dc3
Java
guochengabc/xxhj_project
/app/src/main/java/com/kongtiaoapp/xxhj/prefessionalknowledge/adapter/MyFavoriteInformationAdapter.java
UTF-8
3,964
1.875
2
[]
no_license
package com.kongtiaoapp.xxhj.prefessionalknowledge.adapter; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.kongtiaoapp.xxhj.App; import com.kongtiaoapp.xxhj.R; import com.kongtiaoapp.xxhj.activites.ImageScaleActivity; import com.kongtiaoapp.xxhj.afinal.ConstantValue; import com.kongtiaoapp.xxhj.bean.MyZiXun; import com.kongtiaoapp.xxhj.net.TestData; import com.kongtiaoapp.xxhj.ui.NineGridView.NetworkImageAdapter; import com.kongtiaoapp.xxhj.ui.NineGridView.NineGridView; import com.kongtiaoapp.xxhj.utils.GlideCircleTransform; import com.kongtiaoapp.xxhj.utils.TimeUtils; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Luoye on 2016-6-14. */ public class MyFavoriteInformationAdapter extends BaseAdapter { private Context mContext; private List<MyZiXun.MyZiXunBean> mList; public MyFavoriteInformationAdapter(Context context, List<MyZiXun.MyZiXunBean> list) { this.mContext = context; this.mList = list; } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final TestData.Moment moment = TestData.getData().get(position); ViewHolder holder = null; if (convertView == null) { // convertView = inflater.inflate(R.layout.whatever, parent, false); convertView = LayoutInflater.from(App.application).inflate( R.layout.item_favorite_information, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } final MyZiXun.MyZiXunBean momentInfo = (MyZiXun.MyZiXunBean) getItem(position); if (!TextUtils.isEmpty(momentInfo.getAvatarUrl())) { Glide.with(mContext).load(ConstantValue.URL + momentInfo.getAvatarUrl()).placeholder(R.mipmap.default_head).transform(new GlideCircleTransform(mContext)).crossFade().into(holder.ivHead); } holder.tvName.setText(momentInfo.getUserName()); holder.tvTime.setText(TimeUtils.getStandardDate(momentInfo.getCreateTime())); holder.tvContent.setText(momentInfo.getTitle()); NetworkImageAdapter adapter = new NetworkImageAdapter(App.application, momentInfo.getImageUrl()); holder.gallery.setAdapter(adapter); final String[] arr = (String[]) momentInfo.getImageUrl().toArray(new String[momentInfo.getImageUrl().size()]); holder.gallery.setOnImageClickListener(new NineGridView.OnImageClickListener() { @Override public void onImageCilcked(int position, View view) { mContext.startActivity(new Intent(App.application, ImageScaleActivity.class).putExtra("urls", arr).putExtra("currentItem", position)); // ImageScaleActivity.instance.overridePendingTransition(R.anim.activity_translate_in, // 0); } }); return convertView; } static class ViewHolder { @BindView(R.id.iv_head) ImageView ivHead; @BindView(R.id.tv_time) TextView tvTime; @BindView(R.id.tv_name) TextView tvName; @BindView(R.id.tv_content) TextView tvContent; @BindView(R.id.gallery) NineGridView gallery; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
true
af657669fea02f6c2cf5b892edd09652c67325a1
Java
kanyuxia/oldStudyJava
/designpattern/src/com/kanyuxia/template/Client.java
UTF-8
387
2.53125
3
[]
no_license
package com.kanyuxia.template; import java.util.AbstractList; /** * Created by kanyuxia on 2017/3/30. */ public class Client { public static void main(String[] args) { AbstractClass class1 = new ConcreteClass1(); AbstractClass class2 = new ConcreteClass2(); // 调用模板方法 class1.templateMethod(); class2.templateMethod(); } }
true
74eac051520f8010b7390bbcbdcfe450f0de247c
Java
aditya-thakare/HdfsUtils
/src/main/java/com/github/gbraccialli/hdfs/Implement2.java
UTF-8
1,995
2.640625
3
[]
no_license
package com.github.gbraccialli.hdfs; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.BasicConfigurator; public class Implement2 { public static void main(String args[]){ System.out.println("IMP2: From Main: WELCOMEEEEEE" ); implementCall(); } public static String implementCall(){ BasicConfigurator.configure(); System.out.println("From IMP2: implementCall" ); String json = ""; try { FileSystem hdfs = HDFSConfigUtils.loadConfigsAndGetFileSystem("/tmp/zeppline/","hdfs"); int currentLevel = 0; //current level, default = 0 int maxLevelThreshold = 7; //max number of directories do drill down. -1 means no limit. for example: maxLevelThreshold=3 means drill down will stop after 3 levels of subdirectories int minSizeThreshold = -1; //min number of bytes in a directory to continue drill down. -1 means no limit. minSizeThreshold=1000000 means only directories greater > 1000000 bytes will be drilled down boolean showFiles = false; //whether to show information about files. showFiles=false will show summary information about files in each directory/subdirectory. String excludeList = ""; //directories to exclude from drill down, for example: /tmp/,/user/ won't present information about those directories. boolean verbose = false; //when true print processing info into System.err (not applied for zeppelin) Path hdfsPath = new Path("/dl"); //path to start analysis PathInfo dirInfo = DirectoryContentsUtils.listContents(hdfs,hdfsPath,currentLevel,maxLevelThreshold,minSizeThreshold,showFiles,verbose,excludeList); json = DirectoryContentsUtils.directoryInfoToJson(dirInfo); System.out.println("JSON: " + json); } catch (Exception e) { System.out.println("ERROR: " + e.getMessage()); } return json; } }
true
88e93a4f5d63f303421273369927dc857ddda93e
Java
rushilkhattar09/3playertictactoe
/app/src/main/java/com/zvox/rushilkhattar/a3playertictactoe/HomePage2.java
UTF-8
3,984
1.929688
2
[]
no_license
package com.zvox.rushilkhattar.a3playertictactoe; import android.content.Intent; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.MobileAds; /** * Created by rushilkhattar on 14/08/17. */ public class HomePage2 extends AppCompatActivity { public static int IS_ACTIVITY_OPENED_FIRST_TIME = 10; Button button1, button2, button3, button4; MediaPlayer mediaPlayer19; private InterstitialAd interstitialAd; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home_page); new MyTask2().execute(); MobileAds.initialize(this, "ca-app-pub-9771570406820302~3687906064"); interstitialAd = new InterstitialAd(HomePage2.this); interstitialAd.setAdUnitId("ca-app-pub-9771570406820302/7136018875"); interstitialAd.loadAd(new AdRequest.Builder().build()); interstitialAd.setAdListener(new AdListener() { @Override public void onAdLoaded() { if (IS_ACTIVITY_OPENED_FIRST_TIME % 5 == 0) { displayAd(); } IS_ACTIVITY_OPENED_FIRST_TIME++; } }); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); button3 = (Button) findViewById(R.id.button3); button4 = (Button) findViewById(R.id.button4); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaPlayer19.stop(); Intent intent6 = new Intent(HomePage2.this, ThirdActivity.class); startActivity(intent6); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaPlayer19.stop(); Intent intent5 = new Intent(HomePage2.this, MainActivity.class); startActivity(intent5); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaPlayer19.stop(); Intent intent4 = new Intent(HomePage2.this, SecondActivity.class); startActivity(intent4); } }); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaPlayer19.stop(); Intent intent16 = new Intent(HomePage2.this, HowtoPlay.class); startActivity(intent16); } }); } private void displayAd() { interstitialAd.show(); } private class MyTask2 extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { mediaPlayer19 = MediaPlayer.create(HomePage2.this, R.raw.zero0); mediaPlayer19.setLooping(true); mediaPlayer19.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }); return null; } } @Override public void onBackPressed() { mediaPlayer19.stop(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
true
4e1eddfef930f5289fbbae619696ea5aeefa8b4f
Java
magarciaroig/hadoop-fca
/fca-backend-app/src/main/java/com/mgarciaroig/fca/analysis/model/FormalConcept.java
UTF-8
8,831
2.453125
2
[ "Apache-2.0" ]
permissive
package com.mgarciaroig.fca.analysis.model; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.hadoop.io.Writable; import com.mgarciaroig.fca.analysis.persistence.FormalContextItemRepository; /** * Class to modelize a FCA formal concept * * @author Miguel Ángel García Roig (rocho08@gmail.com) * */ public class FormalConcept extends IntentManager implements Writable { private TreeSet<String> objectIds; private TreeSet<String> sharedAttbs; private Integer cachedHashCode; /** * Default constructor (needed by serialization utilities) */ public FormalConcept(){ reset(); } /** * Constructor used for explicitly set the intent and extent for the new formal concept. It us useful in order to create the maximun * and minimun formal concepts in a cheap way * @param objectIds * @param sharedAttbs */ public FormalConcept(final List<String> objectIds, List<String> sharedAttbs){ this.cachedHashCode = null; this.objectIds = new TreeSet<>(objectIds); this.sharedAttbs = new TreeSet<>(sharedAttbs); } /** * Build formal context from object list (calculates shared attributes from objects) * @param objects * @throws FormalConceptNonConsistentAttributesException */ public FormalConcept(final Collection<FormalContextItem> objects) throws FormalConceptNonConsistentAttributesException{ this(objects, null); } /** * Build formal context by object list and shared attributes list (tipically used in the FCA first step) * @param objects * @param sharedAttbs * @throws FormalConceptNonConsistentAttributesException */ public FormalConcept(final Collection<FormalContextItem> objects, final Collection<String> sharedAttbs) throws FormalConceptNonConsistentAttributesException{ this.cachedHashCode = null; this.objectIds = populateObjectIds(objects); if (sharedAttbs != null){ checkObjectsAndAttributesConsistencyGuard(objects, sharedAttbs); this.sharedAttbs = populateAttbs(sharedAttbs); } else { this.sharedAttbs = populateAttbsFromObjects(objects); } } /** * Build and new formal context adding a new attribute * * @param objectRepository * @param newAttb * @return * @throws IOException * @throws FormalConceptNonConsistentAttributesException */ public FormalConcept deriveNewFormalConcept(final FormalContextItemRepository objectRepository, final String newAttb) throws IOException, FormalConceptNonConsistentAttributesException{ List<FormalContextItem> objects = new ArrayList<FormalContextItem>(); final List<String> allObjectIdsWithNewAttb = objectRepository.findObjectIdsByAttribute(newAttb); final List<String> myObjectIdsWithNewAttb = myObjectIdsIntersectionWith(allObjectIdsWithNewAttb); if (myObjectIdsWithNewAttb.size() > 0){ objects = objectRepository.find(myObjectIdsWithNewAttb); } return new FormalConcept(objects); } /** * Build a new key adding a new attribute * @param newAttribute * @return */ public FormalConceptBuildingKey deriveNewBuildingKey(final String newAttribute){ return new FormalConceptBuildingKey(this.sharedAttbs, newAttribute); } public TreeSet<String> getObjects(){ return new TreeSet<String>(this.objectIds); } public TreeSet<String> getAttributes(){ return new TreeSet<String>(this.sharedAttbs); } public boolean hasObject(final String objectId){ return containsElement(objectIds, objectId); } public boolean hasAttb(final String attb){ return containsElement(sharedAttbs, attb); } public Set<String> attributesUpTo(final String toAttribute){ return super.attributesUpTo(this.sharedAttbs, toAttribute); } public boolean extentIsEmpty(){ return this.objectIds.isEmpty(); } @Override public String toString(){ String separator = ", "; final StringBuilder sb = new StringBuilder(getClass().getSimpleName()); sb.append(" ["); sb.append("objects: {"); sb.append(StringUtils.join(this.objectIds, separator)); sb.append("}, atributes: {"); sb.append(StringUtils.join(this.sharedAttbs, separator)); sb.append("} ]"); return sb.toString(); } @Override public boolean equals(final Object other){ boolean weAreEquivalent = false; if (other instanceof FormalConcept){ final FormalConcept otherFormalConcept = (FormalConcept) other; final EqualsBuilder equalsBuilder = new EqualsBuilder(); equalsBuilder.append(this.objectIds, otherFormalConcept.objectIds); equalsBuilder.append(this.sharedAttbs, otherFormalConcept.sharedAttbs); weAreEquivalent = equalsBuilder.isEquals(); } return weAreEquivalent; } @Override public int hashCode(){ if (this.cachedHashCode == null){ this.cachedHashCode = toString().hashCode(); } return this.cachedHashCode; } @Override public void readFields(final DataInput in) throws IOException { reset(); int itemsToRead = in.readInt(); for (int currentObjectIndex = 0; currentObjectIndex < itemsToRead; currentObjectIndex++){ this.objectIds.add(in.readUTF()); } itemsToRead = in.readInt(); for (int currentAttbIndex = 0; currentAttbIndex < itemsToRead; currentAttbIndex++){ this.sharedAttbs.add(in.readUTF()); } } @Override public void write(final DataOutput out) throws IOException { out.writeInt(this.objectIds.size()); for (final String currentObjectId : this.objectIds){ out.writeUTF(currentObjectId); } out.writeInt(this.sharedAttbs.size()); for (final String currentAttb : this.sharedAttbs){ out.writeUTF(currentAttb); } } private void reset(){ this.cachedHashCode = null; this.objectIds = new TreeSet<String>(); this.sharedAttbs = new TreeSet<String>(); } private void checkObjectsAndAttributesConsistencyGuard(final Collection<FormalContextItem> objects, final Collection<String> sharedAttbs) throws FormalConceptNonConsistentAttributesException { for (final String currentAttb : sharedAttbs){ checkAtributeSharedByAllGuard(objects, currentAttb); } } private void checkAtributeSharedByAllGuard(final Collection<FormalContextItem> objects, final String sharedAttb) throws FormalConceptNonConsistentAttributesException{ for (final FormalContextItem currentObject : objects){ if (!currentObject.hasAttb(sharedAttb)) { throw new FormalConceptNonConsistentAttributesException(objects, sharedAttbs); } } } private boolean containsElement(final Collection<String> store, final String element){ return store.contains(element); } private TreeSet<String> populateAttbs(final Collection<String> attbs) { final TreeSet<String> nonRepeatedAttbs = new TreeSet<String>(); for (final String currentAttb : attbs){ nonRepeatedAttbs.add(currentAttb); } return nonRepeatedAttbs; } private TreeSet<String> populateAttbsFromObjects(final Collection<FormalContextItem> objects) { final TreeSet<String> attbsSharedByAll = new TreeSet<String>(); if (noObjectsAvailable(objects)) return attbsSharedByAll; for (final String currentAttb : allAttbNamesInOrder(objects)){ if (attbIsSharedByAll(objects, currentAttb)){ attbsSharedByAll.add(currentAttb); } } return attbsSharedByAll; } private List<String> myObjectIdsIntersectionWith(final List<String> otherObjectIds){ final ArrayList<String> intersected = new ArrayList<String>(otherObjectIds); intersected.retainAll(this.objectIds); return intersected; } private boolean attbIsSharedByAll(final Collection<FormalContextItem> objects, final String currentAttb) { final Iterator<FormalContextItem> it = objects.iterator(); boolean attSharedByAll = true; while (it.hasNext()){ if (!it.next().hasAttb(currentAttb)){ attSharedByAll = false; break; } } return attSharedByAll; } private List<String> allAttbNamesInOrder(final Collection<FormalContextItem> objects){ if (noObjectsAvailable(objects)) return new ArrayList<String>(); return objects.iterator().next().allAttbNamesInOrder(); } private boolean noObjectsAvailable(final Collection<FormalContextItem> objects) { return objects == null || objects.size() < 1; } private TreeSet<String> populateObjectIds(final Collection<FormalContextItem> objects){ final TreeSet<String> ids = new TreeSet<String>(); for (final FormalContextItem currentObject : objects){ ids.add(currentObject.getObjectId()); } return ids; } }
true
121f2f1691ac72d2c59fb5232937aa7b725623b4
Java
roukell/seleniumPrac
/src/Safaridriver.java
UTF-8
1,687
2.75
3
[]
no_license
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.safari.SafariDriver; import org.openqa.selenium.support.ui.Select; public class Safaridriver { public static void main(String[] args) throws InterruptedException { // testing on Safari now System.setProperty("webdriver.safari.driver", "//usr//bin//safaridriver"); WebDriver driver = new SafariDriver(); driver.get("https://rahulshettyacademy.com/dropdownsPractise/"); System.out.println(driver.getTitle()); //dropdown with <select> tag (aka static dropdown) WebElement staticDropdown = driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")); Select dropdown = new Select(staticDropdown); // if static dropdown, we can select dropdown by index dropdown.selectByIndex(3); // we can select dropdown by visible text dropdown.selectByVisibleText("AED"); // we can select dropdown by value attribute dropdown.selectByValue("INR"); // to varify if a dropdown is selected correctly, to the following and get text String selectedDropdown = dropdown.getFirstSelectedOption().getText(); System.out.println(selectedDropdown); driver.findElement(By.id("divpaxinfo")).click(); Thread.sleep(2000); // not a good practice, but leave it for now. String passengerNum = driver.findElement(By.id("divpaxinfo")).getText(); System.out.println(passengerNum); for (int i = 1; i < 5; i++) { driver.findElement(By.id("hrefIncAdt")).click(); }; String passengerNum1 = driver.findElement(By.id("divpaxinfo")).getText(); System.out.println(passengerNum1); driver.quit(); } }
true
e78adcb8a3e0757ac42e314899516fa68e3d04bd
Java
victorcastanogutierrez/OCAM-android
/app/src/main/java/com/ocam/osm/maptypes/PNOAIGN.java
UTF-8
1,361
2.015625
2
[]
no_license
package com.ocam.osm.maptypes; import com.ocam.model.types.GPSPoint; import org.osmdroid.tileprovider.MapTile; import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase; import org.osmdroid.views.MapView; import static com.ocam.osm.maptypes.MapTypesUtil.getPointFromXY; public class PNOAIGN extends BaseMapType { public PNOAIGN(String mapName) { super(mapName); } @Override public void setMap(MapView mapView) { mapView.setTileSource(new OnlineTileSourceBase(getMapTypeName(), 0, 18, 256, "", new String[] { "http://www.ign.es/wms-inspire/pnoa-ma?request=GetMap&service=WMS&VERSION=1.3.0&LAYERS=OI.OrthoimageCoverage&STYLES=&FORMAT=image/png&BGCOLOR=0xFFFFFF&TRANSPARENT=TRUE&CRS=EPSG:4326&WIDTH=250&HEIGHT=250&BBOX="}) { @Override public String getTileURLString(MapTile aTile) { double zpow = Math.pow(2, aTile.getZoomLevel()); GPSPoint ulw = getPointFromXY(aTile.getX() * 256.0 / zpow, (aTile.getY() + 1) * 256.0 / zpow); GPSPoint lrw = getPointFromXY((aTile.getX() + 1) * 256.0 / zpow, (aTile.getY()) * 256.0 / zpow); String bbox = ulw.getLatitude() + "," + ulw.getLongitude() + "," + lrw.getLatitude() + "," + lrw.getLongitude(); return getBaseUrl() + bbox; } }); } }
true
e59f0bba638576ac35aac3becc99e6c672f7096b
Java
Ignatovw99/SoftUni
/Java OOP - 2019/01. Working with Abstraction - Lab and Exercise/src/greedytimes/Bag.java
UTF-8
5,362
3.1875
3
[]
no_license
package greedytimes; import java.util.ArrayList; import java.util.Comparator; public class Bag { private static Comparator<Item> DEFAULT_COMPARATOR = ((first, second) -> { int nameCompare = second.getType().compareTo(first.getType()); if (nameCompare == 0) { return Long.compare(first.getQuantity(), second.getQuantity()); } return nameCompare; }); private long capacity; private long fullness; private ArrayList<Cash> cashItems; private ArrayList<Gem> gemItems; private Gold gold; private long goldAmount; private long gemAmount; private long cashAmount; public Bag(long capacity) { this.capacity = capacity; this.fullness = 0; this.cashItems = new ArrayList<>(); this.gemItems = new ArrayList<>(); } public void fillTheBag(Treasure treasure) { ArrayList<Item> validItems = treasure.getValidItems(); for (Item item : validItems) { if (this.canContainItem(item.getQuantity(), item.getClass().getSimpleName())) { if (item instanceof Cash) { int indexOfItem = Bag.getItemByIndex(item, this.cashItems); if (indexOfItem == -1) { this.cashItems.add(new Cash(item.getType(), item.getQuantity())); } else { this.cashItems.get(indexOfItem).increaseQuantity(item.getQuantity()); } this.cashAmount += item.getQuantity(); } else if (item instanceof Gem) { int indexOfItem = Bag.getItemByIndex(item, this.gemItems); if (indexOfItem == -1) { this.gemItems.add(new Gem(item.getType(), item.getQuantity())); } else { this.gemItems.get(indexOfItem).increaseQuantity(item.getQuantity()); } this.gemAmount += item.getQuantity(); } else if (item instanceof Gold) { if (this.gold != null) { this.gold.increaseQuantity(item.getQuantity()); } else { this.gold = new Gold(item.getType(), item.getQuantity()); } this.goldAmount += item.getQuantity(); } this.fullness += item.getQuantity(); } } } private static <T extends Item> int getItemByIndex(Item item, ArrayList<T> cashItems) { for (int i = 0; i < cashItems.size(); i++) { if (item.getType().equals(cashItems.get(i).getType())) { return i; } } return -1; } private boolean canContainItem(int quantity, String itemType) { boolean canItemBePushed = this.fullness + quantity <= this.capacity; boolean conditionForAdding = false; switch (itemType) { case "Cash": conditionForAdding = this.goldAmount >= this.gemAmount && this.gemAmount >= this.cashAmount + quantity; break; case "Gem": conditionForAdding = this.goldAmount >= this.gemAmount + quantity && this.gemAmount + quantity >= this.cashAmount; break; case "Gold": conditionForAdding = this.goldAmount + quantity >= this.gemAmount && this.gemAmount >= this.cashAmount; } return canItemBePushed && conditionForAdding; } @Override public String toString() { StringBuilder builder = new StringBuilder(); String goldInfo = this.getGoldInfo(); if (goldInfo != null) { builder.append(goldInfo); } String gemInfo = this.getGemInfo(); if (gemInfo != null) { builder.append(gemInfo); } String cashInfo = this.getCashInfo(); if (cashInfo != null) { builder.append(cashInfo); } return builder.toString(); } private String getCashInfo() { if (this.cashItems.size() == 0) {return null;} StringBuilder builder = new StringBuilder(); builder.append("<Cash> $").append(String.format("%d%n", this.cashAmount)); this.cashItems.sort(Bag.DEFAULT_COMPARATOR); for (Cash cashItem : this.cashItems) { builder.append(cashItem.toString()).append(System.lineSeparator()); } return builder.toString(); } private String getGemInfo() { if (this.gemItems.size() == 0) { return null; } StringBuilder builder = new StringBuilder(); builder.append("<Gem> $").append(String.format("%d%n", this.gemAmount)); this.gemItems.sort(Bag.DEFAULT_COMPARATOR); for (Gem item : this.gemItems) { builder.append(item.toString()).append(System.lineSeparator()); } return builder.toString(); } private String getGoldInfo() { if (this.gold == null) { return null; } StringBuilder builder = new StringBuilder(); builder.append("<Gold> $").append(String.format("%d%n", this.goldAmount)); builder.append(this.gold.toString()).append(System.lineSeparator()); return builder.toString(); } }
true
964d640eed420b6c9e72149d068a97a6fc103251
Java
eduardovaloisfranz/estrutura-de-dados
/estruturaDeDados/src/implementacaoListaComEncadeamento/ListaComEncadeamento.java
UTF-8
5,390
3.3125
3
[]
no_license
package implementacaoListaComEncadeamento; public class ListaComEncadeamento{ private NoLista first; private NoLista last; private int counter; public ListaComEncadeamento() { this.counter = 0; this.first = null; this.last = null; } public void add(Integer info) { if(info == null) { throw new NullPointerException("You cant give null info"); }else { if(counter == 0) { this.first = new NoLista(info, null); this.last = first; }else { NoLista novo = new NoLista(info, null); this.last.setNext(novo); this.last = novo; } this.counter++; } } public void add(Integer info, int index) { if(info == null) { throw new NullPointerException("You cant give null info"); } if(index < 0 || index > counter) { throw new IndexOutOfBoundsException("The position is invalid"); } int counter = 0; NoLista temp = first; NoLista elementByIndexAsc = null; NoLista elementByIndex= null; while(temp != null) { if(counter == index - 1) { elementByIndexAsc = temp; } if(counter == index) { elementByIndex = temp; } counter++; temp = temp.getNext(); } NoLista novo = new NoLista(info, elementByIndex); elementByIndexAsc.setNext(novo); this.counter++; } public Integer remove(int index) { if(index < 0 || index > counter) { throw new IndexOutOfBoundsException("Invalid index"); } Integer oldValue = null; NoLista temp = first; NoLista previousElement = null; NoLista nextElement = null; int counter = 0; while(temp != null) { if(counter == index - 1) { previousElement = temp; } if(counter == index + 1) { nextElement = temp; } counter++; temp = temp.getNext(); } oldValue = previousElement.getNext().getInfo(); previousElement.setNext(nextElement); this.counter--; return oldValue; } public boolean removeFirst(Integer info) { boolean infoExists = false; if(info == null) { throw new NullPointerException("You cant give null info"); } NoLista temp = first; int counter = 0; while(temp != null) { if(info.equals(temp.getInfo())) { remove(counter); infoExists = true; } counter++; temp = temp.getNext(); } return infoExists; } public Integer get(int index) { if(index < 0 || index > counter) { throw new IndexOutOfBoundsException("Invalid index"); } Integer info = null; NoLista temp = first; int counter = 0; while(temp != null) { if(index == counter) { info = temp.getInfo(); } counter++; temp = temp.getNext(); } return info; } public Integer set(int index, Integer info) { if(index < 0 || index > counter) { throw new IndexOutOfBoundsException("Invalid Index"); } if(info == null) { throw new NullPointerException("You cant give null info"); } Integer oldInfo = null; NoLista temp = first; int counter = 0; while(temp != null) { if(index == counter) { oldInfo = temp.getInfo(); temp.setInfo(info); } counter++; temp = temp.getNext(); } return oldInfo; } public boolean isEmpty() { if(counter == 0) { return true; }else { return false; } } public void clear() { this.first = null; this.last = null; this.counter = 0; } public boolean contains(Integer info) { if(info == null) { throw new NullPointerException("You cant give null info"); } NoLista temp = first; while(temp != null) { if(temp.getInfo().equals(info)) { return true; } temp = temp.getNext(); } return false; } public int indexOf(Integer info) { if(info == null) { throw new NullPointerException("You cant give null info"); } NoLista temp = first; int counter = 0; while(temp != null) { if(temp.getInfo().equals(info)) { return counter; } counter++; temp = temp.getNext(); } return -1; } private NoLista getNoListaByIndex (int index) { if(index < 0 || index > counter) { throw new IndexOutOfBoundsException("Invalid index"); } NoLista noLista = null; NoLista temp = first; int counter = 0; while(temp != null) { if(index == counter) { noLista = temp; } counter++; temp = temp.getNext(); } return noLista; } public int lastIndexOf(Integer info) { if(info == null) { throw new NullPointerException("You cant give null info"); } if(indexOf(info) == -1) { return -1; } int firstIndex = indexOf(info); int lastIndex = 0; NoLista temp = getNoListaByIndex(firstIndex); while(temp != null) { if(temp.getInfo().equals(info)) { lastIndex = firstIndex; } firstIndex++; temp = temp.getNext(); } if(lastIndex == 0) { return -1; }else { return lastIndex; } } public Integer[] toArray() { Integer[] arr = new Integer[counter]; NoLista temp = first; int counter = 0; while(temp != null){ arr[counter] = temp.getInfo(); counter++; temp = temp.getNext(); } return arr; } public int size() { return this.counter; } @Override public String toString() { String info = " [ "; NoLista temp = first; do { //System.out.println("Atual: " + temp + " Proximo: " + temp.getNext()); info += "{ Atual: " + temp + " Proximo: " + temp.getNext() + " }"; temp = temp.getNext(); }while(temp != null); return info += " ]"; } }
true
fc2e7e62c7815f9810063ff1be87984ea99c38c2
Java
longdm10/DuongBoDoanhNghiepApp-portlet
/docroot/WEB-INF/src/vn/dtt/duongbien/dao/vrcb/model/DmHistoryUnitGeneralWrapper.java
UTF-8
10,843
1.984375
2
[]
no_license
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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. */ package vn.dtt.duongbien.dao.vrcb.model; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.ModelWrapper; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * <p> * This class is a wrapper for {@link DmHistoryUnitGeneral}. * </p> * * @author longdm * @see DmHistoryUnitGeneral * @generated */ public class DmHistoryUnitGeneralWrapper implements DmHistoryUnitGeneral, ModelWrapper<DmHistoryUnitGeneral> { public DmHistoryUnitGeneralWrapper( DmHistoryUnitGeneral dmHistoryUnitGeneral) { _dmHistoryUnitGeneral = dmHistoryUnitGeneral; } @Override public Class<?> getModelClass() { return DmHistoryUnitGeneral.class; } @Override public String getModelClassName() { return DmHistoryUnitGeneral.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("id", getId()); attributes.put("unitCode", getUnitCode()); attributes.put("unitName", getUnitName()); attributes.put("isDelete", getIsDelete()); attributes.put("markedAsDelete", getMarkedAsDelete()); attributes.put("modifiedDate", getModifiedDate()); attributes.put("requestedDate", getRequestedDate()); attributes.put("syncVersion", getSyncVersion()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Integer id = (Integer)attributes.get("id"); if (id != null) { setId(id); } String unitCode = (String)attributes.get("unitCode"); if (unitCode != null) { setUnitCode(unitCode); } String unitName = (String)attributes.get("unitName"); if (unitName != null) { setUnitName(unitName); } Integer isDelete = (Integer)attributes.get("isDelete"); if (isDelete != null) { setIsDelete(isDelete); } Integer markedAsDelete = (Integer)attributes.get("markedAsDelete"); if (markedAsDelete != null) { setMarkedAsDelete(markedAsDelete); } Date modifiedDate = (Date)attributes.get("modifiedDate"); if (modifiedDate != null) { setModifiedDate(modifiedDate); } Date requestedDate = (Date)attributes.get("requestedDate"); if (requestedDate != null) { setRequestedDate(requestedDate); } String syncVersion = (String)attributes.get("syncVersion"); if (syncVersion != null) { setSyncVersion(syncVersion); } } /** * Returns the primary key of this dm history unit general. * * @return the primary key of this dm history unit general */ @Override public int getPrimaryKey() { return _dmHistoryUnitGeneral.getPrimaryKey(); } /** * Sets the primary key of this dm history unit general. * * @param primaryKey the primary key of this dm history unit general */ @Override public void setPrimaryKey(int primaryKey) { _dmHistoryUnitGeneral.setPrimaryKey(primaryKey); } /** * Returns the ID of this dm history unit general. * * @return the ID of this dm history unit general */ @Override public int getId() { return _dmHistoryUnitGeneral.getId(); } /** * Sets the ID of this dm history unit general. * * @param id the ID of this dm history unit general */ @Override public void setId(int id) { _dmHistoryUnitGeneral.setId(id); } /** * Returns the unit code of this dm history unit general. * * @return the unit code of this dm history unit general */ @Override public java.lang.String getUnitCode() { return _dmHistoryUnitGeneral.getUnitCode(); } /** * Sets the unit code of this dm history unit general. * * @param unitCode the unit code of this dm history unit general */ @Override public void setUnitCode(java.lang.String unitCode) { _dmHistoryUnitGeneral.setUnitCode(unitCode); } /** * Returns the unit name of this dm history unit general. * * @return the unit name of this dm history unit general */ @Override public java.lang.String getUnitName() { return _dmHistoryUnitGeneral.getUnitName(); } /** * Sets the unit name of this dm history unit general. * * @param unitName the unit name of this dm history unit general */ @Override public void setUnitName(java.lang.String unitName) { _dmHistoryUnitGeneral.setUnitName(unitName); } /** * Returns the is delete of this dm history unit general. * * @return the is delete of this dm history unit general */ @Override public int getIsDelete() { return _dmHistoryUnitGeneral.getIsDelete(); } /** * Sets the is delete of this dm history unit general. * * @param isDelete the is delete of this dm history unit general */ @Override public void setIsDelete(int isDelete) { _dmHistoryUnitGeneral.setIsDelete(isDelete); } /** * Returns the marked as delete of this dm history unit general. * * @return the marked as delete of this dm history unit general */ @Override public int getMarkedAsDelete() { return _dmHistoryUnitGeneral.getMarkedAsDelete(); } /** * Sets the marked as delete of this dm history unit general. * * @param markedAsDelete the marked as delete of this dm history unit general */ @Override public void setMarkedAsDelete(int markedAsDelete) { _dmHistoryUnitGeneral.setMarkedAsDelete(markedAsDelete); } /** * Returns the modified date of this dm history unit general. * * @return the modified date of this dm history unit general */ @Override public java.util.Date getModifiedDate() { return _dmHistoryUnitGeneral.getModifiedDate(); } /** * Sets the modified date of this dm history unit general. * * @param modifiedDate the modified date of this dm history unit general */ @Override public void setModifiedDate(java.util.Date modifiedDate) { _dmHistoryUnitGeneral.setModifiedDate(modifiedDate); } /** * Returns the requested date of this dm history unit general. * * @return the requested date of this dm history unit general */ @Override public java.util.Date getRequestedDate() { return _dmHistoryUnitGeneral.getRequestedDate(); } /** * Sets the requested date of this dm history unit general. * * @param requestedDate the requested date of this dm history unit general */ @Override public void setRequestedDate(java.util.Date requestedDate) { _dmHistoryUnitGeneral.setRequestedDate(requestedDate); } /** * Returns the sync version of this dm history unit general. * * @return the sync version of this dm history unit general */ @Override public java.lang.String getSyncVersion() { return _dmHistoryUnitGeneral.getSyncVersion(); } /** * Sets the sync version of this dm history unit general. * * @param syncVersion the sync version of this dm history unit general */ @Override public void setSyncVersion(java.lang.String syncVersion) { _dmHistoryUnitGeneral.setSyncVersion(syncVersion); } @Override public boolean isNew() { return _dmHistoryUnitGeneral.isNew(); } @Override public void setNew(boolean n) { _dmHistoryUnitGeneral.setNew(n); } @Override public boolean isCachedModel() { return _dmHistoryUnitGeneral.isCachedModel(); } @Override public void setCachedModel(boolean cachedModel) { _dmHistoryUnitGeneral.setCachedModel(cachedModel); } @Override public boolean isEscapedModel() { return _dmHistoryUnitGeneral.isEscapedModel(); } @Override public java.io.Serializable getPrimaryKeyObj() { return _dmHistoryUnitGeneral.getPrimaryKeyObj(); } @Override public void setPrimaryKeyObj(java.io.Serializable primaryKeyObj) { _dmHistoryUnitGeneral.setPrimaryKeyObj(primaryKeyObj); } @Override public com.liferay.portlet.expando.model.ExpandoBridge getExpandoBridge() { return _dmHistoryUnitGeneral.getExpandoBridge(); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.model.BaseModel<?> baseModel) { _dmHistoryUnitGeneral.setExpandoBridgeAttributes(baseModel); } @Override public void setExpandoBridgeAttributes( com.liferay.portlet.expando.model.ExpandoBridge expandoBridge) { _dmHistoryUnitGeneral.setExpandoBridgeAttributes(expandoBridge); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.service.ServiceContext serviceContext) { _dmHistoryUnitGeneral.setExpandoBridgeAttributes(serviceContext); } @Override public java.lang.Object clone() { return new DmHistoryUnitGeneralWrapper((DmHistoryUnitGeneral)_dmHistoryUnitGeneral.clone()); } @Override public int compareTo( vn.dtt.duongbien.dao.vrcb.model.DmHistoryUnitGeneral dmHistoryUnitGeneral) { return _dmHistoryUnitGeneral.compareTo(dmHistoryUnitGeneral); } @Override public int hashCode() { return _dmHistoryUnitGeneral.hashCode(); } @Override public com.liferay.portal.model.CacheModel<vn.dtt.duongbien.dao.vrcb.model.DmHistoryUnitGeneral> toCacheModel() { return _dmHistoryUnitGeneral.toCacheModel(); } @Override public vn.dtt.duongbien.dao.vrcb.model.DmHistoryUnitGeneral toEscapedModel() { return new DmHistoryUnitGeneralWrapper(_dmHistoryUnitGeneral.toEscapedModel()); } @Override public vn.dtt.duongbien.dao.vrcb.model.DmHistoryUnitGeneral toUnescapedModel() { return new DmHistoryUnitGeneralWrapper(_dmHistoryUnitGeneral.toUnescapedModel()); } @Override public java.lang.String toString() { return _dmHistoryUnitGeneral.toString(); } @Override public java.lang.String toXmlString() { return _dmHistoryUnitGeneral.toXmlString(); } @Override public void persist() throws com.liferay.portal.kernel.exception.SystemException { _dmHistoryUnitGeneral.persist(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DmHistoryUnitGeneralWrapper)) { return false; } DmHistoryUnitGeneralWrapper dmHistoryUnitGeneralWrapper = (DmHistoryUnitGeneralWrapper)obj; if (Validator.equals(_dmHistoryUnitGeneral, dmHistoryUnitGeneralWrapper._dmHistoryUnitGeneral)) { return true; } return false; } /** * @deprecated As of 6.1.0, replaced by {@link #getWrappedModel} */ public DmHistoryUnitGeneral getWrappedDmHistoryUnitGeneral() { return _dmHistoryUnitGeneral; } @Override public DmHistoryUnitGeneral getWrappedModel() { return _dmHistoryUnitGeneral; } @Override public void resetOriginalValues() { _dmHistoryUnitGeneral.resetOriginalValues(); } private DmHistoryUnitGeneral _dmHistoryUnitGeneral; }
true
4b39a2a9497f87fdedab592133726ac8499aaff8
Java
yeogini/blog
/blog/src/main/java/com/yedam/blog/reply/impl/ReplyMapper.java
UTF-8
336
1.609375
2
[]
no_license
package com.yedam.blog.reply.impl; import java.util.List; import com.yedam.blog.reply.ReplyVO; public interface ReplyMapper { public List<ReplyVO> getReplyList(ReplyVO replyvo); public void insertReply(ReplyVO replyvo); public void deleteReply(ReplyVO replyvo); public ReplyVO getReply (ReplyVO replyvo); }
true
1100fccb529377de0685e0179591225dadb38492
Java
aliyun/aliyun-openapi-java-sdk
/aliyun-java-sdk-live/src/main/java/com/aliyuncs/live/transform/v20161101/DescribeCasterScenesResponseUnmarshaller.java
UTF-8
3,456
1.703125
2
[ "Apache-2.0" ]
permissive
/* * 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.aliyuncs.live.transform.v20161101; import java.util.ArrayList; import java.util.List; import com.aliyuncs.live.model.v20161101.DescribeCasterScenesResponse; import com.aliyuncs.live.model.v20161101.DescribeCasterScenesResponse.Scene; import com.aliyuncs.live.model.v20161101.DescribeCasterScenesResponse.Scene.StreamInfo; import com.aliyuncs.transform.UnmarshallerContext; public class DescribeCasterScenesResponseUnmarshaller { public static DescribeCasterScenesResponse unmarshall(DescribeCasterScenesResponse describeCasterScenesResponse, UnmarshallerContext _ctx) { describeCasterScenesResponse.setRequestId(_ctx.stringValue("DescribeCasterScenesResponse.RequestId")); describeCasterScenesResponse.setTotal(_ctx.integerValue("DescribeCasterScenesResponse.Total")); List<Scene> sceneList = new ArrayList<Scene>(); for (int i = 0; i < _ctx.lengthValue("DescribeCasterScenesResponse.SceneList.Length"); i++) { Scene scene = new Scene(); scene.setStatus(_ctx.integerValue("DescribeCasterScenesResponse.SceneList["+ i +"].Status")); scene.setLayoutId(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].LayoutId")); scene.setOutputType(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].OutputType")); scene.setRtsUrl(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].RtsUrl")); scene.setSceneId(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].SceneId")); scene.setSceneName(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].SceneName")); scene.setStreamUrl(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].StreamUrl")); List<String> componentIds = new ArrayList<String>(); for (int j = 0; j < _ctx.lengthValue("DescribeCasterScenesResponse.SceneList["+ i +"].ComponentIds.Length"); j++) { componentIds.add(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].ComponentIds["+ j +"]")); } scene.setComponentIds(componentIds); List<StreamInfo> streamInfos = new ArrayList<StreamInfo>(); for (int j = 0; j < _ctx.lengthValue("DescribeCasterScenesResponse.SceneList["+ i +"].StreamInfos.Length"); j++) { StreamInfo streamInfo = new StreamInfo(); streamInfo.setVideoFormat(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].StreamInfos["+ j +"].VideoFormat")); streamInfo.setOutputStreamUrl(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].StreamInfos["+ j +"].OutputStreamUrl")); streamInfo.setTranscodeConfig(_ctx.stringValue("DescribeCasterScenesResponse.SceneList["+ i +"].StreamInfos["+ j +"].TranscodeConfig")); streamInfos.add(streamInfo); } scene.setStreamInfos(streamInfos); sceneList.add(scene); } describeCasterScenesResponse.setSceneList(sceneList); return describeCasterScenesResponse; } }
true
297bcfacfad0f165d3e1687286f6e98f26da3533
Java
kilodleif/hm-spring-boot
/src/main/java/cn/zsh/hmspringboot/controller/HmFoodController.java
UTF-8
1,585
2.15625
2
[]
no_license
package cn.zsh.hmspringboot.controller; import cn.zsh.hmspringboot.dto.HmFood; import cn.zsh.hmspringboot.service.IHmFoodService; import cn.zsh.hmspringboot.util.ReturnData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * @author kilodleif */ @Controller @RequestMapping("food") public class HmFoodController { @Autowired private IHmFoodService service; @RequestMapping(value = "/queryAvailable") @ResponseBody public ReturnData queryAvailable(HmFood condition, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int pageSize) { return new ReturnData(service.queryAvailableFood(condition, page, pageSize)); } @RequestMapping(value = "/query") @ResponseBody public ReturnData queryAll(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int pageSize) { return new ReturnData(service.queryAll(page, pageSize)); } @RequestMapping(value = "/add") @ResponseBody public boolean add(@RequestBody HmFood food) { service.addFood(food); return true; } @RequestMapping(value = "/update") @ResponseBody public boolean update(@RequestBody HmFood food) { service.updateFood(food); return true; } }
true
1b6634210ba4bb3226399af081796f9d5e5f0af2
Java
zhangxunice/douyinvideoServer
/src/main/java/com/douyin/douyinvideo/vo/UsersVO.java
UTF-8
1,795
2.171875
2
[]
no_license
package com.douyin.douyinvideo.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter @ApiModel(value="用户对象", description="这是用户对象") public class UsersVO { private String id; /** * 用户名 */ @ApiModelProperty(value="用户名", name="username", example="imoocuser", required=true) private String username; /** * 密码 */ @ApiModelProperty(value="密码", name="password", example="123456", required=true) private String password; /** * 我的头像,如果没有默认给一张 */ @ApiModelProperty(hidden=true) private String faceImage; /** * 昵称 */ @ApiModelProperty(hidden=true) private String nickname; /** * 我的粉丝数量 */ @ApiModelProperty(hidden=true) private Integer fansCounts; /** * 我关注的人总数 */ @ApiModelProperty(hidden=true) private Integer followCounts; /** * 我接受到的赞美/收藏 的数量 */ @ApiModelProperty(hidden=true) private Integer receiveLikeCounts; private Boolean isFollow; public UsersVO() { super(); } public UsersVO(String id, String username, String password, String faceImage, String nickname, Integer fansCounts, Integer followCounts, Integer receiveLikeCounts, Boolean isFollow) { this.id = id; this.username = username; this.password = password; this.faceImage = faceImage; this.nickname = nickname; this.fansCounts = fansCounts; this.followCounts = followCounts; this.receiveLikeCounts = receiveLikeCounts; this.isFollow = isFollow; } }
true
ee569bb4dcf0252d6051b78e09d73cc4af4b3876
Java
liuxiaohu1810A/My-Ergedd
/app/src/main/java/com/example/myergedd/fragment/hear/music/contract/Music.java
UTF-8
564
1.929688
2
[]
no_license
package com.example.myergedd.fragment.hear.music.contract; import com.example.myergedd.base.BaseCallBack; import com.example.myergedd.bean.EnglishBean; import com.example.myergedd.bean.MusicBean; import java.util.List; public interface Music { public interface MusicView { void onSuccess(List<MusicBean> musicBeanList); void onFailed(String error); } public interface MusicModel { void getMusic(BaseCallBack<List<MusicBean>> musicCallBack); } public interface MusicPresenter { void setMusicData(); } }
true
729f829968ea76a2475eedbcd8e2e0bc5b449834
Java
sadeghebadi/Test-Keyboard-in-my-first-java-Program
/MahdaClient/src/ir/rayacell/mahdaclient/executer/CallServerExecuter.java
UTF-8
557
2.1875
2
[]
no_license
package ir.rayacell.mahdaclient.executer; import ir.rayacell.mahdaclient.manager.Container; import android.content.Intent; import android.net.Uri; import android.util.Log; public class CallServerExecuter { public void startCall(String number){ Uri tel = Uri.parse("tel:" + number); Intent callIntent = new Intent(Intent.ACTION_CALL, tel); Log.d("number", tel + "))))))))))))))))))((((((((((((("); if (callIntent.resolveActivity(Container.activity .getPackageManager()) != null) { Container.activity.startActivity(callIntent); } } }
true
fddc60c7f0bef096217460355e8c79560d0db8d6
Java
Dseym/ArenaStream
/src/ru/dseymo/arenastream/ReloadArenaCMD.java
UTF-8
523
2.03125
2
[]
no_license
package ru.dseymo.arenastream; import org.bukkit.command.CommandSender; import ru.dseymo.libutils.mc.bukkit.Chat; import ru.dseymo.libutils.mc.bukkit.cmd.Command; import ru.dseymo.libutils.mc.core.cmd.Args; public class ReloadArenaCMD extends Command { public ReloadArenaCMD() { super("reloadarena", false, "arenastream.reload"); } @Override public boolean execute(CommandSender sender, Args args) { ArenaStream.getInstance().reloadConfigs(); Chat.SUCCESS.send(sender, "Success"); return true; } }
true
f4fcaf3dab19afbdd2b6ecb98a0c7d4a7ff59571
Java
rohit-ds360/SpringFormApp
/src/main/java/in/ashokit/service/StudentService.java
UTF-8
1,322
2.359375
2
[]
no_license
package in.ashokit.service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import in.ashokit.entity.Courses; import in.ashokit.entity.Gender; import in.ashokit.entity.Timings; import in.ashokit.repository.CoursesRepository; import in.ashokit.repository.GenderRepository; import in.ashokit.repository.TimingsRepository; @Service public class StudentService { @Autowired private GenderRepository genderRepo; @Autowired private CoursesRepository courseRepo; @Autowired private TimingsRepository timingRepo; public List<String> getGenders(){ List<Gender> findAll = genderRepo.findAll(); List<String> genders = new ArrayList<>(); findAll.forEach(gender ->{ genders.add(gender.getGenderName()); }); return genders; } public List<String> getCourses(){ List<Courses> findAll = courseRepo.findAll(); List<String> courses = new ArrayList<>(); findAll.forEach(course ->{ courses.add(course.getCourseName()); }); return courses; } public List<String> getTimings(){ List<Timings> findAll = timingRepo.findAll(); List<String> timings = new ArrayList<>(); findAll.forEach(timing -> { timings.add(timing.getTimingName()); }); return timings; } }
true
892f4f13354ef38a8df5b17916de57e4f7821273
Java
anjeludo/java-ddd-example
/src/mooc/main/tv/codely/mooc/notification/application/like/SendPushToSubscribersOnVideoLiked.java
UTF-8
634
2.59375
3
[]
no_license
package tv.codely.mooc.notification.application.like; import tv.codely.mooc.video.domain.VideoLiked; import tv.codely.shared.application.DomainEventSubscriber; public class SendPushToSubscribersOnVideoLiked implements DomainEventSubscriber<VideoLiked> { @Override public Class<VideoLiked> subscribedTo() { return VideoLiked.class; } @Override public void consume(VideoLiked event) { System.out.println( String.format( "Hey! User with ID <%s> liked video with title <%s>", event.userId(), event.title() ) ); } }
true
7f56c205f40ccaf03d705f772b7f2090a3cb0960
Java
findmyapp/restclientAndroid
/src/no/uka/findmyapp/android/rest/library/RestServiceHelper.java
UTF-8
2,168
2.359375
2
[]
no_license
package no.uka.findmyapp.android.rest.library; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import no.uka.findmyapp.android.rest.library.data.model.ServiceModel; import no.uka.findmyapp.android.rest.library.data.model.Temperature; import no.uka.findmyapp.android.rest.library.data.providers.SensorProvider; import android.content.Context; import android.content.Intent; import com.google.gson.reflect.TypeToken; /** * The rest service helper class, a singleton * which exposes a simple asynchronous * API to be used by the user interface. * * Responsibility * Prepare and send the Service request: * - Check if the method is already running * - Create the requested Intent * - Add the operation type and a unique request id * - Add the method specific parameters * - Add the binder callback * - Call {@link RestService#startService()} * - Return the request id * Handle the callback from the service * - Dispatch callbacks to the user interface listeners */ public class RestServiceHelper { /** * The singleton RestServiceHelper instance */ private static RestServiceHelper INSTANCE; public static enum Services {TEMP, XX} private RestServiceHelper() { } public static RestServiceHelper getInstance() { if(INSTANCE == null) { INSTANCE = new RestServiceHelper(); return INSTANCE; } return INSTANCE; } public void startServiceTest(Context context, ServiceModel serviceModel) { Intent selectIntent = new Intent(context, RestIntentService.class); selectIntent.putExtra("ServiceModel", serviceModel); context.startService(selectIntent); } public class ServiceReferenceFactory { public ServiceModel getService(Services service) { /* switch(service) { case TEMP : try { Type typeToken = new TypeToken<Temperature>(){}.getType(); String uri = ServicesConstants.SERVICE1_URI; return new ServiceModel(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case XX : break; } */ return null; } } }
true
b6b1bd082f59620954c0a280c2fbbb11e3f812fb
Java
MrBlobman/SpigotCommandLib
/src/main/java/io/github/mrblobman/spigotcommandlib/registry/CommandRegistry.java
UTF-8
21,627
1.78125
2
[ "MIT" ]
permissive
/* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; import io.github.mrblobman.spigotcommandlib.*; import io.github.mrblobman.spigotcommandlib.args.*; import io.github.mrblobman.spigotcommandlib.context.SimpleContextProvider; import io.github.mrblobman.spigotcommandlib.invocation.CommandMethodHandle; import io.github.mrblobman.spigotcommandlib.util.ChatUtils; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandMap; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.function.Predicate; import java.util.logging.Level; import java.util.stream.Collectors; import java.util.stream.Stream; public class CommandRegistry implements Listener { private static final String[] EMPTY_STR_ARRAY = new String[0]; private static final int CTX_INSENSITIVE_SENDER_PARAM_IDX = 0; private static final int CTX_SENSITIVE_CONTEXT_PARAM_IDX = 0; private static final int CTX_SENSITIVE_SENDER_PARAM_IDX = 1; private static final BitSet CTX_INSENSITIVE_IMPLICIT_PARAMS_IDX = new BitSet(); static { CTX_INSENSITIVE_IMPLICIT_PARAMS_IDX.set(CTX_INSENSITIVE_SENDER_PARAM_IDX); } private static final BitSet CTX_SENSITIVE_IMPLICIT_PARAMS_IDX = new BitSet(); static { CTX_SENSITIVE_IMPLICIT_PARAMS_IDX.set(CTX_SENSITIVE_CONTEXT_PARAM_IDX); CTX_SENSITIVE_IMPLICIT_PARAMS_IDX.set(CTX_SENSITIVE_SENDER_PARAM_IDX); } private final Map<String, SubCommand> baseCommands = new HashMap<>(); private final Map<SubCommand, CommandExecutor> executors = new HashMap<>(); private final BundleCleaner bundleCleaner; private final CommandMap bukkitCommandMap; private final CommandLib lib; CommandRegistry(CommandLib lib) throws InstantiationException { Method commandMap; try { commandMap = Bukkit.getServer().getClass().getMethod("getCommandMap"); } catch (NoSuchMethodException | SecurityException e) { throw new InstantiationException("Could not grab the command map from the bukkit server. " + e.getLocalizedMessage()); } Object rawMap; try { rawMap = commandMap.invoke(Bukkit.getServer()); } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) { throw new InstantiationException("Could not grab the command map from the bukkit server. " + e.getLocalizedMessage()); } if (!(rawMap instanceof CommandMap)) { throw new InstantiationException("Could not grab the command map from the bukkit server."); } this.bundleCleaner = new BundleCleaner(lib.getHook()); this.bukkitCommandMap = (CommandMap) rawMap; this.lib = lib; } public void register(CommandHandler commandHandler) throws HandlerCompilationException { for (Method method : commandHandler.getClass().getDeclaredMethods()) { CommandHandle handlerAnnotation = method.getAnnotation(CommandHandle.class); //Move on, this method isn't annotated if (handlerAnnotation == null) continue; String[] command = buildCommand(EMPTY_STR_ARRAY, handlerAnnotation.command(), method.getName()); CommandExecutor executor = buildContextInsensitiveCommand(method, commandHandler, command, handlerAnnotation.permission(), ChatUtils.splitAndColorLines(handlerAnnotation.description())); this.executors.put(executor.getTrigger(), executor); lib.getHook().getLogger().log(Level.INFO, "Successfully registered " + method.getName() + " in " + commandHandler.getClass().getSimpleName() + " for /" + Arrays.toString(handlerAnnotation.command()).replaceAll("[,\\[\\]]", "")); } } public void register(SubCommandHandler commandHandler, String... subCommandPrefix) throws HandlerCompilationException { register(commandHandler, CommandLib.NO_PERMISSION, subCommandPrefix); } public void register(SubCommandHandler commandHandler, String permission, String... subCommandPrefix) throws HandlerCompilationException { for (Method method : commandHandler.getClass().getDeclaredMethods()) { SubCommandHandle handlerAnnotation = method.getAnnotation(SubCommandHandle.class); //Move on, this method isn't annotated if (handlerAnnotation == null) continue; String[] command = buildCommand(subCommandPrefix, handlerAnnotation.command(), method.getName()); CommandExecutor executor = buildContextInsensitiveCommand(method, commandHandler, command, handlerAnnotation.permission().isEmpty() ? permission : handlerAnnotation.permission(), ChatUtils.splitAndColorLines(handlerAnnotation.description())); this.executors.put(executor.getTrigger(), executor); lib.getHook().getLogger().log(Level.INFO, "Successfully registered " + method.getName() + " in " + commandHandler.getClass().getSimpleName() + " for /" + Arrays.toString(command).replaceAll("[,\\[\\]]", "")); } } public <T extends FragmentExecutionContext> void register(FragmentedCommandHandler<T> commandHandler, String permission, long timeout, FragmentedCommandContextSupplier<T> supplier, String... subCommandPrefix) throws HandlerCompilationException { Class<?> contextType = supplier.get().getClass(); // A small hack to get the generic type of the handler. Map<SubCommand, Map<Integer, CommandMethodHandle>> commandHandles = new HashMap<>(); for (Method method : commandHandler.getClass().getDeclaredMethods()) { FragmentedCommandHandle handlerAnnotation = method.getAnnotation(FragmentedCommandHandle.class); // Move on, this method isn't annotated if (handlerAnnotation == null) continue; String[] command = buildCommand(subCommandPrefix, handlerAnnotation.command(), method.getName()); CommandMethodHandle handle = buildFragmentHandle(method, commandHandler, contextType, command, handlerAnnotation.permission().isEmpty() ? permission : handlerAnnotation.permission(), ChatUtils.splitAndColorLines(handlerAnnotation.description())); SubCommand trigger = this.getSubCommand(command); Map<Integer, CommandMethodHandle> variants = commandHandles.computeIfAbsent(trigger, t -> new HashMap<>()); if (variants.containsKey(handlerAnnotation.state())) lib.getHook().getLogger().log(Level.WARNING, "Overwriting handle for " + trigger.toString() + " with " + method.getName() + " because both fragments have the same sub command and state."); variants.put(handlerAnnotation.state(), handle); lib.getHook().getLogger().log(Level.INFO, "Registering fragment " + method.getName() + " in " + commandHandler.getClass().getSimpleName() + " for " + trigger.toString() + " when in state " + handlerAnnotation.state()); } // All the commands need to share the context provider SimpleContextProvider<T> provider = new SimpleContextProvider<>(supplier::get); commandHandles.forEach((trigger, variants) -> { CommandExecutor executor = new ContextSensitiveCommand<>(trigger, variants, provider); this.executors.put(trigger, executor); lib.getHook().getLogger().log(Level.INFO, "Successfully registered variants for " + trigger.toString()); }); } private CommandMethodHandle buildFragmentHandle(Method method, Object commandHandler, Class<?> contextType, String[] command, String permission, List<String> desc) throws HandlerCompilationException { MethodDescriptor methodDesc = MethodDescriptor.fromMethod(method); CommandParameters cmdParams = this.compileParams(methodDesc, CTX_SENSITIVE_IMPLICIT_PARAMS_IDX); Parameter ctxParam = checkImplicitParam(methodDesc, "context", CTX_SENSITIVE_CONTEXT_PARAM_IDX, contextType); Parameter senderParam = checkImplicitParam(methodDesc, "sender", CTX_SENSITIVE_SENDER_PARAM_IDX, Player.class); SubCommand cmd = this.addSubCommand(command, permission); if (cmd == null) throw new HandlerCompilationException(methodDesc, "Invalid sub command %s.", Arrays.toString(command)); MethodHandle methodHandle; try { method.setAccessible(true); methodHandle = MethodHandles.lookup() .unreflect(method) .bindTo(commandHandler); } catch (IllegalAccessException e) { throw new HandlerCompilationException(methodDesc, "Error accessing method.", e); } return new CommandMethodHandle(senderParam.getType(), cmdParams, desc, methodHandle); } private CommandExecutor buildContextInsensitiveCommand(Method method, Object commandHandler, String[] command, String permission, List<String> desc) throws HandlerCompilationException { MethodDescriptor methodDesc = MethodDescriptor.fromMethod(method); CommandParameters cmdParams = this.compileParams(methodDesc, CTX_INSENSITIVE_IMPLICIT_PARAMS_IDX); Parameter senderParam = checkImplicitParam(methodDesc, "sender", CTX_INSENSITIVE_SENDER_PARAM_IDX, CommandSender.class); SubCommand cmd = this.addSubCommand(command, permission); if (cmd == null) throw new HandlerCompilationException(methodDesc, "Invalid sub command %s.", Arrays.toString(command)); MethodHandle methodHandle; try { method.setAccessible(true); methodHandle = MethodHandles.lookup() .unreflect(method) .bindTo(commandHandler); } catch (IllegalAccessException e) { throw new HandlerCompilationException(methodDesc, "Error accessing method.", e); } CommandMethodHandle handle = new CommandMethodHandle(senderParam.getType(), cmdParams, desc, methodHandle); return new ContextInsensitiveCommand(cmd, handle); } private String[] buildCommand(String[] prefix, String[] cmd, String fallback) { if (cmd == null || cmd.length == 0) cmd = new String[]{ fallback }; if (prefix.length == 0) return cmd; String[] concat = Arrays.copyOf(prefix, prefix.length + cmd.length); System.arraycopy(cmd, 0, concat, prefix.length, cmd.length); return concat; } private Parameter checkImplicitParam(MethodDescriptor method, String name, int idx, Class<?> assignableTo) throws HandlerCompilationException { Parameter param = method.getParameter(idx); if (param == null) throw new HandlerCompilationException(method, "Missing required implicit parameter %s in position %d.", name, idx); if (!assignableTo.isAssignableFrom(param.getType())) throw new HandlerCompilationException(method, "Invalid %s type %s. Must be assignable to %s.", name, param.getType().getSimpleName(), assignableTo.getName()); return param; } private CommandParameters compileParams(MethodDescriptor method, BitSet skip) throws HandlerCompilationException { List<Parameter> methodParams = method.getParameters(); List<CommandParameter<?>> cmdParams = new ArrayList<>(methodParams.size() - skip.cardinality()); int argIdx = -1; for (int i = 0; i < methodParams.size(); i++) { if (skip.get(i)) continue; argIdx++; Parameter p = methodParams.get(i); ArgDescription argDesc = p.getAnnotation(ArgDescription.class); CommandParameterKind kind = p.isVarArgs() ? CommandParameterKind.VAR_ARGS : argDesc != null && argDesc.optional() ? CommandParameterKind.OPTIONAL : CommandParameterKind.REQUIRED; ArgumentFormatter<?> formatter = p.isVarArgs() ? FormatterMapping.lookpArray(p.getType()) : FormatterMapping.lookup(p.getType()); String name = argDesc != null && !argDesc.name().isEmpty() ? argDesc.name() : p.isNamePresent() ? p.getName() : String.format("arg%d", argIdx); List<String> desc = argDesc != null && argDesc.description().length != 0 ? Arrays.asList(argDesc.description()) : null; if (formatter == null) throw new HandlerCompilationException(method, "Unknown argument type %s for parameter %s.", p.getType().getSimpleName(), name); CommandParameter<?> param = new CommandParameter<>(kind, formatter, p.getType(), name, desc); cmdParams.add(param); } try { return CommandParameters.fromList(cmdParams); } catch (IllegalArgumentException e) { throw new HandlerCompilationException(method, e.getMessage()); } } protected SubCommand getSubCommand(String[] command) { if (command == null || command.length < 1) return null; SubCommand cmd = this.getBaseCommand(command[0]); if (cmd == null) return null; for (int i = 1; i < command.length; i++) { cmd = cmd.getSubCommand(command[i]); if (cmd == null) return null; } return cmd; } private SubCommand getBaseCommand(String baseCommand) { for (String baseAlias : baseCommand.split("\\|")) { if (this.baseCommands.containsKey(baseAlias.toLowerCase())) { return this.baseCommands.get(baseAlias.toLowerCase()); } } return null; } protected SubCommand addSubCommand(String[] command, String permission) { if (command == null || command.length < 1) return null; SubCommand superCmd = addBaseCommand(command[0], permission); for (int i = 1; i < command.length; i++) { String[] subCommandAliases = command[i].split("\\|"); SubCommand subCmd = null; for (String s : subCommandAliases) { subCmd = superCmd.getSubCommand(s); if (subCmd != null) break; //We found it } if (subCmd == null) { //We could find an existing one, so many a new one if (subCommandAliases.length > 1) { subCmd = new SubCommand(subCommandAliases[0], Arrays.copyOfRange(subCommandAliases, 1, subCommandAliases.length), permission, superCmd); } else { subCmd = new SubCommand(subCommandAliases[0], new String[0], permission, superCmd); } } subCmd.addPermission(permission); superCmd.addSubCommand(subCmd); superCmd = subCmd; } return superCmd; } private SubCommand addBaseCommand(String baseCommand, String permission) { String[] baseAliases = baseCommand.split("\\|"); SubCommand base = getBaseCommand(baseAliases[0]); if (base != null) { base.addPermission(permission); for (int i = 1; i < baseAliases.length; i++) if (!base.getAliases().contains(baseAliases[i])) base.getAliases().add(baseAliases[i]); return base; } if (baseAliases.length > 1) { base = new SubCommand(baseAliases[0], Arrays.copyOfRange(baseAliases, 1, baseAliases.length), permission, null); } else { base = new SubCommand(baseAliases[0], new String[0], permission, null); } for (String alias : baseAliases) this.baseCommands.put(alias.toLowerCase(), base); this.bukkitCommandMap.register(base.getName(), this.lib.getHook().getName().toLowerCase(), new BukkitInterceptorCommand(this.lib, base.getName(), "/" + base.getName(), "/" + base.getName(), base.getAliases())); return base; } /** * Usage designed for tab complete. * * @param enteredCommand the partial command entered * * @return a List containing the possible sub commands that may follow, will never return null */ public List<String> getPossibleSubCommands(String[] enteredCommand) { // TODO not case insensitive SubCommand sub = this.getSubCommand(enteredCommand); if (sub == null) { //Try to partially fix the last arg sub = this.getSubCommand(Arrays.copyOfRange(enteredCommand, 0, enteredCommand.length - 1)); if (sub == null) { //Nope they are lost return Collections.emptyList(); } String lastEntered = enteredCommand[enteredCommand.length - 1]; return sub.getSubCommands().stream() .filter(it -> it.startsWith(lastEntered)) .collect(Collectors.toList()); } else { if (sub.canBeInvokedBy(enteredCommand[enteredCommand.length - 1])) { //We have a complete command return Collections.emptyList(); } return sub.getSubCommands(); } } /** * Handle the given command. * * @param sender the {@link CommandSender} that sent the command * @param command the command split into parts. The command followed by each argument * * @return true iff the base command is registered with this registry and an attempt to execute was preformed * * @throws CommandException if an error occurs while handling the command. */ protected boolean handleCommand(CommandSender sender, String[] command) throws CommandException { if (command == null || command.length < 1) throw new IllegalArgumentException("command was empty"); SubCommand cmd = this.getBaseCommand(command[0]); if (cmd == null) return false; SubCommand next; int i; for (i = 1; i < command.length; i++) { next = cmd.getSubCommand(command[i]); if (next == null) break; // We went as far as we could go else cmd = next; } if (!cmd.canBeExecutedBy(sender)) { sender.sendMessage(ChatColor.RED + "You do not have permission to execute " + cmd.toString() + "."); return true; } // Invoke the command CommandExecutor executor = this.executors.get(cmd); if (executor == null) return false; if (!executor.canExecute(sender)) { sender.sendMessage(ChatColor.RED + "Cannot execute " + cmd.toString() + " in your current state."); return true; } // i is index of first arg try { List<String> args = i < command.length ? Arrays.asList(command).subList(i, command.length) : Collections.emptyList(); executor.execute(sender, args); } catch (Exception e) { throw new CommandException(e); } return true; } public void displayHelp(CommandSender sender, String[] partialCmdRaw) { Stream<SubCommand> cmds = this.executors.keySet().stream(); if (partialCmdRaw.length > 0) { SubCommand partialCmd = this.getSubCommand(partialCmdRaw); if (partialCmd == null) { sender.sendMessage(ChatColor.YELLOW + "No commands match the query " + Arrays.toString(partialCmdRaw) + "."); return; } cmds = cmds.filter(cmd -> cmd.startsWith(partialCmd)); } List<CommandExecutor> matching = cmds .sorted() .map(this.executors::get) .filter(Objects::nonNull) .collect(Collectors.toList()); if (matching.isEmpty()) sender.sendMessage(ChatColor.RED + "No commands you are allowed to execute match the query."); else matching.forEach(executor -> executor.sendDescription(sender)); } }
true
cdf549913f52ccfafda38f2a0282538ba6f75206
Java
Jockay/Coster
/app/src/main/java/com/jockay/apmt/controller/util/MyUtil.java
UTF-8
308
2.578125
3
[]
no_license
package com.jockay.apmt.controller.util; public class MyUtil { public static int getIndexOfElement(String[] items, String element) { for(int i = 0; i < items.length; i++) { if(items[i].equals(element)) { return i; } } return -1; } }
true
37fab61ba3dab60107500325c14f81bcf992f403
Java
sikorsson/UWr
/Kurs jezyka programowania Java/lab4/obliczenia/arg_2_operacje/WiekszeRowne.java
UTF-8
483
3
3
[]
no_license
package obliczenia.arg_2_operacje; import obliczenia.Wyrazenie; public class WiekszeRowne extends Arg_2 { public WiekszeRowne(Wyrazenie l, Wyrazenie r) { a = l; b = r; } @Override public int oblicz() throws Exception { if(a.oblicz() >= b.oblicz()) return 1; else return 0; } @Override public String toString() { return "(" + a.toString() + " >= " + b.toString() + ")"; } }
true
825e12aa34653e64d3ec5d4dc53ce95c47dac8a7
Java
joselume/portfolio
/src/main/java/com/demo/portfolio/dto/PortfolioDTO.java
UTF-8
708
2.1875
2
[]
no_license
package com.demo.portfolio.dto; import com.demo.portfolio.model.Portfolio; import org.springframework.social.twitter.api.Tweet; import java.util.List; public class PortfolioDTO { private Portfolio portfolio; private List<Tweet> tweets; public PortfolioDTO(Portfolio portfolio, List<Tweet> tweets) { this.portfolio = portfolio; this.tweets = tweets; } public Portfolio getPortfolio() { return portfolio; } public void setPortfolio(Portfolio portfolio) { this.portfolio = portfolio; } public List<Tweet> getTweets() { return tweets; } public void setTweets(List<Tweet> tweets) { this.tweets = tweets; } }
true
bc54f63cf3515dc013eea87a1b64adc09ce94372
Java
FranciscoRayo/proyecto-fdc
/src/main/java/com/example/demo/dao/ClientDao.java
UTF-8
435
1.546875
2
[]
no_license
package com.example.demo.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.demo.model.Client; /** * Nombre Interfaz: ClientDao.java Descripcion: Clase para lanzar consultas a la * BBDD Fecha: 13/05/2021 Version: 1.0 Autor: Pedro Barrantes * **/ @Repository public interface ClientDao extends JpaRepository<Client, Integer> { }
true
42ee8d03d34725899a421c58d8e1bd3f2c846be9
Java
ZhipingLi/rt-source
/org/omg/DynamicAny/_DynSequenceStub.java
UTF-8
21,823
1.859375
2
[]
no_license
package org.omg.DynamicAny; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Properties; import org.omg.CORBA.Any; import org.omg.CORBA.ORB; import org.omg.CORBA.Object; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.Delegate; import org.omg.CORBA.portable.ObjectImpl; import org.omg.CORBA.portable.ServantObject; import org.omg.DynamicAny.DynAnyPackage.InvalidValue; import org.omg.DynamicAny.DynAnyPackage.TypeMismatch; public class _DynSequenceStub extends ObjectImpl implements DynSequence { public static final Class _opsClass = DynSequenceOperations.class; private static String[] __ids = { "IDL:omg.org/DynamicAny/DynSequence:1.0", "IDL:omg.org/DynamicAny/DynAny:1.0" }; public int get_length() { servantObject = _servant_preinvoke("get_length", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_length(); } finally { _servant_postinvoke(servantObject); } } public void set_length(int paramInt) throws InvalidValue { servantObject = _servant_preinvoke("set_length", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.set_length(paramInt); } finally { _servant_postinvoke(servantObject); } } public Any[] get_elements() { servantObject = _servant_preinvoke("get_elements", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_elements(); } finally { _servant_postinvoke(servantObject); } } public void set_elements(Any[] paramArrayOfAny) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("set_elements", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.set_elements(paramArrayOfAny); } finally { _servant_postinvoke(servantObject); } } public DynAny[] get_elements_as_dyn_any() { servantObject = _servant_preinvoke("get_elements_as_dyn_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_elements_as_dyn_any(); } finally { _servant_postinvoke(servantObject); } } public void set_elements_as_dyn_any(DynAny[] paramArrayOfDynAny) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("set_elements_as_dyn_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.set_elements_as_dyn_any(paramArrayOfDynAny); } finally { _servant_postinvoke(servantObject); } } public TypeCode type() { servantObject = _servant_preinvoke("type", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.type(); } finally { _servant_postinvoke(servantObject); } } public void assign(DynAny paramDynAny) throws TypeMismatch { servantObject = _servant_preinvoke("assign", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.assign(paramDynAny); } finally { _servant_postinvoke(servantObject); } } public void from_any(Any paramAny) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("from_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.from_any(paramAny); } finally { _servant_postinvoke(servantObject); } } public Any to_any() { servantObject = _servant_preinvoke("to_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.to_any(); } finally { _servant_postinvoke(servantObject); } } public boolean equal(DynAny paramDynAny) { servantObject = _servant_preinvoke("equal", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.equal(paramDynAny); } finally { _servant_postinvoke(servantObject); } } public void destroy() { servantObject = _servant_preinvoke("destroy", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.destroy(); } finally { _servant_postinvoke(servantObject); } } public DynAny copy() { servantObject = _servant_preinvoke("copy", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.copy(); } finally { _servant_postinvoke(servantObject); } } public void insert_boolean(boolean paramBoolean) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_boolean", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_boolean(paramBoolean); } finally { _servant_postinvoke(servantObject); } } public void insert_octet(byte paramByte) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_octet", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_octet(paramByte); } finally { _servant_postinvoke(servantObject); } } public void insert_char(char paramChar) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_char", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_char(paramChar); } finally { _servant_postinvoke(servantObject); } } public void insert_short(short paramShort) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_short", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_short(paramShort); } finally { _servant_postinvoke(servantObject); } } public void insert_ushort(short paramShort) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_ushort", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_ushort(paramShort); } finally { _servant_postinvoke(servantObject); } } public void insert_long(int paramInt) throws InvalidValue { servantObject = _servant_preinvoke("insert_long", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_long(paramInt); } finally { _servant_postinvoke(servantObject); } } public void insert_ulong(int paramInt) throws InvalidValue { servantObject = _servant_preinvoke("insert_ulong", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_ulong(paramInt); } finally { _servant_postinvoke(servantObject); } } public void insert_float(float paramFloat) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_float", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_float(paramFloat); } finally { _servant_postinvoke(servantObject); } } public void insert_double(double paramDouble) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_double", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_double(paramDouble); } finally { _servant_postinvoke(servantObject); } } public void insert_string(String paramString) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_string", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_string(paramString); } finally { _servant_postinvoke(servantObject); } } public void insert_reference(Object paramObject) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_reference", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_reference(paramObject); } finally { _servant_postinvoke(servantObject); } } public void insert_typecode(TypeCode paramTypeCode) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_typecode", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_typecode(paramTypeCode); } finally { _servant_postinvoke(servantObject); } } public void insert_longlong(long paramLong) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_longlong", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_longlong(paramLong); } finally { _servant_postinvoke(servantObject); } } public void insert_ulonglong(long paramLong) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_ulonglong", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_ulonglong(paramLong); } finally { _servant_postinvoke(servantObject); } } public void insert_wchar(char paramChar) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_wchar", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_wchar(paramChar); } finally { _servant_postinvoke(servantObject); } } public void insert_wstring(String paramString) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_wstring", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_wstring(paramString); } finally { _servant_postinvoke(servantObject); } } public void insert_any(Any paramAny) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_any(paramAny); } finally { _servant_postinvoke(servantObject); } } public void insert_dyn_any(DynAny paramDynAny) throws TypeMismatch { servantObject = _servant_preinvoke("insert_dyn_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_dyn_any(paramDynAny); } finally { _servant_postinvoke(servantObject); } } public void insert_val(Serializable paramSerializable) throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("insert_val", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.insert_val(paramSerializable); } finally { _servant_postinvoke(servantObject); } } public boolean get_boolean() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_boolean", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_boolean(); } finally { _servant_postinvoke(servantObject); } } public byte get_octet() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_octet", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_octet(); } finally { _servant_postinvoke(servantObject); } } public char get_char() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_char", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_char(); } finally { _servant_postinvoke(servantObject); } } public short get_short() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_short", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_short(); } finally { _servant_postinvoke(servantObject); } } public short get_ushort() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_ushort", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_ushort(); } finally { _servant_postinvoke(servantObject); } } public int get_long() { servantObject = _servant_preinvoke("get_long", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_long(); } finally { _servant_postinvoke(servantObject); } } public int get_ulong() { servantObject = _servant_preinvoke("get_ulong", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_ulong(); } finally { _servant_postinvoke(servantObject); } } public float get_float() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_float", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_float(); } finally { _servant_postinvoke(servantObject); } } public double get_double() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_double", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_double(); } finally { _servant_postinvoke(servantObject); } } public String get_string() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_string", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_string(); } finally { _servant_postinvoke(servantObject); } } public Object get_reference() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_reference", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_reference(); } finally { _servant_postinvoke(servantObject); } } public TypeCode get_typecode() { servantObject = _servant_preinvoke("get_typecode", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_typecode(); } finally { _servant_postinvoke(servantObject); } } public long get_longlong() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_longlong", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_longlong(); } finally { _servant_postinvoke(servantObject); } } public long get_ulonglong() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_ulonglong", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_ulonglong(); } finally { _servant_postinvoke(servantObject); } } public char get_wchar() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_wchar", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_wchar(); } finally { _servant_postinvoke(servantObject); } } public String get_wstring() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_wstring", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_wstring(); } finally { _servant_postinvoke(servantObject); } } public Any get_any() { servantObject = _servant_preinvoke("get_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_any(); } finally { _servant_postinvoke(servantObject); } } public DynAny get_dyn_any() { servantObject = _servant_preinvoke("get_dyn_any", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_dyn_any(); } finally { _servant_postinvoke(servantObject); } } public Serializable get_val() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("get_val", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.get_val(); } finally { _servant_postinvoke(servantObject); } } public boolean seek(int paramInt) { servantObject = _servant_preinvoke("seek", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.seek(paramInt); } finally { _servant_postinvoke(servantObject); } } public void rewind() { servantObject = _servant_preinvoke("rewind", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { dynSequenceOperations.rewind(); } finally { _servant_postinvoke(servantObject); } } public boolean next() throws TypeMismatch, InvalidValue { servantObject = _servant_preinvoke("next", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.next(); } finally { _servant_postinvoke(servantObject); } } public int component_count() { servantObject = _servant_preinvoke("component_count", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.component_count(); } finally { _servant_postinvoke(servantObject); } } public DynAny current_component() { servantObject = _servant_preinvoke("current_component", _opsClass); DynSequenceOperations dynSequenceOperations = (DynSequenceOperations)servantObject.servant; try { return dynSequenceOperations.current_component(); } finally { _servant_postinvoke(servantObject); } } public String[] _ids() { return (String[])__ids.clone(); } private void readObject(ObjectInputStream paramObjectInputStream) throws IOException { String str = paramObjectInputStream.readUTF(); String[] arrayOfString = null; Properties properties = null; oRB = ORB.init(arrayOfString, properties); try { Object object = oRB.string_to_object(str); Delegate delegate = ((ObjectImpl)object)._get_delegate(); _set_delegate(delegate); } finally { oRB.destroy(); } } private void writeObject(ObjectOutputStream paramObjectOutputStream) throws IOException { String[] arrayOfString = null; Properties properties = null; oRB = ORB.init(arrayOfString, properties); try { String str = oRB.object_to_string(this); paramObjectOutputStream.writeUTF(str); } finally { oRB.destroy(); } } } /* Location: D:\software\jd-gui\jd-gui-windows-1.6.3\rt.jar!\org\omg\DynamicAny\_DynSequenceStub.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.0.7 */
true
dedd12bc6b1084b9eeb058f848740c964bc6353c
Java
zyqyyy/New-World
/src/main/java/com/lanou/entity/Exteproductc.java
UTF-8
14,318
1.703125
2
[]
no_license
package com.lanou.entity; import java.io.Serializable; import java.math.BigDecimal; public class Exteproductc implements Serializable{ /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.EXT_EPRODUCT_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String EXT_EPRODUCT_ID; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.EXPORT_PRODUCT_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String EXPORT_PRODUCT_ID; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.FACTORY_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String FACTORY_ID; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.FACTORY_NAME * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String FACTORY_NAME; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.CTYPE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private Short CTYPE; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.PRODUCT_NO * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String PRODUCT_NO; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.PRODUCT_IMAGE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String PRODUCT_IMAGE; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.PRODUCT_DESC * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String PRODUCT_DESC; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.CNUMBER * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private Short CNUMBER; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.PACKING_UNIT * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String PACKING_UNIT; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.PRICE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private BigDecimal PRICE; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.AMOUNT * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private BigDecimal AMOUNT; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.PRODUCT_REQUEST * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private String PRODUCT_REQUEST; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column EXT_EPRODUCT_C.ORDER_NO * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ private Short ORDER_NO; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.EXT_EPRODUCT_ID * * @return the value of EXT_EPRODUCT_C.EXT_EPRODUCT_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getEXT_EPRODUCT_ID() { return EXT_EPRODUCT_ID; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.EXT_EPRODUCT_ID * * @param EXT_EPRODUCT_ID the value for EXT_EPRODUCT_C.EXT_EPRODUCT_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setEXT_EPRODUCT_ID(String EXT_EPRODUCT_ID) { this.EXT_EPRODUCT_ID = EXT_EPRODUCT_ID; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.EXPORT_PRODUCT_ID * * @return the value of EXT_EPRODUCT_C.EXPORT_PRODUCT_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getEXPORT_PRODUCT_ID() { return EXPORT_PRODUCT_ID; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.EXPORT_PRODUCT_ID * * @param EXPORT_PRODUCT_ID the value for EXT_EPRODUCT_C.EXPORT_PRODUCT_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setEXPORT_PRODUCT_ID(String EXPORT_PRODUCT_ID) { this.EXPORT_PRODUCT_ID = EXPORT_PRODUCT_ID; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.FACTORY_ID * * @return the value of EXT_EPRODUCT_C.FACTORY_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getFACTORY_ID() { return FACTORY_ID; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.FACTORY_ID * * @param FACTORY_ID the value for EXT_EPRODUCT_C.FACTORY_ID * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setFACTORY_ID(String FACTORY_ID) { this.FACTORY_ID = FACTORY_ID; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.FACTORY_NAME * * @return the value of EXT_EPRODUCT_C.FACTORY_NAME * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getFACTORY_NAME() { return FACTORY_NAME; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.FACTORY_NAME * * @param FACTORY_NAME the value for EXT_EPRODUCT_C.FACTORY_NAME * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setFACTORY_NAME(String FACTORY_NAME) { this.FACTORY_NAME = FACTORY_NAME; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.CTYPE * * @return the value of EXT_EPRODUCT_C.CTYPE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public Short getCTYPE() { return CTYPE; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.CTYPE * * @param CTYPE the value for EXT_EPRODUCT_C.CTYPE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setCTYPE(Short CTYPE) { this.CTYPE = CTYPE; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.PRODUCT_NO * * @return the value of EXT_EPRODUCT_C.PRODUCT_NO * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getPRODUCT_NO() { return PRODUCT_NO; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.PRODUCT_NO * * @param PRODUCT_NO the value for EXT_EPRODUCT_C.PRODUCT_NO * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setPRODUCT_NO(String PRODUCT_NO) { this.PRODUCT_NO = PRODUCT_NO; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.PRODUCT_IMAGE * * @return the value of EXT_EPRODUCT_C.PRODUCT_IMAGE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getPRODUCT_IMAGE() { return PRODUCT_IMAGE; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.PRODUCT_IMAGE * * @param PRODUCT_IMAGE the value for EXT_EPRODUCT_C.PRODUCT_IMAGE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setPRODUCT_IMAGE(String PRODUCT_IMAGE) { this.PRODUCT_IMAGE = PRODUCT_IMAGE; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.PRODUCT_DESC * * @return the value of EXT_EPRODUCT_C.PRODUCT_DESC * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getPRODUCT_DESC() { return PRODUCT_DESC; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.PRODUCT_DESC * * @param PRODUCT_DESC the value for EXT_EPRODUCT_C.PRODUCT_DESC * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setPRODUCT_DESC(String PRODUCT_DESC) { this.PRODUCT_DESC = PRODUCT_DESC; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.CNUMBER * * @return the value of EXT_EPRODUCT_C.CNUMBER * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public Short getCNUMBER() { return CNUMBER; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.CNUMBER * * @param CNUMBER the value for EXT_EPRODUCT_C.CNUMBER * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setCNUMBER(Short CNUMBER) { this.CNUMBER = CNUMBER; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.PACKING_UNIT * * @return the value of EXT_EPRODUCT_C.PACKING_UNIT * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getPACKING_UNIT() { return PACKING_UNIT; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.PACKING_UNIT * * @param PACKING_UNIT the value for EXT_EPRODUCT_C.PACKING_UNIT * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setPACKING_UNIT(String PACKING_UNIT) { this.PACKING_UNIT = PACKING_UNIT; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.PRICE * * @return the value of EXT_EPRODUCT_C.PRICE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public BigDecimal getPRICE() { return PRICE; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.PRICE * * @param PRICE the value for EXT_EPRODUCT_C.PRICE * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setPRICE(BigDecimal PRICE) { this.PRICE = PRICE; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.AMOUNT * * @return the value of EXT_EPRODUCT_C.AMOUNT * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public BigDecimal getAMOUNT() { return AMOUNT; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.AMOUNT * * @param AMOUNT the value for EXT_EPRODUCT_C.AMOUNT * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setAMOUNT(BigDecimal AMOUNT) { this.AMOUNT = AMOUNT; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.PRODUCT_REQUEST * * @return the value of EXT_EPRODUCT_C.PRODUCT_REQUEST * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public String getPRODUCT_REQUEST() { return PRODUCT_REQUEST; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.PRODUCT_REQUEST * * @param PRODUCT_REQUEST the value for EXT_EPRODUCT_C.PRODUCT_REQUEST * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setPRODUCT_REQUEST(String PRODUCT_REQUEST) { this.PRODUCT_REQUEST = PRODUCT_REQUEST; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column EXT_EPRODUCT_C.ORDER_NO * * @return the value of EXT_EPRODUCT_C.ORDER_NO * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public Short getORDER_NO() { return ORDER_NO; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column EXT_EPRODUCT_C.ORDER_NO * * @param ORDER_NO the value for EXT_EPRODUCT_C.ORDER_NO * * @mbg.generated Fri Jan 05 15:47:01 CST 2018 */ public void setORDER_NO(Short ORDER_NO) { this.ORDER_NO = ORDER_NO; } }
true
121ad46f0a5917e2e5a2c75199118272b910bf0e
Java
Laakeri/ohtu-viikko3
/QueryLanguage/src/main/java/statistics/matcher/QueryBuilder.java
UTF-8
1,153
2.609375
3
[]
no_license
package statistics.matcher; // jostain syystä materiaalissa ei tehdä aina uutta querybuilder oliota mutta // mun mielestä se on pakollista että saadaan toiminnallisuus jossa käyttäjä ei // voi tehdä outoja virheitä public class QueryBuilder { private final Matcher matcher; public QueryBuilder() { this.matcher = new EmptyMatcher(); } private QueryBuilder(Matcher matcher) { this.matcher = matcher; } public QueryBuilder playsIn(String team) { return new QueryBuilder(new And(this.matcher, new PlaysIn(team))); } public QueryBuilder hasAtLeast(int n, String category) { return new QueryBuilder(new And(this.matcher, new HasAtLeast(n, category))); } public QueryBuilder hasFewerThan(int n, String category) { return new QueryBuilder(new And(this.matcher, new HasFewerThan(n, category))); } // tässä varmaan kannattais olla querybuilderit parametrinä public QueryBuilder oneOf(Matcher... matchers) { return new QueryBuilder(new Or(matchers)); } public Matcher build() { return matcher; } }
true