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
1cad00d8d53adfb7e1f3520278ea107f26b7a3a9
Java
pckv/kompisapp
/app/src/main/java/me/pckv/kompisapp/data/model/Listing.java
UTF-8
560
2.203125
2
[]
no_license
package me.pckv.kompisapp.data.model; import androidx.annotation.Nullable; import lombok.Data; @Data public class Listing { private long id; private String title; private boolean driver; private boolean active; private Location location; private User owner; @Nullable private Assignee assignee; private double distance; public boolean hasAssignee() { return assignee != null; } public boolean matchesQuery(String query) { return title.toLowerCase().contains(query.toLowerCase()); } }
true
a0c59d613d2ac8fc174067066c4d4436841f614f
Java
limaluizpaulo/java-
/TesteFile/src/teste/Frame.java
UTF-8
1,496
2.9375
3
[]
no_license
package teste; import java.awt.Color; import java.awt.FlowLayout; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Frame extends JFrame { private static final long serialVersionUID = 1L; private JPanel painel = new JPanel(); private JButton jButtonArquivo = new JButton("Escolher Arquivo"); private JTextField jTextFieldTexto = new JTextField("Caminho do arquivo", 35); public Frame() { initActionEvents(); this.setTitle("Exemplo Arquivo"); this.setSize(500, 150); painel.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 20)); painel.setBackground(new Color(255, 255, 255)); painel.add(jTextFieldTexto); painel.add(jButtonArquivo); this.getContentPane().add(painel); this.setLocationRelativeTo(null); this.setVisible(true); } private void initActionEvents() { java.awt.event.ActionListener actionListener = new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JFileChooser file = new JFileChooser(); file.setFileSelectionMode(JFileChooser.FILES_ONLY); int i = file.showSaveDialog(null); if (i == 1) { jTextFieldTexto.setText(""); } else { File arquivo = file.getSelectedFile(); jTextFieldTexto.setText(arquivo.getPath()); } } }; jButtonArquivo.addActionListener(actionListener); } }
true
734d4c7d0ccc123159a5973db3c527bca4e4220a
Java
chlgpgus57/DHM
/src/main/java/com/f/dhm/location/LocationVO.java
UTF-8
1,776
2.046875
2
[]
no_license
package com.f.dhm.location; import java.util.Arrays; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import com.sun.xml.bind.v2.runtime.unmarshaller.XsiNilLoader.Array; import lombok.Data; @Data @Entity @Table(name = "location") public class LocationVO { @Id private int arCode; private String arImg; private String arName; private int arIndex; private int added; private int subway; private int taxi; private int mycar; private int airplane; private int bus; private int transfer; private int bak0; private int bak1; private int bak2; private int bak3; private int bak4; private int bak5; private int bak6; private int bak7; private int bak8; private int bak9; private int totalBak; @Transient private String maxBak; @Transient private String maxTransfer; public void inputBak(int day) throws Exception{ switch (day) { case 0: this.bak0+=1; break; case 1: this.bak1+=1; break; case 2: this.bak2+=1; break; case 3: this.bak3+=1; break; case 4: this.bak4+=1; break; case 5: this.bak5+=1; break; case 6: this.bak6+=1; break; case 7: this.bak7+=1; break; case 8: this.bak8+=1; break; default: this.bak9+=1; break; } this.totalBak+=1; } public void inputTransfer(String trans) { if (trans.equals("택시")) { this.taxi = taxi + 1; }else if (trans.equals("버스")) { this.bus+=1; }else if (trans.equals("기차")) { this.subway+=1; }else if (trans.equals("항공")) { this.airplane+=1; }else if (trans.equals("자차")) { this.mycar+=1; } if (trans != null && !trans.equals("선택")) { this.transfer+=1; } } }
true
9733a93df733d1663770b01a1dffff2646c389d4
Java
Matenwp/know
/knows-search/src/main/java/cn/tedu/knows/search/vo/QuestionVo.java
UTF-8
2,661
2.0625
2
[]
no_license
package cn.tedu.knows.search.vo; import cn.tedu.knows.commons.model.Tag; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.elasticsearch.annotations.DateFormat; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.io.Serializable; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; /** * <p> * * </p> * * @author tedu.cn * @since 2021-06-25 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @Document(indexName = "knows") public class QuestionVo implements Serializable { private static final long serialVersionUID = 1L; public static final Integer POSTED=0; //已提交\未回复 public static final Integer SOLVING=1; //未采纳\已回复 public static final Integer SOLVED=2; //已采纳\已解决 @Id private Integer id; /** * 问题的标题 */ @Field(type = FieldType.Text,analyzer = "ik_smart", searchAnalyzer = "ik_smart") private String title; /** * 提问内容 */ @Field(type = FieldType.Text,analyzer = "ik_smart", searchAnalyzer = "ik_smart") private String content; /** * 提问者用户名 */ @Field(type = FieldType.Keyword) private String userNickName; /** * 提问者id */ @Field(type = FieldType.Integer) private Integer userId; /** * 创建时间 */ @Field(type = FieldType.Date, format = DateFormat.basic_date_time) private LocalDateTime createtime; /** * 状态,0-》未回答,1-》待解决,2-》已解决 */ @Field(type = FieldType.Integer) private Integer status; /** * 浏览量 */ @Field(type = FieldType.Integer) private Integer pageViews; /** * 该问题是否公开,所有学生都可见,0-》否,1-》是 */ @Field(type = FieldType.Integer) private Integer publicStatus; @Field(type = FieldType.Date,format = DateFormat.basic_date) private LocalDate modifytime; @Field(type = FieldType.Integer) private Integer deleteStatus; @Field(type = FieldType.Keyword) private String tagNames; // 保存当前问题的所有标签 //@Transient表示当前属性在ES中没有对应的列 @Transient private List<Tag> tags; }
true
21156862480ef4e2b935a3e0bf350453fb024651
Java
Asel06/online_store
/store/src/main/java/com/store/Controller/RoleController.java
UTF-8
885
2.125
2
[]
no_license
package com.store.controller; import com.store.entity.Role; import com.store.repository.RoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(path = "/role") public class RoleController { @Autowired private RoleRepository roleRepository; @RequestMapping(value = "/allRole", method = RequestMethod.GET) public Iterable<Role> getAllRole() { return roleRepository.findAll(); } @RequestMapping(value = "/addRole", method = RequestMethod.POST) public Role addNewRole (@RequestBody Role role) { return roleRepository.save(role); } }
true
c73d5dc0cb3640b2153881136f62b3f895c062ee
Java
phwd/quest-tracker
/hollywood/com.oculus.browser-base/sources/defpackage/TO.java
UTF-8
461
1.585938
2
[]
no_license
package defpackage; import android.view.View; /* renamed from: TO reason: default package */ /* compiled from: chromium-OculusBrowser.apk-stable-281887347 */ public class TO implements TW { /* renamed from: a reason: collision with root package name */ public final /* synthetic */ XO f8955a; public TO(XO xo, SO so) { this.f8955a = xo; } @Override // defpackage.TW public View b() { return this.f8955a.r; } }
true
656784811fb245c4e1916924e2466bd7ce174fe8
Java
U-22/MezamashiNippon
/app/src/main/java/com/example/kimata/mezamashinippon/MNAsyncImageLoader.java
UTF-8
580
2.09375
2
[]
no_license
package com.example.kimata.mezamashinippon; import android.graphics.Bitmap; import android.support.v4.content.AsyncTaskLoader; import android.content.Context; /** * Created by umino on 16/10/17. */ public class MNAsyncImageLoader extends AsyncTaskLoader<Boolean>{ private MNHtml m_html; public MNAsyncImageLoader(Context context, MNHtml html) { super(context); m_html = html; } @Override public Boolean loadInBackground(){ return m_html.getPicture(); } @Override protected void onStartLoading() {forceLoad();} }
true
145f37fc6fcce034300c4ce5ad046c1a66695e27
Java
ws410/dataStructure
/src/ch07/SY_DebugCounTimes.java
UTF-8
979
3
3
[]
no_license
package ch07; public class SY_DebugCounTimes { static int maxSize = 10; public static void main(String[] args) throws Exception { int[] d = new int[maxSize]; //顺序表空间大小 for (int i = 0; i < maxSize; i++) { d[i] = (int) (Math.random() * 100); } SY_counTimes sc; sc=createList(d); runMethod(sc, 'b'); sc.displayTimes('b'); sc=createList(d); runMethod(sc, 'p'); sc.displayTimes('p'); } private static SY_counTimes createList(int[] d) throws Exception { SY_counTimes L = new SY_counTimes(maxSize); //建立顺序表 for (int i = 0; i < d.length; i++) { RecordNode r = new RecordNode(d[i]); L.insert(L.length(), r); } return L; } public static void runMethod(SY_counTimes sct,char methType){ switch (methType) { case 'b': sct.bubbleSort(); break; case 'p': sct.Partition(1, 5); break; } } }
true
cdf9188a8dcefda7845385cdd935fee363d614fc
Java
zoli90/SegregationModel
/src/segregationmodel/Tests.java
UTF-8
19,373
2.96875
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 segregationmodel; import java.util.ArrayList; import java.util.Random; import java.util.Arrays; /** * * @author zoli */ public class Tests { //create a counter for the number of performed test cases int testCaseCounter = 1; public static void main(String[] args) { //create an Agent and set some of its variables Agent testAgent = new Agent(new Cell (0,0, 'A'), 0.5f); //instantiate an Tests object and start running the tests Tests at = new Tests(); at.testChecker(testAgent); at.testGetters(testAgent); at.testDecision(testAgent); at.testUpdate(testAgent); //instantiate a simulation object and start running the tests SegregationModel sm = new SegregationModel(); at.testSetupSim(sm); } public void testChecker(Agent testAgent) { //create 3 different cells to be put in different ArrayLists Cell cell1 = new Cell(0,0,'A'); Cell cell2 = new Cell(0,1,'A'); Cell cell3 = new Cell(0,1,'A'); Cell cell4 = new Cell(0,0,'A'); Agent.checkCellCode testresult; //create and test an empty ArrayList ArrayList<Cell> empty = new ArrayList<Cell>(); testresult = testAgent.checkCells(empty); if (testresult == Agent.checkCellCode.ARRAYLIST_TOO_SHORT) { System.out.println("Agent checkCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent checkCells Test (#" + testCaseCounter + ", UID: 2) failed! Reported output: " + testresult); } testCaseCounter++; //create and test an ArrayList containing 2 identical cells ArrayList<Cell> duplicates = new ArrayList<Cell>(); duplicates.add(cell1); duplicates.add(cell2); duplicates.add(cell3); testAgent.checkCells(duplicates); testresult = testAgent.checkCells(duplicates); if (testresult == Agent.checkCellCode.DUPLICATE_CELLS_FOUND) { System.out.println("Agent checkCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent checkCells Test (#" + testCaseCounter + ", UID: 3) failed! Reported output: " + testresult); } testCaseCounter++; //create and test an ArrayList containing 2x2 identical cells ArrayList<Cell> duplicates2 = new ArrayList<Cell>(); duplicates2.add(cell1); duplicates2.add(cell2); duplicates2.add(cell3); duplicates2.add(cell4); testAgent.checkCells(duplicates2); testresult = testAgent.checkCells(duplicates2); if (testresult == Agent.checkCellCode.DUPLICATE_CELLS_FOUND) { System.out.println("Agent checkCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent checkCells Test (#" + testCaseCounter + ", UID: 4) failed! Reported output: " + testresult); } testCaseCounter++; //create and test a correct ArrayList ArrayList<Cell> correct = new ArrayList<Cell>(); correct.add(cell1); correct.add(cell2); testAgent.checkCells(correct); testresult = testAgent.checkCells(correct); if (testresult == Agent.checkCellCode.ARRAYLIST_OK) { System.out.println("Agent checkCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent checkCells Test (#" + testCaseCounter + ", UID: 5) failed! Reported output: " + testresult); } testCaseCounter++; } public void testGetters(Agent testAgent) { //create a 3x3 test coordinate system and assign the Agent's position char[][] testArray1 = {{'_','A','_'}, {'B','A','_'}, {'_','_','A'}}; testAgent.setCell(1, 1, 'A'); //test: find all 5 neighboring empty cells, 2 cell of the same color and 1 cell of different color testAgent.getCells(testArray1); if (testAgent.getNumberOfEmptyCells() == 5){ System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ", UID: 1) failed! Number of percieved empty cells: " + testAgent.getNumberOfEmptyCells()); } testCaseCounter++; if (testAgent.getNumberOfSameColorCells()== 2){ System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ", UID: 7) failed! Number of percieved same color cells: " + testAgent.getNumberOfSameColorCells()); } testCaseCounter++; if (testAgent.getNumberOfDifferentColorCells()== 1){ System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ", UID: 8) failed! Number of percieved different color cells: " + testAgent.getNumberOfDifferentColorCells()); } testCaseCounter++; //test: find all 3 neighboring empty cells, 1 cell of the same color and 1 cell of different color when the Agent is on the edge of the map. //here the array should be replaced but for the sake of simplicity, we'll use the same array but with a different position. testAgent.setCell(1, 0, 'A'); testAgent.getCells(testArray1); if (testAgent.getNumberOfEmptyCells() == 3){ System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ", UID: 6) failed! Number of percieved empty cells: " + testAgent.getNumberOfEmptyCells()); } testCaseCounter++; if (testAgent.getNumberOfSameColorCells()== 1){ System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ", UID: 9) failed! Number of percieved same color cells: " + testAgent.getNumberOfSameColorCells()); } testCaseCounter++; if (testAgent.getNumberOfDifferentColorCells()== 1){ System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ", UID: 10) failed! Number of percieved different color cells: " + testAgent.getNumberOfDifferentColorCells()); } testCaseCounter++; //create a 4x3 test coordinate system and assign the Agent's position char[][] testArray2 = {{'A','A','A'}, {'A','B','A'}, {'A','A','A'}, {'_','_','B'}}; testAgent.setCell(1, 1, 'B'); //test: find 0 neighboring empty cell, 0 cell of the same color and 8 cell of different color testAgent.getCells(testArray2); if (testAgent.getNumberOfEmptyCells() == 0){ System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ", UID: 11) failed! Number of percieved empty cells: " + testAgent.getNumberOfEmptyCells()); } testCaseCounter++; if (testAgent.getNumberOfSameColorCells()== 0){ System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ", UID: 12) failed! Number of percieved same color cells: " + testAgent.getNumberOfSameColorCells()); } testCaseCounter++; if (testAgent.getNumberOfDifferentColorCells()== 8){ System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ", UID: 13) failed! Number of percieved different color cells: " + testAgent.getNumberOfDifferentColorCells()); } testCaseCounter++; //test: find 1 neighboring empty cell, 0 cell of the same color and 2 cells of different color when the Agent is in the corner of the map. //here the array should be replaced but for the sake of simplicity, we'll use the same array but with a different position. testAgent.setCell(2, 3, 'A'); testAgent.getCells(testArray2); if (testAgent.getNumberOfEmptyCells() == 1){ System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfEmptyCells Test (#" + testCaseCounter + ", UID: 14) failed! Number of percieved empty cells: " + testAgent.getNumberOfEmptyCells()); } testCaseCounter++; if (testAgent.getNumberOfSameColorCells()== 0){ System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfSameColorCells Test (#" + testCaseCounter + ", UID: 15) failed! Number of percieved same color cells: " + testAgent.getNumberOfSameColorCells()); } testCaseCounter++; if (testAgent.getNumberOfDifferentColorCells()== 2){ System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNumberOfDifferentColorCells Test (#" + testCaseCounter + ", UID: 16) failed! Number of percieved different color cells: " + testAgent.getNumberOfDifferentColorCells()); } testCaseCounter++; } public void testDecision(Agent testAgent) { if (testAgent.getNextStep()== null){ System.out.println("Agent getNextStep Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent getNextStep Test (#" + testCaseCounter + ", UID: 17) failed! Next step data(x, y, color): " + testAgent.getNextStep().getX() + ", " + testAgent.getNextStep().getY() + ", " + testAgent.getNextStep().getColor()); } testCaseCounter++; char[][] testArray2 = {{'A','A','A'}, {'_','B','B'}, {'_','A','A'}, {'_','_','B'}}; testAgent.setCell(2, 0, 'A'); testAgent.getCells(testArray2); testAgent.setNextStep(); if (testAgent.getNextStep()== null){ System.out.println("Agent setNextStep Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent setNextStep Test (#" + testCaseCounter + ", UID: 18) failed! Next step data(x, y, color): " + testAgent.getNextStep().getX() + ", " + testAgent.getNextStep().getY() + ", " + testAgent.getNextStep().getColor()); } testCaseCounter++; testAgent.setCell(1, 0, 'A'); testAgent.setHomophility(0.01f); testAgent.getCells(testArray2); testAgent.setNextStep(); if (testAgent.getNextStep()== null){ System.out.println("Agent setNextStep Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent setNextStep Test (#" + testCaseCounter + ", UID: 19) failed! Next step data(x, y, color): " + testAgent.getNextStep().getX() + ", " + testAgent.getNextStep().getY() + ", " + testAgent.getNextStep().getColor()); } testCaseCounter++; testAgent.setCell(1, 2, 'A'); testAgent.setHomophility(1f); testAgent.getCells(testArray2); testAgent.setNextStep(); ArrayList<Cell> remainingCells = testAgent.getNeighborCells(); int arraySize = remainingCells.size(); //instantiate a second, separate RNG for the testing the decision "algorithm". During the decision test, both Random object draw the first int using the exact same seed Random testRNG = new Random(SegregationModel.seed); int randomOutput = testRNG.nextInt(arraySize); if (remainingCells.get(randomOutput).equals(testAgent.getNextStep())){ System.out.println("Agent setNextStep Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent setNextStep Test (#" + testCaseCounter + ", UID: 20) failed! Next step data(x, y, color): " + testAgent.getNextStep().getX() + ", " + testAgent.getNextStep().getY() + ", " + testAgent.getNextStep().getColor()); System.out.println("randomOutput = " + randomOutput); System.out.println("randomly chosen cell by second RNG (x, y, color): " + remainingCells.get(randomOutput).getX() + ", " + remainingCells.get(randomOutput).getY() + ", " + remainingCells.get(randomOutput).getColor()); } testCaseCounter++; } public void testUpdate(Agent testAgent) { testAgent.setCell(0, 0, 'A'); testAgent.setHomophility(1f); char[][] testArrayInput = {{'A','B','_'}, {'_','B','_'}, {'_','_','_'}, {'_','_','_'}}; char[][] testExpectedOutput = {{'_','B','_'}, {'A','B','_'}, {'_','_','_'}, {'_','_','_'}}; testAgent.getCells(testArrayInput); testAgent.setNextStep(); char[][] testArrayOutput = testAgent.setPosition(testArrayInput); if (Arrays.deepEquals(testExpectedOutput, testArrayOutput)){ System.out.println("Agent setPosition Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent setPosition Test (#" + testCaseCounter + ", UID: 21) failed! Actual output: " + Arrays.deepToString(testArrayOutput)); } testCaseCounter++; testAgent.setCell(0, 0, 'A'); testAgent.setHomophility(1f); char[][] testArrayInput2 = {{'A','B','_'}, {'A','B','_'}, {'_','_','_'}, {'_','_','_'}}; char[][] testExpectedOutput2 = {{'A','B','_'}, {'A','B','_'}, {'_','_','_'}, {'_','_','_'}}; testAgent.getCells(testArrayInput2); testAgent.setNextStep(); char[][] testArrayOutput2 = testAgent.setPosition(testArrayInput2); if (Arrays.deepEquals(testExpectedOutput2, testArrayOutput2)){ System.out.println("Agent setPosition Test (#" + testCaseCounter + ") passed."); } else { System.out.println("Agent setPosition Test (#" + testCaseCounter + ", UID: 21) failed! Actual output: " + Arrays.deepToString(testArrayOutput2)); } testCaseCounter++; } public void testSetupSim(SegregationModel sim) { SegregationModel.lastColor = 'A'; SegregationModel.mapHeigth = 2; SegregationModel.mapLength = 2; SegregationModel.mapPoints = 4; SegregationModel.map = new char[2][2]; SegregationModel.agentCount = new ArrayList<Integer>(); SegregationModel.agentCount.add(3); SegregationModel.homophilityList = new ArrayList<Float>(); SegregationModel.homophilityList.add(0.5f); sim.setupSimulation(); System.out.println("SegregationModel setupSimulation Test (#" + testCaseCounter + ", UID: 22). Generated output: " + Arrays.deepToString(SegregationModel.map)); SegregationModel.lastColor = 'B'; SegregationModel.mapHeigth = 3; SegregationModel.mapLength = 3; SegregationModel.mapPoints = 9; SegregationModel.map = new char[3][3]; SegregationModel.agentCount = new ArrayList<Integer>(); SegregationModel.agentCount.add(1); SegregationModel.agentCount.add(1); SegregationModel.homophilityList = new ArrayList<Float>(); SegregationModel.homophilityList.add(0.5f); SegregationModel.homophilityList.add(0.5f); sim.setupSimulation(); System.out.println("SegregationModel setupSimulation Test (#" + testCaseCounter + ", UID: 23). Generated output: " + Arrays.deepToString(SegregationModel.map)); SegregationModel.lastColor = 'D'; SegregationModel.mapHeigth = 4; SegregationModel.mapLength = 1; SegregationModel.mapPoints = 4; SegregationModel.map = new char[4][1]; SegregationModel.agentCount = new ArrayList<Integer>(); SegregationModel.agentCount.add(1); SegregationModel.agentCount.add(1); SegregationModel.agentCount.add(1); SegregationModel.agentCount.add(1); SegregationModel.homophilityList = new ArrayList<Float>(); SegregationModel.homophilityList.add(0.5f); SegregationModel.homophilityList.add(0.5f); SegregationModel.homophilityList.add(0.5f); SegregationModel.homophilityList.add(0.5f); sim.setupSimulation(); System.out.println("SegregationModel setupSimulation Test (#" + testCaseCounter + ", UID: 24). Generated output: " + Arrays.deepToString(SegregationModel.map)); SegregationModel.lastColor = 'A'; SegregationModel.mapHeigth = 1; SegregationModel.mapLength = 1; SegregationModel.mapPoints = 1; SegregationModel.map = new char[1][1]; SegregationModel.agentCount = new ArrayList<Integer>(); SegregationModel.homophilityList = new ArrayList<Float>(); SegregationModel.homophilityList.add(0.5f); sim.setupSimulation(); System.out.println("SegregationModel setupSimulation Test (#" + testCaseCounter + ", UID: 25). Generated output: " + Arrays.deepToString(SegregationModel.map)); } }
true
1f982b94e6c07e00622d02614301c44c1324a290
Java
MeiYien96/Dabao_App_A161209
/app/src/main/java/com/cmy/dabao_app_a161209/User.java
UTF-8
1,351
2.25
2
[]
no_license
package com.cmy.dabao_app_a161209; public class User { String username, matric, email, phone,identity, profilePic; public User(){ } public User(String username, String matric, String email, String phone, String identity, String profilePic) { this.username = username; this.matric = matric; this.email = email; this.phone = phone; this.identity = identity; this.profilePic = profilePic; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMatric() { return matric; } public void setMatric(String matric) { this.matric = matric; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public String getProfilePic() { return profilePic; } public void setProfilePic(String profilePic) { this.profilePic = profilePic; } }
true
109b15aca1d036482f340afd2a7f569e15a732e2
Java
BuiNgocHai/Java_Hit
/Buoi_2/bai_5.java
UTF-8
651
2.890625
3
[]
no_license
import java.util.Scanner; public class bai_5{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n; System.out.print("Moi nhap: "); n = sc.nextInt(); boolean[] check = new boolean[n+1]; for(int i=2;i<n;i++){ check[i]=true; } for(int i=2;i<n;i++){ if(check[i] == true){ for(int j=2*i;j<=n;j+=i){ check[j]=false; } } } for(int i=2;i<n;i++){ if(check[i]==true){ System.out.printf("%d ",i); } } } }
true
5f5b691367674ce2471f92890b3c550dc08ffb32
Java
bridenbrad/inmemdb
/tirion-db-sql-ast/src/main/java/com/tirion/db/sql/parser/transformer/SelectTransformer.java
UTF-8
10,396
2.0625
2
[]
no_license
/** * Copyright © 2013/2014, Veljko Zivkovic * All rights reserved. * * No portion of this file may be reproduced in any form, or by any means, without the prior written * consent of the author. */ package com.tirion.db.sql.parser.transformer; import org.antlr.runtime.tree.CommonTree; import com.tirion.common.Util; import com.tirion.db.common.JoinType; import com.tirion.db.sql.SqlGrammarParser; import com.tirion.db.sql.ast.Node; import com.tirion.db.sql.ast.common.EntityRef; import com.tirion.db.sql.ast.common.FieldRef; import com.tirion.db.sql.ast.common.FunctionCall; import com.tirion.db.sql.ast.common.Star; import com.tirion.db.sql.ast.common.constant.Constant; import com.tirion.db.sql.ast.expression.bool.BoolExpression; import com.tirion.db.sql.ast.select.FromClause; import com.tirion.db.sql.ast.select.GroupByClause; import com.tirion.db.sql.ast.select.HavingClause; import com.tirion.db.sql.ast.select.Join; import com.tirion.db.sql.ast.select.JoinClause; import com.tirion.db.sql.ast.select.LimitClause; import com.tirion.db.sql.ast.select.OrderByClause; import com.tirion.db.sql.ast.select.OrderKind; import com.tirion.db.sql.ast.select.SelectClause; import com.tirion.db.sql.ast.select.SelectStatement; import com.tirion.db.sql.ast.select.SmartSelectStatement; import com.tirion.db.sql.ast.select.WhereClause; /** * @author Veljko Zivkovic, Copyright (C) All Rights Reserved */ public final class SelectTransformer extends AbstractTransformer { private Transformer boolTransformer = new BooleanExpressionTransformer(); @Override public Node transform(CommonTree root) { assertType(root, SqlGrammarParser.SELECT_STATEMENT); SmartSelectStatement stmt = new SmartSelectStatement(); stmt.setSelectClause(transformSelectClause((CommonTree)root.getChild(0))); stmt.setFromClause(transformFromClause((CommonTree)root.getChild(1))); int index = 2; JoinClause joinClause = new JoinClause(); while(true) { CommonTree node = (CommonTree)root.getChild(index); if(node == null || node.getType() != SqlGrammarParser.JOIN) { break; } joinClause.append(transformatJoin(node)); ++index; } if(joinClause.joinCount() > 0) { stmt.setJoinClause(joinClause); } CommonTree node = (CommonTree)root.getChild(index); if(node != null && node.getType() == SqlGrammarParser.WHERE) { stmt.setWhereClause(transformWhereClause(node)); ++index; } node = (CommonTree)root.getChild(index); if(node != null && node.getType() == SqlGrammarParser.GROUP) { stmt.setGroupByClause(transformGroupByClause(node)); ++index; } node = (CommonTree)root.getChild(index); if(node != null && node.getType() == SqlGrammarParser.HAVING) { stmt.setHavingClause(transformHavingClause(node)); ++index; } node = (CommonTree)root.getChild(index); if(node != null && node.getType() == SqlGrammarParser.ORDER) { stmt.setOrderByClause(transformOrderByClause(node)); ++index; } node = (CommonTree)root.getChild(index); if(node != null && node.getType() == SqlGrammarParser.LIMIT) { stmt.setLimitClause(transformLimitClause(node)); ++index; } return stmt; } private SelectClause transformSelectClause(CommonTree root) { assertType(root, SqlGrammarParser.SELECT); SelectClause selectClause = new SelectClause(); for (int i = 0; i < root.getChildCount(); i++) { CommonTree node = (CommonTree)root.getChild(i); if(node.getType() == SqlGrammarParser.STAR) { Star star = new Star(); star.setOwner(((CommonTree)node.getChild(0)).getText()); selectClause.append(star); } else if(node.getType() == SqlGrammarParser.NAME) { FieldRef fieldRef = new FieldRef(); fieldRef.setName(node.getText()); String owner = null; String alias = null; if(node.getChildCount() == 2) { owner = ((CommonTree)node.getChild(0)).getText(); alias = ((CommonTree)node.getChild(1).getChild(0)).getText(); } else if(node.getChildCount() == 1) { CommonTree child = (CommonTree)node.getChild(0); if(child.getType() == SqlGrammarParser.AS) { alias = child.getChild(0).getText(); } else { owner = child.getText(); } } fieldRef.setOwner(owner); fieldRef.setAlias(alias);; selectClause.append(fieldRef); } else if(node.getType() == SqlGrammarParser.FUNCTION_CALL) { FunctionCall functionCall = transformFunctionCall(node); selectClause.append(functionCall); } else { throw new IllegalArgumentException("Unexpected token '" + super.tokenIdToString(node.getType()) + "'"); } } return selectClause; } private FunctionCall transformFunctionCall(CommonTree node) { assertType(node, SqlGrammarParser.FUNCTION_CALL); FunctionCall functionCall = new FunctionCall(); functionCall.setName(((CommonTree)node.getChild(0)).getText()); int lastIndex = node.getChildCount() - 1; if(node.getChild(lastIndex).getType() == SqlGrammarParser.AS) { functionCall.setAlias(((CommonTree)node.getChild(lastIndex).getChild(0)).getText()); --lastIndex; } for (int j = 1; j <= lastIndex; j++) { CommonTree child = (CommonTree) node.getChild(j); switch (child.getType()) { case SqlGrammarParser.STAR: functionCall.append(new Star()); break; case SqlGrammarParser.NAME: FieldRef fieldRef = new FieldRef(); fieldRef.setName(child.getText()); if(child.getChildCount() > 0) { fieldRef.setOwner(((CommonTree)child.getChild(0)).getText()); } functionCall.append(fieldRef); break; case SqlGrammarParser.INT: // pass thru case SqlGrammarParser.FLOAT: Constant constant = new Constant(); constant.setValue(((CommonTree)child).getText()); functionCall.append(constant); break; case SqlGrammarParser.STRING: constant = new Constant(); constant.setValue(Util.trimQuotes(((CommonTree)child).getText())); functionCall.append(constant); break; default: throw new IllegalArgumentException("Unexpected token '" + tokenIdToString(child.getType()) + "'"); } } return functionCall; } private FromClause transformFromClause(CommonTree root) { assertType(root, SqlGrammarParser.FROM); String alias = null; if(root.getChildCount() > 1) { alias = ((CommonTree) root.getChild(1).getChild(0)).getText(); } FromClause from = new FromClause(); from.setAlias(alias); CommonTree child = (CommonTree) root.getChild(0); if(child.getType() == SqlGrammarParser.NAME) { EntityRef entityRef = new EntityRef(); entityRef.setName(child.getText()); from.setTable(entityRef); } else if(child.getType() == SqlGrammarParser.SELECT_STATEMENT) { SelectStatement selectStatement = (SelectStatement) transform(child); from.setSubSelect(selectStatement); } else { throw new IllegalArgumentException("Unexpected token '" + tokenIdToString(child.getType()) + "'"); } return from; } private Join transformatJoin(CommonTree root) { assertType(root, SqlGrammarParser.JOIN); Join join = new Join(); JoinType joinType = JoinType.fromString(((CommonTree) root.getChild(0)).getText()); join.setJoinType(joinType); int onIndex = 2; String alias = null; CommonTree child = (CommonTree) root.getChild(2); if(child.getType() == SqlGrammarParser.AS) { alias = ((CommonTree)child.getChild(0)).getText(); ++onIndex; } join.setAlias(alias); child = (CommonTree) root.getChild(1); if(child.getType() == SqlGrammarParser.NAME) { EntityRef entityRef = new EntityRef(); entityRef.setName(child.getText()); join.setTable(entityRef); } else if(child.getType() == SqlGrammarParser.SELECT_STATEMENT) { join.setSubSelect((SelectStatement)transform(child)); } else { throw new IllegalArgumentException("Unexpected token '" + tokenIdToString(child.getType()) + "'"); } join.setCondition((BoolExpression)boolTransformer.transform((CommonTree) root.getChild(onIndex).getChild(0))); return join; } private WhereClause transformWhereClause(CommonTree root) { assertType(root, SqlGrammarParser.WHERE); WhereClause whereClause = new WhereClause(); whereClause.setExpression((BoolExpression)boolTransformer.transform((CommonTree)root.getChild(0))); return whereClause; } private GroupByClause transformGroupByClause(CommonTree root) { assertType(root, SqlGrammarParser.GROUP); GroupByClause groupBy = new GroupByClause(); for (int i = 0; i < root.getChildCount(); i++) { String fieldName = ((CommonTree)root.getChild(i)).getText(); String owner = null; if(root.getChild(i).getChildCount() > 0) { owner = root.getChild(i).getChild(0).getText(); } FieldRef fieldRef = new FieldRef(); fieldRef.setName(fieldName); fieldRef.setOwner(owner); groupBy.append(fieldRef); } return groupBy; } private HavingClause transformHavingClause(CommonTree root) { assertType(root, SqlGrammarParser.HAVING); HavingClause havingClause = new HavingClause(); havingClause.setExpression((BoolExpression)boolTransformer.transform((CommonTree)root.getChild(0))); return havingClause; } private OrderByClause transformOrderByClause(CommonTree root) { assertType(root, SqlGrammarParser.ORDER); OrderByClause orderBy = new OrderByClause(); for (int i = 0; i < root.getChildCount(); i++) { CommonTree child = (CommonTree)root.getChild(i); String fieldName = child.getText(); OrderKind orderKind = OrderKind.ASC; String owner = null; if(child.getChildCount() == 2) { owner = ((CommonTree)child.getChild(0)).getText(); orderKind = OrderKind.parseFromString(((CommonTree)child.getChild(1)).getText()); } else if(child.getChildCount() == 1) { CommonTree childChild = (CommonTree)child.getChild(0); if(childChild.getType() == SqlGrammarParser.NAME) { owner = childChild.getText(); } else { orderKind = OrderKind.parseFromString(childChild.getText()); } } FieldRef fieldRef = new FieldRef(); fieldRef.setName(fieldName); fieldRef.setOwner(owner); orderBy.append(fieldRef, orderKind); } return orderBy; } private LimitClause transformLimitClause(CommonTree root) { assertType(root, SqlGrammarParser.LIMIT); LimitClause limitClause = new LimitClause(); String value = ((CommonTree)root.getChild(0)).getText(); limitClause.setValue(Integer.parseInt(value)); return limitClause; } }
true
268762e40fdf48de0d1005417b9665b3da4504b2
Java
TanmayBhaise/repo1
/Employee/src/main/java/com/proj2/CRunner.java
UTF-8
1,019
2.46875
2
[]
no_license
package com.proj2; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import com.proj2.emp.Employee; import com.proj2.serv.EmpService; @Component public class CRunner implements CommandLineRunner { @Autowired private Employee e; @Autowired private EmpService es; @Override public void run(String... args) throws Exception { // TODO Auto-generated method stub //es.insertdb(e); List<Employee> list = es.getAllEmployee(); System.out.println("EmpId\tEmpName\tEmpSal"); for(Employee i: list) { System.out.println(i.getEid() + "\t" + i.getEname()+ "\t"+ i.getEsal()); } Employee e1 = es.getEmployeeById(222); System.out.println("Employee Details of id 111:"); System.out.println(e1.getEid() + "\t" + e1.getEname()+"\t"+e1.getEsal()); // String s = es.deleteById(444); // System.out.println(s+" id 444"); } }
true
1b3b2e5e8f6479108ea0162ca35d425ff76c5a3e
Java
xusoku/PlayShareElement
/app/src/main/java/com/test/transitiondemo/PlayStateSaver.java
UTF-8
1,191
2.21875
2
[]
no_license
package com.test.transitiondemo; import android.os.Bundle; import android.view.View; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.ui.PlayerView; import com.hw.ycshareelement.transition.ViewStateSaver; /** * Created by xushengfu on 2019/4/24. */ public class PlayStateSaver extends ViewStateSaver { public boolean getIsPlaying(Bundle bundle) { return bundle.getBoolean("isPlaying"); } public long getPosition(Bundle bundle) { return bundle.getLong("textColor"); } @Override protected void captureViewInfo(View view, Bundle bundle) { if (view instanceof PlayerView) { PlayerView playerView= (PlayerView) view; bundle.putBoolean("isPlaying",isPlaying(playerView.getPlayer())); bundle.putLong("position",playerView.getPlayer()==null?0:playerView.getPlayer().getCurrentPosition()); } } private boolean isPlaying(Player player) { return player != null && player.getPlaybackState() != Player.STATE_ENDED && player.getPlaybackState() != Player.STATE_IDLE && player.getPlayWhenReady(); } }
true
028bd06544a6ce01d5b9a4f03e79b57942b3a55d
Java
cha63506/CompSecurity
/youtube-source/src/com/google/android/apps/youtube/app/adapter/at.java
UTF-8
2,360
1.507813
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.android.apps.youtube.app.adapter; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.youtube.app.ui.fv; import com.google.android.apps.youtube.common.fromguava.c; import com.google.android.apps.youtube.core.a.a; import com.google.android.apps.youtube.datalib.legacy.model.Playlist; import com.google.android.youtube.h; import java.util.HashMap; import java.util.Map; // Referenced classes of package com.google.android.apps.youtube.app.adapter: // au public class at extends a { protected final Resources a; private final LayoutInflater b; private final int d; private final Map e = new HashMap(); private final Bitmap f; public at(Context context, int i) { b = LayoutInflater.from(context); a = context.getResources(); d = i; f = fv.a(a); } protected final View a(View view, ViewGroup viewgroup) { View view1 = view; if (view == null) { view1 = b.inflate(d, viewgroup, false); view1.setTag(new au(view1)); } return view1; } protected final View a(Playlist playlist, View view, ViewGroup viewgroup) { view = a(view, viewgroup); viewgroup = (au)view.getTag(); ((au) (viewgroup)).a.setText(playlist.title); ((au) (viewgroup)).b.setImageResource(h.J); return view; } public final void a() { e.clear(); super.a(); } protected final void a(int i, Object obj) { obj = (Playlist)obj; c.a(obj); e.put(((Playlist) (obj)).contentUri, f); super.a(i, obj); } protected final void a(Object obj) { obj = (Playlist)obj; c.a(obj); e.put(((Playlist) (obj)).contentUri, f); super.a(obj); } public View getView(int i, View view, ViewGroup viewgroup) { return a((Playlist)getItem(i), view, viewgroup); } }
true
3ec8c650af1409e58befcd4c4c26ae7b554b7505
Java
SaberAlpha/kaola
/project/app/src/main/java/qianfeng/com/kaola1613/other/widget/BlurFrameLayout.java
UTF-8
1,606
2.28125
2
[]
no_license
package qianfeng.com.kaola1613.other.widget; /** * Created by liujianping on 2016/10/20. */ import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.FrameLayout; import qianfeng.com.kaola1613.other.utils.BlurCalculate; public class BlurFrameLayout extends FrameLayout { private BlurCalculate mBlurCalculate; public BlurFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub mBlurCalculate=new BlurCalculate(this); } public BlurFrameLayout(Context context) { super(context); // TODO Auto-generated constructor stub } /*** * radius for linearlayout***/ public void setRadius(int arg0) { if(mBlurCalculate!=null) mBlurCalculate.setRadius(arg0); invalidate(); } @Override protected void onAttachedToWindow() { // TODO Auto-generated method stub super.onAttachedToWindow(); mBlurCalculate.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { // TODO Auto-generated method stub super.onDetachedFromWindow(); mBlurCalculate.BluronDetachedFromWindow(); } @Override protected void dispatchDraw(Canvas canvas) { // TODO Auto-generated method stub if(mBlurCalculate.isCanvasChanged(canvas)) mBlurCalculate.BlurCanvas(); else { mBlurCalculate.DrawCanvas(canvas); super.dispatchDraw(canvas); } } }
true
2c2e75dba9445a3600abfc416d0a110e8f855969
Java
freestrings/shreder-core
/src/test/resources/com/freestrings/shreder/type/Parent.java
UTF-8
204
2.078125
2
[]
no_license
package com.freestrings.shreder.type; import javax.validation.constraints.NotNull; public class Parent { @NotNull private int parentValue; public int getParentValue() { return parentValue; } }
true
2eb72be4f2180ef18c7b11ae7582b66680332331
Java
Nullrable/soul
/shenyu-plugin/shenyu-plugin-apache-dubbo/src/test/java/org/apache/shenyu/plugin/apache/dubbo/cache/DubboProviderVersionCacheTest.java
UTF-8
3,363
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shenyu.plugin.apache.dubbo.cache; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.rpc.Invoker; import org.apache.shenyu.common.constant.Constants; import org.apache.shenyu.common.utils.ReflectUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * The Test Case For DubboProviderVersionCache. */ @RunWith(MockitoJUnitRunner.class) public final class DubboProviderVersionCacheTest { private DubboProviderVersionCache dubboProviderVersionCache; @Before public void setUp() { dubboProviderVersionCache = DubboProviderVersionCache.getInstance(); } @Test public void getInstance() { assertNotNull(this.dubboProviderVersionCache); } @Test public void testGet() { assertNotNull(this.dubboProviderVersionCache.get("/test")); } @Test public void testCacheProviderVersion() { final String version = "2.7.3"; final String path = "/test"; final DubboProviderVersionCache dubboProviderVersionCache = spy(DubboProviderVersionCache.getInstance()); ReferenceConfig referenceConfig = mock(ReferenceConfig.class); Invoker invoker = mock(Invoker.class); URL url = mock(URL.class); mockStatic(ReflectUtils.class); when(ReflectUtils.getFieldValue(referenceConfig, Constants.DUBBO_REFRENCE_INVOKER)).thenReturn(invoker); when(invoker.getUrl()).thenReturn(url); when(url.getParameter(anyString())).thenReturn(version); dubboProviderVersionCache.cacheProviderVersion(path, referenceConfig); assertEquals(version, dubboProviderVersionCache.get(path)); final String nullVersion = null; when(url.getParameter(anyString())).thenReturn(nullVersion); dubboProviderVersionCache.cacheProviderVersion(path, referenceConfig); assertEquals("", dubboProviderVersionCache.get(path)); dubboProviderVersionCache.invalidateAll(); } @Test public void testInvalidate() { this.dubboProviderVersionCache.invalidate("/test"); this.dubboProviderVersionCache.invalidateAll(); } }
true
8006d4aeafc68f07efe54d9f1dc61788096b10c2
Java
avers182/saucemanager
/src/main/java/ru/sav/saucemanager/domain/SecGroup.java
UTF-8
672
2.15625
2
[]
no_license
package ru.sav.saucemanager.domain; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import java.util.List; @Entity @Table(name = "o_bs_secgroup") public class SecGroup { @Id private Long id; @OneToMany(mappedBy = "secGroup") private List<Membership> memberships; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public List<Membership> getMemberships() { return memberships; } public void setMemberships(List<Membership> memberships) { this.memberships = memberships; } }
true
69e711e7cd2fcba749a8e12f062b5df925d8f45b
Java
yooreka/chisong1
/0501/src/ByteFlileInou.java
UTF-8
1,404
3.40625
3
[]
no_license
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ByteFlileInou { public static void main(String[] args) { //파일에 기록할 스트림 변수 FileOutputStream fos = null; try { //예외가 발생할 가능성이 있는 코드 //파일에 바이트 단위로 기록할 스트림 생성 fos = new FileOutputStream("./test.txt"); String msg = "안녕하세요"; fos.write(msg.getBytes()); fos.flush(); }catch(Exception e) {e.getMessage(); e.printStackTrace(); //예외가 발생했을 떄 수행할 코드 }finally { //무조건 수행되는 코드 try { fos.close(); }catch(IOException e) { e.printStackTrace(); } } //파일의 내용을 바이트 단위로 읽기 //try resources //try()안에서 생성한 것은 close를 호출하지않아도 자동으로 close를 호출함 try(FileInputStream fis = new FileInputStream("./test.txt")){ //파일의 내용을 바이트 단위로 일기 byte[] b = new byte[1024]; int len = fis.read(b); if(len == -1) { System.out.println("읽은 데이터가 없음"); }else { System.out.println(new String(b)); } }catch(Exception e) { //예외 내용출력 System.out.println(e.getMessage()); //예외 발생지점 역추 e.printStackTrace(); } } }
true
9b7a2b40dfc4b641914723a0bae4d802d75bf745
Java
joker1618/java-libs
/java-repo/src/test/java/junitTests/school/ClassRoom.java
UTF-8
517
2.234375
2
[]
no_license
package junitTests.school; import xxx.joker.libs.repo.design.SimpleRepoEntity; import xxx.joker.libs.repo.design.annotation.marker.EntityPK; public class ClassRoom extends SimpleRepoEntity { @EntityPK private String roomLabel; public ClassRoom() { } public ClassRoom(String roomLabel) { this.roomLabel = roomLabel; } public String getRoomLabel() { return roomLabel; } public void setRoomLabel(String roomLabel) { this.roomLabel = roomLabel; } }
true
bd6a4e4badcfd252e0f69cb13bc0ee6219ab27f3
Java
nendraharyo/presensimahasiswa-sourcecode
/com/google/gson/Gson$6.java
UTF-8
1,007
1.898438
2
[]
no_license
package com.google.gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.util.concurrent.atomic.AtomicLong; final class Gson$6 extends TypeAdapter { Gson$6(TypeAdapter paramTypeAdapter) {} public AtomicLong read(JsonReader paramJsonReader) { Number localNumber = (Number)this.val$longAdapter.read(paramJsonReader); AtomicLong localAtomicLong = new java/util/concurrent/atomic/AtomicLong; long l = localNumber.longValue(); localAtomicLong.<init>(l); return localAtomicLong; } public void write(JsonWriter paramJsonWriter, AtomicLong paramAtomicLong) { TypeAdapter localTypeAdapter = this.val$longAdapter; Long localLong = Long.valueOf(paramAtomicLong.get()); localTypeAdapter.write(paramJsonWriter, localLong); } } /* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\com\google\gson\Gson$6.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
true
fcf4bf63c546973dc52059021b74e152b60cba9f
Java
hayashi-h-s/omikuji_app_android
/app/src/main/java/com/haya/omikuji/app/ResultActivity.java
UTF-8
1,208
2.359375
2
[]
no_license
package com.haya.omikuji.app; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import java.util.Random; public class ResultActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result_main); TextView resultTextView = findViewById(R.id.result_text_view); String unsei = ""; Random random = new Random(); switch (random.nextInt( 5)) { case 0: unsei = "大吉"; break; case 1: unsei = "吉"; break; case 2: unsei = "中吉"; break; case 3: unsei = "小吉"; break; case 4: unsei = "末吉"; break; case 5: unsei = "凶"; } resultTextView.setText(unsei); // Toast.makeText( ResultActivity.this, unsei, Toast.LENGTH_SHORT).show(); } }
true
4fd56f8684b742695b65f01ac85d84d4b431dc00
Java
nova-dev-team/nova
/src/worker/nova/worker/handler/StopVnodeHandler.java
UTF-8
3,123
2.15625
2
[]
no_license
package nova.worker.handler; import java.util.UUID; import org.apache.log4j.Logger; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.libvirt.Domain; import org.libvirt.LibvirtException; import nova.common.service.SimpleAddress; import nova.common.service.SimpleHandler; import nova.master.models.Vnode; import nova.worker.NovaWorker; import nova.worker.api.messages.StopVnodeMessage; import nova.worker.daemons.VnodeStatusDaemon; /** * destroy and undefine a domain on a physical host * * @author shayf, Tianyu Chen * */ public class StopVnodeHandler implements SimpleHandler<StopVnodeMessage> { /** * Log4j logger. */ Logger log = Logger.getLogger(StopVnodeHandler.class); @Override public void handleMessage(StopVnodeMessage msg, ChannelHandlerContext ctx, MessageEvent e, SimpleAddress xreply) { final String virtService; if (msg.getHyperVisor().equalsIgnoreCase("kvm")) { virtService = "qemu:///system"; } else if (msg.getHyperVisor().equalsIgnoreCase("vstaros")) { virtService = "vstaros:///system"; } else if (msg.getHyperVisor().equalsIgnoreCase("lxc")) { virtService = "lxc:///"; } else { virtService = "some xen"; } try { Domain dom = null; synchronized (NovaWorker.getInstance().getConnLock()) { dom = NovaWorker.getInstance().getConn(virtService, false) .domainLookupByUUIDString(msg.getUuid()); // NovaWorker.getInstance().closeConnectToKvm(); } if (dom == null) { VnodeStatusDaemon.putStatus(UUID.fromString(msg.getUuid()), Vnode.Status.CONNECT_FAILURE); log.error("cannot connect and close domain " + msg.getUuid()); return; } if (!msg.isSuspendOnly()) { VnodeStatusDaemon.putStatus(UUID.fromString(msg.getUuid()), Vnode.Status.SHUTTING_DOWN); // if domain is running, shut it down if (dom.isActive() == 1) { dom.destroy(); log.info("domain shut down"); } if (msg.delvm && (dom.isPersistent() == 1)) { dom.undefine(); log.info("domain undefined"); } else { VnodeStatusDaemon.putStatus(UUID.fromString(msg.getUuid()), Vnode.Status.SHUT_OFF); NovaWorker.getInstance().getVnodeIP() .remove(UUID.fromString(msg.getUuid())); } } else { dom.suspend(); log.info("domain suspended"); VnodeStatusDaemon.putStatus(UUID.fromString(msg.getUuid()), Vnode.Status.PAUSED); } } catch (LibvirtException ex) { log.error("error closing domain " + msg.getUuid(), ex); } } }
true
34c3fcbc0b8c6633aaab849b6b9862cb00c4ab13
Java
madsdyd/klimavenligkogebog
/src/main/java/dydensborg/dk/Recipe.java
UTF-8
14,198
2.75
3
[]
no_license
package dydensborg.dk; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.MathContext; import java.nio.file.Files; import java.nio.file.Path; import java.text.DecimalFormat; import java.util.*; /** * Created by madsdyd on 11-07-17. */ public class Recipe { static class Content { String id; double amount; public static Content fromJsonObject(JsonObject jsonObject) { Content c = new Content(); c.id = jsonObject.getString("id"); if ( c.id == null || c.id.equals("")) { System.err.println("While parsing recipe ingredient, missing id. Please check file for errors"); } if ( jsonObject.getJsonNumber("amount") == null) { System.err.println("While parsing recipe ingredient " + c.id + ", missing amount. Please check file for errors"); } c.amount = jsonObject.getJsonNumber("amount").doubleValue(); return c; } @Override public String toString() { return "Content{" + "id='" + id + '\'' + ", amount=" + amount + '}'; } // Adjust to a single person, based on the number of persons the recipe is for. public void adustToPersons(double persons) { amount = amount / persons; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String toTex(Map<String,Ingredient> ingredientMap) { StringBuilder res = new StringBuilder(); // We present the information differently than it is stored double presentationAmount = getAmount(); String presentationUnit = ingredientMap.get(getId()).getUnit(); // Convert some units to make stuff prettier // Weird units // Teaspoon to something larger if ( presentationUnit.equals("tsk") && presentationAmount > 8) { presentationAmount = presentationAmount / 3; presentationUnit = "spsk"; } // Spoons to dl if ( presentationUnit.equals("spsk") && presentationAmount > 10) { // 1 spsk is 0.15 dl presentationAmount = presentationAmount *0.15; presentationUnit = "dl"; } // SI: Basic rule, if larger > 1000, go up in unit, if lower than 1, go down // Special rule for dl => l unit. if (presentationAmount > 10) { // If we know the unit, go "up" in unit if (presentationUnit.equals("dl")) { presentationAmount = presentationAmount / 10; presentationUnit = "l"; } } if (presentationAmount > 1000) { // If we know the unit, go "up" in unit if (presentationUnit.equals("g")) { presentationAmount = presentationAmount / 1000; presentationUnit = "kg"; } if (presentationUnit.equals("ml")) { presentationAmount = presentationAmount / 1000; presentationUnit = "l"; } } if (presentationAmount < 1) { // If we know the unit, go "down" in unit if (presentationUnit.equals("kg")) { presentationAmount = presentationAmount * 1000; presentationUnit = "g"; presentationAmount = Math.round(presentationAmount); } if (presentationUnit.equals("l")) { presentationAmount = presentationAmount * 1000; presentationUnit = "ml"; presentationAmount = Math.round(presentationAmount); } } // Do not use decimals for these types. if (presentationUnit.equals("example")) { presentationAmount = Math.round(presentationAmount); } // format without trailing zeros, max two decimals. // String amountString = new DecimalFormat("###.##").format(presentationAmount); String amountString = ""; // For some units, round or use interval. if ((presentationUnit.equals("tsk") || presentationUnit.equals("spsk")) && presentationAmount > 1 ) { if ((presentationAmount - Math.floor(presentationAmount)) < 0.3) { amountString = new DecimalFormat("###.##").format(Math.floor(presentationAmount)); } else { if ((Math.ceil(presentationAmount) - presentationAmount) < 0.3) { amountString = new DecimalFormat("###.##").format(Math.ceil(presentationAmount)); } else { amountString = new DecimalFormat("###.##").format(Math.floor(presentationAmount)) + "-" + new DecimalFormat("###.##").format(Math.ceil(presentationAmount)); } } } else { // Round to two significant digits BigDecimal bd = new BigDecimal(presentationAmount); bd = bd.round(new MathContext(2)); presentationAmount = bd.doubleValue(); amountString = new DecimalFormat("###.##").format(presentationAmount); } // Ignore amounts that are zero if ( getAmount() < 0.000001 ) { amountString = ""; presentationUnit = ""; } res .append(" \\ruingredient{") .append(getId()).append("}{") .append(amountString).append("}{") .append(presentationUnit) .append("}" + System.lineSeparator()); return res.toString(); } } static public class MealTypeOrdering { static public int sortOrder(String mealType) { switch ( mealType) { case "Aftensmad" : return 30; case "Morgenmad" : return 10; case "Frokost" : return 20; case "Snack" : return 40; default : return 50; } } } // Name of the recipe String name; // Short description / introduction String desc; // The steps in the recipe String recipe; // Content List<Content> contents = new ArrayList<>(); // Calculated co2 for the total number of persons double co2; // A CO2 rating String co2Rating = "undefined"; // Number of persons recipe match - read from file, then adjusted to setting int persons; // Time needed to prepare the dish. String time; // type of meal, "Morgenmad", "Frokost", "Aftensmad", etc. String mealType; int mealOrder; // Calculated based on mealType.... public String getName() { return name; } public int getMealOrder() { return mealOrder; } public String getMealType() { return mealType; } public double getCo2() { return co2; } public int getPersons() { return persons; } public String getCo2Rating() { return co2Rating; } /** * Create a single Posting object from a JsonObject. * <p> * I would assume you could do stuff like this with bindings, but I do not know how. And do not really care. * * @param jsonObject The object to parse from. * @return A new posting object, representing the stuff in the jsonObject */ public static Recipe fromJsonObject(JsonObject jsonObject) { Recipe r = new Recipe(); r.name = jsonObject.getString("name"); if ( r.name == null || r.name.equals("")) { System.err.println("While parsing recipe, missing name. Please check file for errors"); } r.desc = jsonObject.getString("desc"); if ( r.desc == null || r.desc.equals("")) { System.err.println("While parsing recipe for " + r.name + ", missing desc. Please check file for errors"); } r.recipe = jsonObject.getString("recipe"); if ( r.recipe == null || r.recipe.equals("")) { System.err.println("While parsing recipe for " + r.name + ", missing recipe. Please check file for errors"); } r.time = jsonObject.getString("time"); if ( r.time == null || r.time.equals("")) { r.time = "Ukendt"; } // If meal type is not set, use Aftensmad. try { r.mealType = jsonObject.getString("meal"); } catch (NullPointerException e) { r.mealType = "Aftensmad"; } r.mealOrder = MealTypeOrdering.sortOrder(r.mealType); // Parse the array. JsonArray content = jsonObject.getJsonArray("content"); if ( content == null || content.size() == 0 ) { System.err.println("While parsing recipe for " + r.name + ", missing content. Please check file for errors"); } for (JsonObject c : content.getValuesAs(JsonObject.class)) { r.contents.add(Content.fromJsonObject(c)); } if ( jsonObject.getJsonNumber("persons") == null) { System.err.println("While parsing recipe ingredient " + r.name + ", missing persons. Please check file for errors"); } r.persons = jsonObject.getJsonNumber("persons").intValue(); System.out.println("Parsed recipe " + r.name); return r; } /** * Creates a list of Postings from a JSON file with multiple posting in. * * @param path The path to a JSON poting file from Spiir * @return A list of postings corresponding to the file. * @throws IOException If path can not be found */ public static List<Recipe> fromJsonFile(Path path) throws IOException { List<Recipe> recipes = new ArrayList<>(); try (InputStream is = Files.newInputStream(path); JsonReader rdr = Json.createReader(is)) { JsonArray jpostings = rdr.readArray(); for (JsonObject result : jpostings.getValuesAs(JsonObject.class)) { recipes.add(fromJsonObject(result)); } } return recipes; } @Override public String toString() { return "Recipe{" + "name='" + name + '\'' + ", desc='" + desc + '\'' + ", recipe='" + recipe + '\'' + ", contents=" + contents + ", co2=" + co2 + ", persons=" + persons + ", time='" + time + '\'' + '}'; } // Only call this once. It adjust the content to the number of persons. public void adjustToPersons(int numPersons) { if (persons != numPersons) { contents.forEach(c -> { c.adustToPersons( ((double) persons) / numPersons); }); persons = numPersons; } } public double calculateCo2(Map<String, Ingredient> ingredientsMap, Rater rater) { double res = 0.0; for(Content c : contents) { if ( null == ingredientsMap.get(c.getId())) { System.err.println("While calculating CO2 for '" + name + "': Unable to locate ingredient '" + c.getId() + "'"); } res += c.getAmount() * ingredientsMap.get(c.getId()).getCo2(); }; co2 = res; co2Rating = rater.rate(co2/persons); return res; } /** * Generate a tex string. * * Environment variables * * #1 : Navn * #2 : Introtekst / desc * #3 : How many persons * #4 : CO2 * #5 : Tid * #6 : Ingredientslist * #7 : Recipe * * @return A tex String. */ public String toTex(Map<String, Ingredient> ingredientMap) { StringBuilder sb = new StringBuilder(); // Ingredient list StringBuilder il = new StringBuilder(); //il.append(" \\begin{ruingredients}" + System.lineSeparator()); for (Content c: contents) { il.append(c.toTex(ingredientMap)); } //il.append(" \\end{ruingredients}" + System.lineSeparator()); // Co2 is currently for the entire course, lets do per person too String co2string = String.format("%.2f/%.2f", co2/persons, co2); // The steps needs to be calculated from \\ in the code. List<String> stepsList = Arrays.asList(recipe.split("\\\\")); StringBuilder steps = new StringBuilder(); for(String step : stepsList) { steps.append("\\rustep{").append(step.trim()).append("}").append(System.lineSeparator()); } sb .append("\\begin{rurecipe}" + System.lineSeparator()) .append(" {" + name + "}" + System.lineSeparator()) .append(" {" + desc.replaceAll(("\\\\"), ("\\\\\\\\" + System.lineSeparator())) + "}" + System.lineSeparator()) .append(" {" + persons + "}" + System.lineSeparator()) // #4 : C2 .append(" {" + co2string + "}" + System.lineSeparator()) .append(" {" + co2Rating + "}" + System.lineSeparator()) .append(" {" + time + "}" + System.lineSeparator()) .append(" {" + il.toString() + "}" + System.lineSeparator()) .append(" {" + steps.toString() + "}" + System.lineSeparator()) .append("\\end{rurecipe}" + System.lineSeparator() + System.lineSeparator()); return sb.toString(); } }
true
63363ce93f4a599999c99eec95f14125a0591733
Java
zhaoml529/erp
/src/com/erp/service/ProjectService.java
UTF-8
674
1.6875
2
[]
no_license
package com.erp.service; import java.util.List; import java.util.Map; import com.erp.model.Customer; import com.erp.model.Project; import com.erp.model.ProjectFollow; import com.erp.util.PageUtil; public interface ProjectService { boolean delProject(Integer projectId ); List<Project> findProjectList(Map<String, Object> param, PageUtil pageUtil ); Long getCount(Map<String, Object> param, PageUtil pageUtil ); boolean persistenceProject(Project p, Map<String, List<ProjectFollow>> map ); List<ProjectFollow> findProjectFollowsList(Integer projectId ); List<Customer> findCustomers(); List<Project> findProjectListCombobox(); }
true
29679bf26c614a078a9f07fe9dda284f59826242
Java
NrgXnat/container-service
/src/main/java/org/nrg/containers/model/xnat/Session.java
UTF-8
9,772
1.632813
2
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
package org.nrg.containers.model.xnat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Function; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.nrg.xdat.model.XnatAbstractresourceI; import org.nrg.xdat.model.XnatImageassessordataI; import org.nrg.xdat.model.XnatImagescandataI; import org.nrg.xdat.model.XnatImagesessiondataI; import org.nrg.xdat.om.XnatExperimentdata; import org.nrg.xdat.om.XnatImagesessiondata; import org.nrg.xdat.om.XnatResourcecatalog; import org.nrg.xdat.om.base.BaseXnatExperimentdata.UnknownPrimaryProjectException; import org.nrg.xft.XFTItem; import org.nrg.xft.security.UserI; import org.nrg.xnat.exceptions.InvalidArchiveStructure; import org.nrg.xnat.helpers.uri.URIManager; import org.nrg.xnat.helpers.uri.UriParserUtils; import org.nrg.xnat.helpers.uri.archive.AssessedURII; import org.nrg.xnat.helpers.uri.archive.ExperimentURII; import javax.annotation.Nullable; import java.util.List; import java.util.Objects; @JsonInclude(Include.NON_NULL) public class Session extends XnatModelObject { @JsonIgnore private XnatImagesessiondataI xnatImagesessiondataI; private List<Scan> scans; private List<Assessor> assessors; private List<Resource> resources; @JsonProperty("project-id") private String projectId; @JsonProperty("subject-id") private String subjectId; private String directory; public Session() {} public Session(final String sessionId, final UserI userI) { this.id = sessionId; loadXnatImagesessiondata(userI); this.uri = UriParserUtils.getArchiveUri(xnatImagesessiondataI); populateProperties(null); } public Session(final AssessedURII assessedURII) { final XnatImagesessiondata imagesessiondata = assessedURII.getSession(); if (imagesessiondata != null && XnatImagesessiondata.class.isAssignableFrom(imagesessiondata.getClass())) { this.xnatImagesessiondataI = imagesessiondata; this.uri = ((URIManager.DataURIA) assessedURII).getUri(); populateProperties(null); } } public Session(final XnatImagesessiondataI xnatImagesessiondataI) { this(xnatImagesessiondataI, null, null); } public Session(final XnatImagesessiondataI xnatImagesessiondataI, final String parentUri, final String rootArchivePath) { this.xnatImagesessiondataI = xnatImagesessiondataI; if (parentUri == null) { this.uri = UriParserUtils.getArchiveUri(xnatImagesessiondataI); } else { this.uri = parentUri + "/experiments/" + xnatImagesessiondataI.getId(); } populateProperties(rootArchivePath); } private void populateProperties(final String rootArchivePath) { this.id = xnatImagesessiondataI.getId(); this.label = xnatImagesessiondataI.getLabel(); this.xsiType = xnatImagesessiondataI.getXSIType(); this.projectId = xnatImagesessiondataI.getProject(); this.subjectId = xnatImagesessiondataI.getSubjectId(); try { this.directory = ((XnatExperimentdata) xnatImagesessiondataI).getCurrentSessionFolder(true); } catch (UnknownPrimaryProjectException | InvalidArchiveStructure e) { // ignored, I guess? } this.scans = Lists.newArrayList(); for (final XnatImagescandataI xnatImagescandataI : xnatImagesessiondataI.getScans_scan()) { this.scans.add(new Scan(xnatImagescandataI, this.uri, rootArchivePath)); } this.resources = Lists.newArrayList(); for (final XnatAbstractresourceI xnatAbstractresourceI : xnatImagesessiondataI.getResources_resource()) { if (xnatAbstractresourceI instanceof XnatResourcecatalog) { resources.add(new Resource((XnatResourcecatalog) xnatAbstractresourceI, this.uri, rootArchivePath)); } } this.assessors = Lists.newArrayList(); for (final XnatImageassessordataI xnatImageassessordataI : xnatImagesessiondataI.getAssessors_assessor()) { assessors.add(new Assessor(xnatImageassessordataI, this.uri, rootArchivePath)); } } public static Function<URIManager.ArchiveItemURI, Session> uriToModelObject() { return new Function<URIManager.ArchiveItemURI, Session>() { @Nullable @Override public Session apply(@Nullable URIManager.ArchiveItemURI uri) { XnatImagesessiondata imageSession; if (uri != null && AssessedURII.class.isAssignableFrom(uri.getClass())) { imageSession = ((AssessedURII) uri).getSession(); if (imageSession != null && XnatImagesessiondata.class.isAssignableFrom(imageSession.getClass())) { return new Session((AssessedURII) uri); } } else if (uri != null && ExperimentURII.class.isAssignableFrom(uri.getClass())) { final XnatExperimentdata experimentdata = ((ExperimentURII) uri).getExperiment(); if (experimentdata != null && XnatImagesessiondataI.class.isAssignableFrom(experimentdata.getClass())) { return new Session((XnatImagesessiondataI) experimentdata); } } return null; } }; } public static Function<String, Session> idToModelObject(final UserI userI) { return new Function<String, Session>() { @Nullable @Override public Session apply(@Nullable String s) { if (StringUtils.isBlank(s)) { return null; } final XnatImagesessiondata imagesessiondata = XnatImagesessiondata.getXnatImagesessiondatasById(s, userI, true); if (imagesessiondata != null) { return new Session(imagesessiondata); } return null; } }; } public Project getProject(final UserI userI) { loadXnatImagesessiondata(userI); return new Project(xnatImagesessiondataI.getProject(), userI); } public Subject getSubject(final UserI userI) { loadXnatImagesessiondata(userI); return new Subject(xnatImagesessiondataI.getSubjectId(), userI); } public void loadXnatImagesessiondata(final UserI userI) { if (xnatImagesessiondataI == null) { xnatImagesessiondataI = XnatImagesessiondata.getXnatImagesessiondatasById(id, userI, false); } } public XnatImagesessiondataI getXnatImagesessiondataI() { return xnatImagesessiondataI; } public void setXnatImagesessiondataI(final XnatImagesessiondataI xnatImagesessiondataI) { this.xnatImagesessiondataI = xnatImagesessiondataI; } public List<Resource> getResources() { return resources; } public void setResources(final List<Resource> resources) { this.resources = resources; } public List<Assessor> getAssessors() { return assessors; } public void setAssessors(final List<Assessor> assessors) { this.assessors = assessors; } public List<Scan> getScans() { return scans; } public void setScans(final List<Scan> scans) { this.scans = scans; } public String getProjectId() { return projectId; } public void setProjectId(final String projectId) { this.projectId = projectId; } public String getSubjectId() { return subjectId; } public void setSubjectId(final String subjectId) { this.subjectId = subjectId; } public String getDirectory() { return directory; } public void setDirectory(final String directory) { this.directory = directory; } @Override public XFTItem getXftItem(final UserI userI) { loadXnatImagesessiondata(userI); return xnatImagesessiondataI == null ? null : ((XnatImagesessiondata)xnatImagesessiondataI).getItem(); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; final Session that = (Session) o; return Objects.equals(this.xnatImagesessiondataI, that.xnatImagesessiondataI) && Objects.equals(this.scans, that.scans) && Objects.equals(this.assessors, that.assessors) && Objects.equals(this.resources, that.resources) && Objects.equals(this.projectId, that.projectId) && Objects.equals(this.subjectId, that.subjectId) && Objects.equals(this.directory, that.directory); } @Override public int hashCode() { return Objects.hash(super.hashCode(), xnatImagesessiondataI, scans, assessors, resources, projectId, subjectId, directory); } @Override public String toString() { return addParentPropertiesToString(MoreObjects.toStringHelper(this)) .add("scans", scans) .add("assessors", assessors) .add("resources", resources) .add("projectId", projectId) .add("subjectId", subjectId) .add("directory", directory) .toString(); } }
true
fbe0fac62d2ff3a43d5847075c3d638224c6db1e
Java
liuqingyang123ab/scmis
/src/com/xx/sm/framework/model/dao/impl/IMisUserDAO.java
UTF-8
362
1.796875
2
[]
no_license
package com.xx.sm.framework.model.dao.impl; import java.util.List; import com.xx.sm.framework.model.entity.MisUser; public interface IMisUserDAO { public boolean add(MisUser misUser); public boolean remove(String id); public boolean modify(MisUser misUser); public MisUser findByName(String name); public List<MisUser> findByLike(MisUser misUser); }
true
f97209d725fd8e77f13444a7225a37e4023bc579
Java
lvrenzhao/casecomment
/src/main/java/cn/gov/ahcourt/casecomment/mapper/BdCheckLevelsMapper.java
UTF-8
451
1.734375
2
[]
no_license
package cn.gov.ahcourt.casecomment.mapper; import cn.gov.ahcourt.casecomment.bean.BdCheckLevels; import java.util.List; public interface BdCheckLevelsMapper { int deleteByPrimaryKey(String levelid); int insert(BdCheckLevels record); BdCheckLevels selectByPrimaryKey(String levelid); List<BdCheckLevels> selectAll(BdCheckLevels bean); int updateByPrimaryKey(BdCheckLevels record); String getLevelByScore(String score); }
true
56106d84fac0db73d6a56353a3041b9116e2c12c
Java
MohsenShahriari/REST-OCD-Services
/LAS2peer Sample Service/src/main/i5/las2peer/services/servicePackage/algorithms/Algorithm.java
UTF-8
560
2.21875
2
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
package i5.las2peer.services.servicePackage.algorithms; import java.util.Locale; /** * An enum representation for overlapping community detection algorithms. * @author Sebastian * */ public enum Algorithm { UNDEFINED, RANDOM_WALK_LABEL_PROPAGATION_ALGORITHM, SPEAKER_LISTENER_LABEL_PROPAGATION_ALGORITHM, SSK_ALGORITHM, LINK_COMMUNITIES_ALGORITHM, CLIZZ_ALGORITHM; @Override public String toString() { String name = name(); name = name.replace('_', ' '); name = name.toLowerCase(Locale.ROOT); return name; } }
true
cc5770e30dab48064ae396ee0c261121ba4b7c62
Java
daegis/spring-boot-view
/spring-autowire/src/main/java/cn/aegisa/springbootview/condition/OnSystemPropertiesCondition.java
UTF-8
858
2.203125
2
[]
no_license
package cn.aegisa.springbootview.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; /** * Using IntelliJ IDEa. * * @author XIaNYINGDa at 9/28/2018 3:41 PM */ public class OnSystemPropertiesCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Map<String, Object> annotationattributes = metadata.getAnnotationAttributes(ConditionOnSystemProperties.class.getName()); Object name = annotationattributes.get("name"); Object value = annotationattributes.get("value"); System.out.println(name); System.out.println(value); return name.equals("aaa") && value.equals("bbb"); } }
true
993d5f67697724c3acc0b8ace556bab7150f6152
Java
Sanske/springboot-demo
/src/main/java/com/sanske/springdemo/common/exception/BioSanRuntimeException.java
UTF-8
244
2.078125
2
[]
no_license
package com.sanske.springdemo.common.exception; /** * @author sanske * @date 2018/8/2 下午3:33 **/ public class BioSanRuntimeException extends RuntimeException{ public BioSanRuntimeException(String message) { super(message); } }
true
55b1496266081c129e8e84f8ca8d7f3e303628ee
Java
nomskiii/LoanCalculator
/app/src/main/java/com/example/loancalculator/MainActivity.java
UTF-8
2,348
2.3125
2
[]
no_license
package com.example.loancalculator; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewDebug; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText LoanAmount,InterestRate,LoanTerm,LoanFees,MinimumPayment; private Button button; private TextView TotalInterest, MonthlyPayment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListenerOnButton(); } public void addListenerOnButton() { LoanAmount = (EditText) findViewById(R.id.textLoanAmount); InterestRate = (EditText) findViewById(R.id.textInterestRate); LoanTerm = (EditText) findViewById(R.id.textLoanTerm); LoanFees = (EditText) findViewById(R.id.textLoanFees); button = (Button) findViewById(R.id.button); TotalInterest = (TextView) findViewById(R.id.textViewTotalInterest); MonthlyPayment = (TextView) findViewById(R.id.textViewMonthlyPayment); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String value1 = LoanAmount.getText().toString(); String value2 = InterestRate.getText().toString(); String value3 = LoanTerm.getText().toString(); String value4 = LoanFees.getText().toString(); int a = Integer.parseInt(value1); int r = Integer.parseInt(value2); int t = Integer.parseInt(value3); int f = Integer.parseInt(value4); double ir = (double) ( 1 + .01 * r); double i = (double) ( ( a + f ) * (Math.pow(ir,t)) ); double ti = i - ( a + f ); double mp = i / ( t * 12 ); String totalInterest = String.valueOf(String.format("%.2f", ti)); String monthlyPayment = String.valueOf(String.format("%.2f", mp)); TotalInterest.setText(totalInterest); MonthlyPayment.setText(monthlyPayment); } }); } }
true
d1a733fc306a929391594d17c1fff1c21bf81a9f
Java
AaditPatel13/GamblingGames
/Gambing/src/BlackJackGame/blackJackGUI.java
UTF-8
17,179
3.015625
3
[]
no_license
package BlackJackGame; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.SpringLayout; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JButton; import java.awt.Color; import javax.swing.JTextArea; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.ArrayList; public class blackJackGUI { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { blackJackGUI window = new blackJackGUI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public blackJackGUI() { initialize(); } /** * Initialize the contents of the frame. */ Deck d1 = new Deck(); ArrayList<Card> deck = new ArrayList<>(); int playerTotalPoints= 0; int dealerTotalPoints = 0; int cardNumber = 3; Card dealerSecondCard; boolean playerAce =false; boolean dealerAce =false; int playerAceTotal; int dealerAceTotal; private void initialize() { frame = new JFrame(); frame.getContentPane().setBackground(new Color(0, 100, 0)); frame.setBounds(100, 100, 450, 508); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SpringLayout springLayout = new SpringLayout(); frame.getContentPane().setLayout(springLayout); JLabel lblPlayer = new JLabel("Player"); lblPlayer.setBackground(new Color(255, 255, 255)); lblPlayer.setFont(new Font("Lucida Grande", Font.PLAIN, 14)); springLayout.putConstraint(SpringLayout.WEST, lblPlayer, 201, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, lblPlayer, -10, SpringLayout.SOUTH, frame.getContentPane()); frame.getContentPane().add(lblPlayer); JLabel lblDealer = new JLabel("Dealer"); lblDealer.setFont(new Font("Lucida Grande", Font.PLAIN, 14)); springLayout.putConstraint(SpringLayout.NORTH, lblDealer, 10, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, lblDealer, 0, SpringLayout.WEST, lblPlayer); frame.getContentPane().add(lblDealer); JButton hitButton = new JButton("Hit"); hitButton.setEnabled(false); springLayout.putConstraint(SpringLayout.WEST, hitButton, 6, SpringLayout.EAST, lblPlayer); springLayout.putConstraint(SpringLayout.SOUTH, hitButton, -2, SpringLayout.SOUTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, hitButton, 76, SpringLayout.EAST, lblPlayer); frame.getContentPane().add(hitButton); JButton stayButton = new JButton("Stay"); stayButton.setEnabled(false); springLayout.putConstraint(SpringLayout.NORTH, stayButton, -4, SpringLayout.NORTH, lblPlayer); springLayout.putConstraint(SpringLayout.EAST, stayButton, -6, SpringLayout.WEST, lblPlayer); frame.getContentPane().add(stayButton); JLabel lblTotal = new JLabel("Total"); springLayout.putConstraint(SpringLayout.SOUTH, lblTotal, -19, SpringLayout.NORTH, stayButton); springLayout.putConstraint(SpringLayout.EAST, lblTotal, -219, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(lblTotal); JLabel playerTotal = new JLabel("0"); springLayout.putConstraint(SpringLayout.WEST, playerTotal, 6, SpringLayout.EAST, lblTotal); springLayout.putConstraint(SpringLayout.SOUTH, playerTotal, -19, SpringLayout.NORTH, hitButton); springLayout.putConstraint(SpringLayout.EAST, playerTotal, 0, SpringLayout.EAST, hitButton); frame.getContentPane().add(playerTotal); JLabel label = new JLabel("Total"); springLayout.putConstraint(SpringLayout.NORTH, label, 14, SpringLayout.SOUTH, lblDealer); springLayout.putConstraint(SpringLayout.WEST, label, 0, SpringLayout.WEST, lblPlayer); frame.getContentPane().add(label); JLabel dealerTotal = new JLabel("0"); springLayout.putConstraint(SpringLayout.NORTH, dealerTotal, 14, SpringLayout.SOUTH, lblDealer); springLayout.putConstraint(SpringLayout.WEST, dealerTotal, 8, SpringLayout.EAST, label); springLayout.putConstraint(SpringLayout.EAST, dealerTotal, -112, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(dealerTotal); JTextArea playerSlot1 = new JTextArea(); playerSlot1.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.WEST, playerSlot1, 10, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, playerSlot1, -105, SpringLayout.SOUTH, frame.getContentPane()); frame.getContentPane().add(playerSlot1); JTextArea dealerSlot1 = new JTextArea(); dealerSlot1.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, playerSlot1, 102, SpringLayout.SOUTH, dealerSlot1); springLayout.putConstraint(SpringLayout.EAST, dealerSlot1, 0, SpringLayout.EAST, playerSlot1); springLayout.putConstraint(SpringLayout.NORTH, dealerSlot1, 85, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, dealerSlot1, 10, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, dealerSlot1, -304, SpringLayout.SOUTH, frame.getContentPane()); frame.getContentPane().add(dealerSlot1); JTextArea dealerSlot2 = new JTextArea(); dealerSlot2.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, dealerSlot2, 85, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, dealerSlot2, 32, SpringLayout.EAST, dealerSlot1); frame.getContentPane().add(dealerSlot2); JTextArea dealerSlot3 = new JTextArea(); dealerSlot3.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, dealerSlot3, 28, SpringLayout.SOUTH, label); springLayout.putConstraint(SpringLayout.WEST, dealerSlot3, 199, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, dealerSlot2, -35, SpringLayout.WEST, dealerSlot3); springLayout.putConstraint(SpringLayout.EAST, dealerSlot3, -190, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(dealerSlot3); JTextArea playerSlot2 = new JTextArea(); playerSlot2.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, playerSlot2, 284, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, playerSlot2, 103, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, dealerSlot2, -102, SpringLayout.NORTH, playerSlot2); springLayout.putConstraint(SpringLayout.EAST, playerSlot1, -32, SpringLayout.WEST, playerSlot2); springLayout.putConstraint(SpringLayout.SOUTH, playerSlot2, -74, SpringLayout.NORTH, stayButton); frame.getContentPane().add(playerSlot2); JTextArea playerSlot3 = new JTextArea(); springLayout.putConstraint(SpringLayout.WEST, playerSlot3, 199, SpringLayout.WEST, frame.getContentPane()); playerSlot3.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.SOUTH, dealerSlot3, -102, SpringLayout.NORTH, playerSlot3); springLayout.putConstraint(SpringLayout.EAST, playerSlot2, -35, SpringLayout.WEST, playerSlot3); springLayout.putConstraint(SpringLayout.SOUTH, playerSlot3, 0, SpringLayout.SOUTH, playerSlot1); springLayout.putConstraint(SpringLayout.NORTH, playerSlot3, 0, SpringLayout.NORTH, playerSlot1); frame.getContentPane().add(playerSlot3); JTextArea playerSlot4 = new JTextArea(); springLayout.putConstraint(SpringLayout.WEST, playerSlot4, 288, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, playerSlot3, -28, SpringLayout.WEST, playerSlot4); playerSlot4.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, playerSlot4, 0, SpringLayout.NORTH, playerSlot1); springLayout.putConstraint(SpringLayout.SOUTH, playerSlot4, 0, SpringLayout.SOUTH, playerSlot1); springLayout.putConstraint(SpringLayout.EAST, playerSlot4, -101, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(playerSlot4); JTextArea dealerSlot4 = new JTextArea(); dealerSlot4.setBackground(new Color(0, 128, 0)); springLayout.putConstraint(SpringLayout.NORTH, dealerSlot4, 85, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, dealerSlot4, 28, SpringLayout.EAST, dealerSlot3); springLayout.putConstraint(SpringLayout.SOUTH, dealerSlot4, 182, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, dealerSlot4, 89, SpringLayout.EAST, dealerSlot3); frame.getContentPane().add(dealerSlot4); JTextArea textArea_6 = new JTextArea(); springLayout.putConstraint(SpringLayout.NORTH, textArea_6, 166, SpringLayout.NORTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.WEST, textArea_6, -11, SpringLayout.EAST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, textArea_6, -304, SpringLayout.SOUTH, frame.getContentPane()); springLayout.putConstraint(SpringLayout.EAST, textArea_6, -10, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(textArea_6); JTextArea dealerSlot5 = new JTextArea(); dealerSlot5.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, dealerSlot5, 0, SpringLayout.NORTH, dealerSlot1); springLayout.putConstraint(SpringLayout.WEST, dealerSlot5, 23, SpringLayout.EAST, dealerSlot4); springLayout.putConstraint(SpringLayout.SOUTH, dealerSlot5, 0, SpringLayout.SOUTH, dealerSlot1); springLayout.putConstraint(SpringLayout.EAST, dealerSlot5, -6, SpringLayout.WEST, textArea_6); frame.getContentPane().add(dealerSlot5); JTextArea playerSlot5 = new JTextArea(); playerSlot5.setBackground(new Color(34, 139, 34)); springLayout.putConstraint(SpringLayout.NORTH, playerSlot5, 102, SpringLayout.SOUTH, dealerSlot5); springLayout.putConstraint(SpringLayout.WEST, playerSlot5, 23, SpringLayout.EAST, playerSlot4); springLayout.putConstraint(SpringLayout.SOUTH, playerSlot5, 199, SpringLayout.SOUTH, dealerSlot5); springLayout.putConstraint(SpringLayout.EAST, playerSlot5, -11, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(playerSlot5); JButton btnDeal = new JButton("Deal"); springLayout.putConstraint(SpringLayout.WEST, btnDeal, 35, SpringLayout.WEST, frame.getContentPane()); springLayout.putConstraint(SpringLayout.SOUTH, btnDeal, -36, SpringLayout.NORTH, playerSlot1); springLayout.putConstraint(SpringLayout.EAST, btnDeal, -330, SpringLayout.EAST, frame.getContentPane()); frame.getContentPane().add(btnDeal); JLabel winOrLose = new JLabel(""); springLayout.putConstraint(SpringLayout.NORTH, winOrLose, 0, SpringLayout.NORTH, btnDeal); springLayout.putConstraint(SpringLayout.WEST, winOrLose, 60, SpringLayout.EAST, btnDeal); springLayout.putConstraint(SpringLayout.SOUTH, winOrLose, 0, SpringLayout.SOUTH, btnDeal); frame.getContentPane().add(winOrLose); JButton playAgain = new JButton("Play Again"); playAgain.setEnabled(false); springLayout.putConstraint(SpringLayout.EAST, winOrLose, -45, SpringLayout.WEST, playAgain); springLayout.putConstraint(SpringLayout.NORTH, playAgain, 0, SpringLayout.NORTH, btnDeal); springLayout.putConstraint(SpringLayout.WEST, playAgain, 202, SpringLayout.EAST, btnDeal); frame.getContentPane().add(playAgain); btnDeal.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deck.clear(); d1.createDeck(deck); d1.shuffle(deck); Card temp = deck.remove(0); if(temp.getcVal().getVal() == 11){ playerAce = true; } playerSlot1.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); temp = deck.remove(0); if(temp.getcVal().getVal() == 11){ playerAce = true; } playerSlot2.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); temp = deck.remove(0); if(temp.getcVal().getVal() == 11){ dealerAce = true; } dealerSlot1.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); dealerTotalPoints += temp.getcVal().getVal(); dealerTotal.setText("" + dealerTotalPoints); dealerSecondCard = deck.remove(0); if(dealerSecondCard.getcVal().getVal() == 11){ dealerAce = true; } dealerTotalPoints += dealerSecondCard.getcVal().getVal(); if(playerTotalPoints == 22){ playerTotalPoints = 12; } playerTotal.setText("" + playerTotalPoints); btnDeal.setEnabled(false); hitButton.setEnabled(true); stayButton.setEnabled(true); } }); hitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Card temp = deck.remove(0); if(temp.getcVal().getVal() == 11){ playerAce = true; } if(cardNumber > 5){ cardNumber = 1; } if(cardNumber == 1){ playerSlot1.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); playerTotal.setText("" + playerTotalPoints); } if(cardNumber == 2){ playerSlot2.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); playerTotal.setText("" + playerTotalPoints); } if(cardNumber == 3){ playerSlot3.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); playerTotal.setText("" + playerTotalPoints); } if(cardNumber == 4){ playerSlot4.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); playerTotal.setText("" + playerTotalPoints); } if(cardNumber == 5){ playerSlot5.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); playerTotalPoints += temp.getcVal().getVal(); playerTotal.setText("" + playerTotalPoints); } if(playerTotalPoints > 21){ if(!playerAce){ winOrLose.setText("YOU LOSE"); hitButton.setEnabled(false); stayButton.setEnabled(false); playAgain.setEnabled(true); } else{ playerTotalPoints -= 10; playerTotal.setText("" + playerTotalPoints); playerAce = false; } } cardNumber++; } }); stayButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dealerSlot2.setText(dealerSecondCard.getcVal() + "\n of \n" + dealerSecondCard.getSuit()); dealerTotal.setText("" + dealerTotalPoints); cardNumber = 3; while(dealerTotalPoints < 17){ Card temp = deck.remove(0); if(temp.getcVal().getVal() == 11){ dealerAce = true; } if(cardNumber > 5){ cardNumber = 1; } if(cardNumber == 1){ dealerSlot1.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); dealerTotalPoints += temp.getcVal().getVal(); dealerTotal.setText("" + dealerTotalPoints); } if(cardNumber == 2){ dealerSlot2.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); dealerTotalPoints += temp.getcVal().getVal(); dealerTotal.setText("" + dealerTotalPoints); } if(cardNumber == 3){ dealerSlot3.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); dealerTotalPoints += temp.getcVal().getVal(); dealerTotal.setText("" + dealerTotalPoints); } if(cardNumber == 4){ dealerSlot4.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); dealerTotalPoints += temp.getcVal().getVal(); dealerTotal.setText("" + dealerTotalPoints); } if(cardNumber == 5){ dealerSlot5.setText(temp.getcVal() + "\n of \n" + temp.getSuit()); dealerTotalPoints += temp.getcVal().getVal(); dealerTotal.setText("" + dealerTotalPoints); } if(dealerTotalPoints > 21 && dealerAce == true){ dealerTotalPoints -= 10; dealerAce = false; } cardNumber++; } if(playerTotalPoints > dealerTotalPoints){ winOrLose.setText("YOU WIN"); } else if(playerTotalPoints < dealerTotalPoints){ if (dealerTotalPoints <= 21){ winOrLose.setText("YOU LOSE"); } else{ winOrLose.setText("YOU WIN"); } } else{ winOrLose.setText("DRAW"); } playAgain.setEnabled(true); hitButton.setEnabled(false); stayButton.setEnabled(false); } }); playAgain.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnDeal.setEnabled(true); playerSlot1.setText(""); playerSlot2.setText(""); playerSlot3.setText(""); playerSlot4.setText(""); playerSlot5.setText(""); dealerSlot1.setText(""); dealerSlot2.setText(""); dealerSlot3.setText(""); dealerSlot4.setText(""); dealerSlot5.setText(""); playerTotalPoints = 0; dealerTotalPoints = 0; playerTotal.setText("0"); dealerTotal.setText("0"); cardNumber = 3; winOrLose.setText(""); playAgain.setEnabled(false); } }); } }
true
5a6ac15e5559889b30ebfcd9afdcf52bd3bce02b
Java
volka-java/java-test
/src/main/java/ru/itvitality/sbrf/cu/jfs/example2/datasourceCalculator/DataProvider.java
UTF-8
165
2.109375
2
[]
no_license
package ru.itvitality.sbrf.cu.jfs.example2.datasourceCalculator; public interface DataProvider { int getDataInteger(); double getDataDouble( int seed ); }
true
eaa9c6ec71bdb6d353faf1da08126141d6f0a295
Java
Year4000/Modules
/bungee/ramtweaks/src/main/java/net/year4000/ramtweaks/RamTweaks.java
UTF-8
797
2.109375
2
[]
no_license
/* * Copyright 2015 Year4000. All Rights Reserved. */ package net.year4000.ramtweaks; import lombok.Getter; import net.md_5.bungee.api.scheduler.ScheduledTask; import net.year4000.ducktape.bungee.module.BungeeModule; import net.year4000.ducktape.module.ModuleInfo; @ModuleInfo( name = "RamTweaks", version = "1.5", description = "Improve BungeeCord with a Module", authors = {"Year4000"} ) public class RamTweaks extends BungeeModule { @Getter private static RamTweaks inst; private ScheduledTask restartClock; public void load() { inst = this; } public void enable() { restartClock = new RestartClock().getTask(); registerCommand(RamCommands.class); } public void disable() { restartClock.cancel(); } }
true
feba8b57be33d3b6c814cb229c37e320930294c5
Java
cs13b1043/SWE-Project
/JFLAP 8.0/src/model/algorithms/testinput/parse/lr/rules/ReduceRule.java
UTF-8
631
2.34375
2
[]
no_license
package model.algorithms.testinput.parse.lr.rules; import model.algorithms.testinput.parse.lr.SLR1Production; public class ReduceRule extends SLR1rule { private int myProductionIndex; public ReduceRule(int productionIndex) { myProductionIndex = productionIndex; } @Override public String getDescriptionName() { return "Reduce Rule"; } @Override public String getDescription() { // TODO Auto-generated method stub return null; } @Override public String toString() { return "r" + myProductionIndex; } public int getProductionIndex() { return myProductionIndex; } }
true
258f98ee691d0a5338ec2f5c26c56fd7f0f06739
Java
vstorm83/DVDStore
/DVDStoreDesktop/src/net/homeip/dvdstore/dialog/ActorDialog.java
UTF-8
23,185
2.046875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * ActorDialog.java * * Created on Mar 3, 2010, 3:06:44 PM */ package net.homeip.dvdstore.dialog; // <editor-fold defaultstate="collapsed" desc="import"> import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.RowSorterEvent; import javax.swing.event.RowSorterListener; import net.homeip.dvdstore.ApplicationContextUtil; import net.homeip.dvdstore.listener.ActorDialogListener; import net.homeip.dvdstore.listener.ResultRetrievedListener; import net.homeip.dvdstore.listener.event.DataChangedEvent; import net.homeip.dvdstore.listener.event.DataChangingEvent; import net.homeip.dvdstore.listener.event.ResultRetrievedEvent; import net.homeip.dvdstore.model.DataChangingModel; import net.homeip.dvdstore.model.LoadDataModel; import net.homeip.dvdstore.pojo.webservice.vo.ActorVO; import net.homeip.dvdstore.swing.ActorTableModel; import net.homeip.dvdstore.swing.renderer.DSTableCellRenderer; import net.homeip.dvdstore.util.TextUtil;// </editor-fold> /** * * @author VU VIET PHUONG */ public class ActorDialog extends javax.swing.JDialog { private ActorTableModel actorTableModel; private LoadDataModel<List<ActorVO>> actorListModel; private DataChangingModel changingModel; private ActorDialogListener actorDialogListener; private String lastTxtActorNameText; private List<Long> lastTblActorSelectedId; private List lastSortKeys; /** Creates new form ActorDialog */ public ActorDialog(java.awt.Frame parent) { super(parent, true); initComponents(); btnChooseActors.setVisible(false); setControlStatus(DISABLE_ALL); setupActorTable(); prepareLoadData(); prepareChangeData(); actorDialogListener = (ActorDialogListener) ApplicationContextUtil.getApplicationContext().getBean( "actorDialogListener"); addWindowListener(actorDialogListener); } private void onChanging(ResultRetrievedEvent evt) { String errorMsg = null; switch (changingModel.getStatus()) { case DataChangingModel.OK: dispatchChangedEvent(); JOptionPane.showMessageDialog(this, "Thao tác thành công"); return; case DataChangingModel.DUPLICATE: errorMsg = "Trùng dữ liệu"; break; case DataChangingModel.VALIDATE_FAIL: errorMsg = "Tên diễn viên từ 1 đến 50 ký tự"; break; case DataChangingModel.SERVER_CONNECTION_ERROR: errorMsg = "Lỗi kết nối Server"; break; case DataChangingModel.SERVER_ERROR: errorMsg = "Lỗi Server"; break; } setControlStatus(LAST_STATE); JOptionPane.showMessageDialog(this, errorMsg); } private void onActorListRetrieved(ResultRetrievedEvent evt) { String errorMsg = null; switch (actorListModel.getStatus()) { case LoadDataModel.OK: actorTableModel.setRowData(actorListModel.getData()); break; case LoadDataModel.SERVER_CONNECTION_ERROR: errorMsg = "Không kết nối được với Server"; break; default: errorMsg = "Lỗi Server"; } setControlStatus(LAST_STATE); preChooseActor(); if (errorMsg != null) { JOptionPane.showMessageDialog(this, errorMsg); } } private void prepareLoadData() { actorListModel = new LoadDataModel<List<ActorVO>>(); actorListModel.addResultRetrievedListener(new ResultRetrievedListener() { public void onResultRetrieved(ResultRetrievedEvent evt) { onActorListRetrieved(evt); } }); } private void prepareChangeData() { changingModel = new DataChangingModel(); changingModel.addResultRetrievedListener(new ResultRetrievedListener() { public void onResultRetrieved(ResultRetrievedEvent evt) { onChanging(evt); } }); } // <editor-fold defaultstate="collapsed" desc="setControlStatus"> private final int DISABLE_ALL = 0; private final int ADD_NEW = 1; private final int UPDATE_DELETE = 2; private final int DELETE = 3; private final int LAST_STATE = 4; private void setControlStatus(int controlStatus) { switch (controlStatus) { case DISABLE_ALL: saveState(); tblActor.setEnabled(false); txtActorName.setEnabled(false); btnAddActor.setEnabled(false); btnDeleteActor.setEnabled(false); btnModifyActor.setEnabled(false); break; case ADD_NEW: tblActor.setEnabled(true); txtActorName.setEnabled(true); txtActorName.setText(""); lblActorId.setText("Thêm mới"); btnAddActor.setEnabled(true); btnAddActor.setText("Đồng ý thêm"); btnDeleteActor.setEnabled(false); btnModifyActor.setEnabled(false); tblActor.clearSelection(); break; case UPDATE_DELETE: tblActor.setEnabled(true); txtActorName.setEnabled(true); btnAddActor.setEnabled(true); btnAddActor.setText("Thêm mới"); btnDeleteActor.setEnabled(true); btnModifyActor.setEnabled(true); break; case DELETE: tblActor.setEnabled(true); txtActorName.setEnabled(false); txtActorName.setText(""); lblActorId.setText(""); btnAddActor.setEnabled(true); btnAddActor.setText("Thêm mới"); btnDeleteActor.setEnabled(true); btnModifyActor.setEnabled(false); break; default: restoreState(); } }// </editor-fold> // <editor-fold defaultstate="collapsed" desc="setupActorTable"> private void setupActorTable() { actorTableModel = new ActorTableModel(); tblActor.setModel(actorTableModel); tblActor.getColumnModel().getColumn(0).setMaxWidth(100); tblActor.setRowHeight(20); DSTableCellRenderer cellRenderer = new DSTableCellRenderer(); tblActor.setDefaultRenderer(Long.class, cellRenderer); tblActor.setDefaultRenderer(String.class, cellRenderer); tblActor.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); tblActor.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } int[] selectedIdx = tblActor.getSelectedRows(); if (selectedIdx.length == 1) { lblActorId.setText(String.valueOf(tblActor.getValueAt( selectedIdx[0], 0))); txtActorName.setText((String) tblActor.getValueAt( selectedIdx[0], 1)); ActorDialog.this.setControlStatus(UPDATE_DELETE); } else if (selectedIdx.length > 1) { ActorDialog.this.setControlStatus(DELETE); } else if (selectedIdx.length == 0) { ActorDialog.this.setControlStatus(ADD_NEW); } } }); tblActor.getRowSorter().addRowSorterListener(new RowSorterListener() { public void sorterChanged(RowSorterEvent e) { if (e.getType() == RowSorterEvent.Type.SORT_ORDER_CHANGED) { lastSortKeys = e.getSource().getSortKeys(); } } }); }// </editor-fold> public LoadDataModel<List<ActorVO>> getActorListModel() { return actorListModel; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; javax.swing.JPanel jPanel2 = new javax.swing.JPanel(); javax.swing.JLabel lbItem = new javax.swing.JLabel(); txtActorName = new javax.swing.JTextField(); javax.swing.JPanel jPanel3 = new javax.swing.JPanel(); btnModifyActor = new javax.swing.JButton(); btnDeleteActor = new javax.swing.JButton(); btnAddActor = new javax.swing.JButton(); javax.swing.JLabel jLabel1 = new javax.swing.JLabel(); lblActorId = new javax.swing.JLabel(); javax.swing.JLabel jLabel3 = new javax.swing.JLabel(); scrollPaneActor = new javax.swing.JScrollPane(); tblActor = new javax.swing.JTable(); btnChooseActors = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Quản lý diễn viên"); setResizable(false); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Quản lý diễn viên")); lbItem.setText("Diễn viên:"); jPanel3.setLayout(new java.awt.GridBagLayout()); btnModifyActor.setText("Sửa"); btnModifyActor.setToolTipText("Chọn danh sách để sửa"); btnModifyActor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnModifyActorActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); jPanel3.add(btnModifyActor, gridBagConstraints); btnDeleteActor.setText("Xóa"); btnDeleteActor.setToolTipText("Chọn danh sách để xóa"); btnDeleteActor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteActorActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); jPanel3.add(btnDeleteActor, gridBagConstraints); btnAddActor.setText("Đồng ý thêm"); btnAddActor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddActorActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); jPanel3.add(btnAddActor, gridBagConstraints); jLabel1.setText("Mã:"); lblActorId.setText("Thêm mới"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(48, 48, 48) .addComponent(lblActorId)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(lbItem) .addGap(18, 18, 18) .addComponent(txtActorName, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(41, 41, 41)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblActorId) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtActorName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbItem)) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27)) ); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18)); jLabel3.setForeground(new java.awt.Color(0, 153, 204)); jLabel3.setText("Danh sách diễn viên"); tblActor.setAutoCreateRowSorter(true); tblActor.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tblActor.setFillsViewportHeight(true); tblActor.getTableHeader().setReorderingAllowed(false); scrollPaneActor.setViewportView(tblActor); btnChooseActors.setText("Chọn"); btnChooseActors.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnChooseActorsActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(79, 79, 79) .addComponent(jLabel3)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(271, Short.MAX_VALUE) .addComponent(btnChooseActors)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(scrollPaneActor, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(btnChooseActors) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(scrollPaneActor, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnModifyActorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModifyActorActionPerformed // TODO add your handling code here: dispatchChangingEvent(DataChangingEvent.MODIFY); }//GEN-LAST:event_btnModifyActorActionPerformed private void btnDeleteActorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActorActionPerformed // TODO add your handling code here: if (JOptionPane.showConfirmDialog(this, "Xóa diễn viên ?", "Xóa", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { dispatchChangingEvent(DataChangingEvent.DELETE); } }//GEN-LAST:event_btnDeleteActorActionPerformed private void btnAddActorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActorActionPerformed // TODO add your handling code here: if (btnAddActor.getText().equals("Thêm mới")) { setControlStatus(ADD_NEW); } else { dispatchChangingEvent(DataChangingEvent.ADD); } }//GEN-LAST:event_btnAddActorActionPerformed // <editor-fold defaultstate="collapsed" desc="chooseActors"> private int chooseActorsAction = DIALOG_CLOSE; private List<ActorVO> choosenActorVOs; private List<ActorVO> preChoosenActorVOs; public static final int DIALOG_CLOSE = 0; public static final int DIALOG_OK = 1; public List<ActorVO> getChoosenActorVOs() { return choosenActorVOs; } public int showActorDialog(List<ActorVO> actorVOs) { if (actorVOs != null) { preChoosenActorVOs = actorVOs; } btnChooseActors.setVisible(true); setVisible(true); return chooseActorsAction; }// </editor-fold> private void btnChooseActorsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseActorsActionPerformed // TODO add your handling code here: choosenActorVOs = new ArrayList<ActorVO>(tblActor.getSelectedRows().length); ActorVO actorVO; for (int idx : tblActor.getSelectedRows()) { actorVO = new ActorVO(); actorVO.setActorId((Long) tblActor.getValueAt(idx, 0)); actorVO.setActorName((String) tblActor.getValueAt(idx, 1)); choosenActorVOs.add(actorVO); } chooseActorsAction = DIALOG_OK; dispose(); }//GEN-LAST:event_btnChooseActorsActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddActor; private javax.swing.JButton btnChooseActors; private javax.swing.JButton btnDeleteActor; private javax.swing.JButton btnModifyActor; private javax.swing.JLabel lblActorId; private javax.swing.JScrollPane scrollPaneActor; private javax.swing.JTable tblActor; private javax.swing.JTextField txtActorName; // End of variables declaration//GEN-END:variables private void dispatchChangingEvent(int action) { setControlStatus(DISABLE_ALL); DataChangingEvent dataChangingEvent = new DataChangingEvent(this); dataChangingEvent.setAction(action); dataChangingEvent.setDataChangingModel(changingModel); Object param; switch (action) { case DataChangingEvent.MODIFY: ActorVO vo = new ActorVO(); vo.setActorId(Long.valueOf(lblActorId.getText())); vo.setActorName(TextUtil.normalize(txtActorName.getText())); param = vo; break; case DataChangingEvent.DELETE: param = getSelectedActorId(); break; default: param = new ActorVO(); ((ActorVO) param).setActorName(TextUtil.normalize(txtActorName.getText())); } dataChangingEvent.setParam(param); actorDialogListener.onDataChanging(dataChangingEvent); } private List<Long> getSelectedActorId() { List<Long> actorIdList = new ArrayList<Long>(); for (int row : tblActor.getSelectedRows()) { actorIdList.add((Long) tblActor.getValueAt(row, 0)); } return actorIdList; } private void dispatchChangedEvent() { actorDialogListener.onDataChanged(new DataChangedEvent(this)); } private void saveState() { lastTblActorSelectedId = getSelectedActorId(); lastSortKeys = tblActor.getRowSorter().getSortKeys(); lastTxtActorNameText = txtActorName.getText(); } private void restoreState() { tblActor.setEnabled(true); tblActor.clearSelection(); tblActor.getRowSorter().setSortKeys(lastSortKeys); for (Long id : lastTblActorSelectedId) { for (int row = 0; row < tblActor.getRowCount(); row++) { if (id.longValue() == ((Long) tblActor.getValueAt(row, 0)).longValue()) { tblActor.addRowSelectionInterval(row, row); } } } if (tblActor.getSelectedRow() == -1) { setControlStatus(ADD_NEW); } txtActorName.setText(lastTxtActorNameText); } private void preChooseActor() { if (preChoosenActorVOs != null) { for (ActorVO actorVO : preChoosenActorVOs) { for (int row = 0; row < tblActor.getRowCount(); row++) { if (actorVO.getActorId().longValue() == ((Long) tblActor.getValueAt(row, 0)).longValue()) { tblActor.addRowSelectionInterval(row, row); } } } } } }
true
58d4f4972d24b5047b9497cdf92480965451795e
Java
Anystat/anycipeRest
/src/main/java/ru/anystat/anycipe/rest/controllers/ErrorsController.java
UTF-8
777
1.984375
2
[]
no_license
package ru.anystat.anycipe.rest.controllers; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import ru.anystat.anycipe.rest.utils.JsonUtils; /** * Created by ustits on 20.11.16. */ @RestController @RequestMapping(value = "/error") public class ErrorsController implements ErrorController { @RequestMapping public ResponseEntity handleConflict() { return JsonUtils.getErrorEntity(404, "Nothing to show you", HttpStatus.NOT_FOUND); } @Override public String getErrorPath() { return "/error"; } }
true
6cf73bf213235f5f6351258cc00fc9420251de42
Java
EstebanDalelR/tinderAnalysis
/apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/snapchat/kit/sdk/core/security/C7925b.java
UTF-8
770
1.78125
2
[]
no_license
package com.snapchat.kit.sdk.core.security; import android.content.Context; import dagger.internal.Factory; import javax.inject.Provider; /* renamed from: com.snapchat.kit.sdk.core.security.b */ public final class C7925b implements Factory<Fingerprint> { /* renamed from: a */ private final Provider<Context> f28511a; public /* synthetic */ Object get() { return m33768a(); } public C7925b(Provider<Context> provider) { this.f28511a = provider; } /* renamed from: a */ public Fingerprint m33768a() { return new Fingerprint((Context) this.f28511a.get()); } /* renamed from: a */ public static Factory<Fingerprint> m33767a(Provider<Context> provider) { return new C7925b(provider); } }
true
618fbae4054b3f47b7819f1d1b63a1c757f7c8df
Java
Siiruo-Wong/w-scheduler
/wscheduler-client/src/main/java/com/siiruo/wscheduler/client/bean/SingleExecutor.java
UTF-8
3,537
2.453125
2
[]
no_license
package com.siiruo.wscheduler.client.bean; import com.siiruo.wscheduler.core.bean.LifecycleExecutor; import com.siiruo.wscheduler.core.bean.ExecuteParameter; import com.siiruo.wscheduler.core.exception.WSchedulerExecutingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by siiruo wong on 2019/12/29. */ public class SingleExecutor implements LifecycleExecutor { private Object target; private String name; private Method execute; private Method before; private Method after; private Method init; private Method destroy; private volatile boolean initialized; private volatile boolean destroyed; public SingleExecutor() { } public SingleExecutor(Object target, String name, Method execute) { this.target = target; this.name = name; this.execute = execute; } public SingleExecutor(Object target, String name, Method execute, Method before, Method after, Method init, Method destroy) { this.target = target; this.name = name; this.execute = execute; this.before = before; this.after = after; this.init = init; this.destroy = destroy; } private synchronized void internalExecute(ExecuteParameter parameter) throws WSchedulerExecutingException { if (!initialized) { init(); } try { if (before!=null) { before.setAccessible(true); before.invoke(target); } execute.setAccessible(true); execute.invoke(target,parameter); } catch (IllegalAccessException e) { throw new WSchedulerExecutingException(e); } catch (InvocationTargetException e) { throw new WSchedulerExecutingException(e); }finally { if (after!=null) { try { after.setAccessible(true); after.invoke(target); } catch (IllegalAccessException e) { throw new WSchedulerExecutingException(e); } catch (InvocationTargetException e) { throw new WSchedulerExecutingException(e); } } } } @Override public void execute(ExecuteParameter parameter) throws WSchedulerExecutingException{ internalExecute(parameter); } @Override public void init() { if (init==null|| initialized) { return; } try { init.setAccessible(true); init.invoke(target); initialized =true; } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } @Override public void destroy() { if (destroy==null||destroyed) { return; } try { destroy.setAccessible(true); destroy.invoke(target); destroyed=true; } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } public Object getTarget() { return target; } public String getName() { return name; } public Method getExecute() { return execute; } public Method getBefore() { return before; } public Method getAfter() { return after; } public Method getInit() { return init; } public Method getDestroy() { return destroy; } }
true
6feabbe28e3dd235137ba96bf6773eda91cebf87
Java
MyhreAndersen/Simula15Loom
/Simula15Loom/src/simulaTestBatch/simtst106$.java
UTF-8
1,564
1.882813
2
[]
no_license
package simulaTestBatch; // Simula-2.0 Compiled at Sun Jan 31 10:26:03 CET 2021 import simula.runtime.*; @SuppressWarnings("unchecked") public final class simtst106$ extends BASICIO$ { boolean found_error=false; final TXT$ fileName=(TXT$)(new TXT$("C:/GitHub/SimulaCompiler/Simula/src/testing/batch/files/data96")); InFile$ inspect$20$0=null; public simtst106$(RTObject$ staticLink) { super(staticLink); BBLK(); BPRG("simtst106$"); } public RTObject$ STM$() { sysout().outtext(new TXT$("--- START Simula a.s. TEST 96")); ; sysout().outimage(); ; sysout().outtext(new TXT$(" Test of Simulation - reads from infile \"data96\".")); ; sysout().outimage(); ; sysout().outimage(); ; { inspect$20$0=new InFile$(CTX$,fileName).STM$(); if(inspect$20$0!=null) new simtst106$PBLK76((CUR$)).START$(); } ; sysout().outtext(new TXT$("--- END Simula a.s. TEST 96")); ; if(VALUE$((!(found_error)))) { sysout().outtext(new TXT$(" (NO ERRORS FOUND)")); } ; sysout().outimage(); ; EBLK(); return(this); } public static void main(String[] args) { RT.setRuntimeOptions(args); new simtst106$(CTX$).STM$(); } public static PROGINFO$ INFO$=new PROGINFO$("simtst106.sim","SimulaProgram simtst106$",1,12,8,14,10,21,18,16,23,17,26,18,31,20,35,242,39,243,42,244,47,245,57,247); }
true
acf48e382b8f1633dcf29b5163415e2313ec037d
Java
msankrish92/LeafTapsPageObjectModelCucumber
/ServiceNowCuc/src/main/java/org/servicenow/pages/ServiceNowLoginPage.java
UTF-8
886
2.21875
2
[]
no_license
package org.servicenow.pages; import org.servicenow.api.ServiceNowProjectSpecificMethods; import org.testng.annotations.Test; import cucumber.api.java.en.Given; public class ServiceNowLoginPage extends ServiceNowProjectSpecificMethods { @Given("User enters a username") public ServiceNowLoginPage enterUserName() { driver.switchTo().frame(0); driver.findElementById(prop.getProperty("login.username.id")).sendKeys("admin"); return this; } @Given("User enters a password") public ServiceNowLoginPage enterPassword() { driver.findElementById(prop.getProperty("login.password.id")).sendKeys("Feb@1234"); return this; } @Given("User Clicks Login Button") public SystemAdministrationPage clickLoginButton() { driver.findElementById(prop.getProperty("login.loginButton.id")).click(); return new SystemAdministrationPage(); } }
true
a2176ecc87cee490f3c23190e0a643f4fbb8b7b9
Java
evencity/oddm
/oddm-application/src/main/java/com/apical/oddm/application/sale/SalePoListServiceImpl.java
UTF-8
657
1.90625
2
[]
no_license
package com.apical.oddm.application.sale; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.apical.oddm.application.base.BaseServiceImpl; import com.apical.oddm.core.dao.sale.SalePoListDaoI; import com.apical.oddm.core.model.sale.SalePoList; @Service("salePoListService") public class SalePoListServiceImpl extends BaseServiceImpl<SalePoList> implements SalePoListServiceI { @Autowired private SalePoListDaoI salePoListDaoI; @Override public List<SalePoList> getByPoId(int poId) { return salePoListDaoI.getByPoId(poId); } }
true
802ad4715ca00c0bf2041c980819f4a21c314ed2
Java
mytliulei/RED
/src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/ide/eclipse/main/plugin/tableeditor/SuiteFileMarkersContainerMock.java
UTF-8
1,166
2
2
[ "Apache-2.0" ]
permissive
package org.robotframework.ide.eclipse.main.plugin.tableeditor; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.robotframework.ide.eclipse.main.plugin.model.RobotFileInternalElement; import org.robotframework.ide.eclipse.main.plugin.project.build.causes.ProblemCategory.Severity; class SuiteFileMarkersContainerMock implements SuiteFileMarkersContainer { private final Map<RobotFileInternalElement, Severity> markers = new HashMap<>(); @Override public Optional<Severity> getHighestSeverityMarkerFor(final Optional<? extends RobotFileInternalElement> element) { if (element.isPresent() && markers.containsKey(element.get())) { return Optional.of(markers.get(element.get())); } return Optional.empty(); } @Override public List<String> getMarkersMessagesFor(final Optional<? extends RobotFileInternalElement> element) { return null; } public void registerMarker(final RobotFileInternalElement element, final Severity highestSeverity) { markers.put(element, highestSeverity); } }
true
729daafec2166a0f105f6ca79160cfbbd070d393
Java
nagillavenkatesh/javaslang-jackson
/src/test/java/javaslang/jackson/datatype/map/MapTest.java
UTF-8
6,937
2.046875
2
[ "Apache-2.0" ]
permissive
package javaslang.jackson.datatype.map; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import javaslang.Tuple; import javaslang.collection.HashMap; import javaslang.collection.List; import javaslang.collection.Map; import javaslang.control.Option; import javaslang.jackson.datatype.BaseTest; import org.junit.Assert; import org.junit.Test; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.IOException; public abstract class MapTest extends BaseTest { abstract Class<?> clz(); abstract <K, V> Map<K, V> emptyMap(); protected abstract TypeReference<? extends Map<String, Option<Integer>>> typeReferenceWithOption(); @Test public void test1() throws IOException { Map<Object, Object> javaslangObject = emptyMap().put("1", 2); java.util.Map<Object, Object> javaObject = new java.util.HashMap<>(); javaObject.put("1", 2); String json = mapper().writer().writeValueAsString(javaslangObject); Assert.assertEquals(genJsonMap(javaObject), json); Map<?, ?> restored = (Map<?, ?>) mapper().readValue(json, clz()); Assert.assertEquals(restored, javaslangObject); } @Test public void test2() throws IOException { ObjectMapper mapper = mapper().addMixIn(clz(), WrapperObject.class); Map<?, ?> src = emptyMap().put("1", 2); String plainJson = mapper().writeValueAsString(src); String wrappedJson = mapper.writeValueAsString(src); Assert.assertEquals(wrappedJson, wrapToObject(clz().getName(), plainJson)); Map<?, ?> restored = (Map<?, ?>) mapper.readValue(wrappedJson, clz()); Assert.assertEquals(src, restored); } @Test public void test3() throws IOException { ObjectMapper mapper = mapper().addMixIn(clz(), WrapperArray.class); Map<?, ?> src = emptyMap().put("1", 2); String plainJson = mapper().writeValueAsString(src); String wrappedJson = mapper.writeValueAsString(src); Assert.assertEquals(wrappedJson, wrapToArray(clz().getName(), plainJson)); Map<?, ?> restored = (Map<?, ?>) mapper.readValue(wrappedJson, clz()); Assert.assertEquals(src, restored); } @Test(expected = JsonParseException.class) public void test4() throws IOException { mapper().readValue("{1: 1}", clz()); } @Test public void testWithOption() throws Exception { verifySerialization(typeReferenceWithOption(), List.of( Tuple.of(emptyMap().put("1", Option.some(1)), genJsonMap(HashMap.of("1", 1).toJavaMap())), Tuple.of(emptyMap().put("1", Option.none()), genJsonMap(HashMap.of("1", null).toJavaMap())) )); } public static class Parameterized<T1, T2> { public Map<T1, T2> value; public Parameterized() {} public Parameterized(Map<T1, T2> value) { this.value = value; } } @Test @SuppressWarnings("unchecked") public void testWrappedParameterizedSome() throws IOException { String expected = "{\"value\":{\"1\":2}}"; Parameterized<Integer, Integer> object = new Parameterized<>(this.<Integer, Integer>emptyMap().put(1, 2)); Assert.assertEquals(expected, mapper().writeValueAsString(object)); Parameterized<Integer, Integer> restored = mapper().readValue(expected, new TypeReference<Parameterized<Integer, Integer>>() {}); Assert.assertEquals(restored.value.get(1).get(), (Integer) 2); } @XmlRootElement(name = "xmlSerialize") private static class JaxbXmlSerializeJavaUtil { @XmlElement(name = "transitType") public java.util.Map<String, String> transitTypes; public JaxbXmlSerializeJavaUtil init(java.util.Map<String, String> javaSet) { transitTypes = javaSet; return this; } } @XmlRootElement(name = "xmlSerialize") private static class JaxbXmlSerializeJavaslang { @XmlElement(name = "transitType") public Map<String, String> transitTypes; public JaxbXmlSerializeJavaslang init(Map<String, String> javaSet) { transitTypes = javaSet; return this; } } // @Test public void testJaxbXmlSerialization() throws IOException { java.util.Map<String, String> javaInit = new java.util.HashMap<>(); javaInit.put("key1", "1"); javaInit.put("key2", "2"); Map<String, String> slangInit = this.<String, String>emptyMap().put("key1", "1").put("key2", "2"); ObjectMapper mapper = xmlMapperJaxb(); String javaJson = mapper.writeValueAsString(new JaxbXmlSerializeJavaUtil().init(javaInit)); String slangJson = mapper.writeValueAsString(new JaxbXmlSerializeJavaslang().init(slangInit)); Assert.assertEquals(javaJson, slangJson); JaxbXmlSerializeJavaslang restored = mapper.readValue(slangJson, JaxbXmlSerializeJavaslang.class); Assert.assertEquals(restored.transitTypes.get("key1").get(), "1"); Assert.assertEquals(restored.transitTypes.get("key2").get(), "2"); } @JacksonXmlRootElement(localName = "xmlSerialize") private static class XmlSerializeJavaUtil { @JsonProperty("transitType") public java.util.Map<String, String> transitTypes; public XmlSerializeJavaUtil init(java.util.Map<String, String> javaSet) { transitTypes = javaSet; return this; } } @JacksonXmlRootElement(localName = "xmlSerialize") private static class XmlSerializeJavaslang { @JsonProperty("transitType") public Map<String, String> transitTypes; public XmlSerializeJavaslang init(Map<String, String> javaSet) { transitTypes = javaSet; return this; } } // @Test public void testXmlSerialization() throws IOException { java.util.Map<String, String> javaInit = new java.util.HashMap<>(); javaInit.put("key1", "1"); javaInit.put("key2", "2"); Map<String, String> slangInit = this.<String, String>emptyMap().put("key1", "1").put("key2", "2"); ObjectMapper mapper = xmlMapper(); String javaJson = mapper.writeValueAsString(new XmlSerializeJavaUtil().init(javaInit)); String slangJson = mapper.writeValueAsString(new XmlSerializeJavaslang().init(slangInit)); Assert.assertEquals(javaJson, slangJson); XmlSerializeJavaslang restored = mapper.readValue(slangJson, XmlSerializeJavaslang.class); Assert.assertEquals(restored.transitTypes.get("key1").get(), "1"); Assert.assertEquals(restored.transitTypes.get("key2").get(), "2"); } }
true
fed278c65b67937418f0286818d01a17c65a2224
Java
PrabhakarGaddipati/Learn_RestAssuredAPI-API_TestingFramework
/src/test/java/com/learning/utilities/DataUtil.java
UTF-8
1,877
2.59375
3
[]
no_license
package com.learning.utilities; import java.lang.reflect.Method; import java.util.Hashtable; import org.testng.annotations.DataProvider; import com.learning.setup.stripe.BaseTest_Stripe; public class DataUtil { public static ExcelReader excel = new ExcelReader(Constants.ExcelSheet); /** * (name = "dp", parallel = true) * * name = "dp" - name of the DataProvider * * parallel = true -> Data will run parallely * */ @DataProvider(name = "dp", parallel = true) public Object[][] getData(Method method) { String sheetName = method.getName(); System.out.println("Sheet Name: " + sheetName); // String sheetName = "validateCreateCustomerAPI"; int rows = excel.getRowCount(sheetName); int cols = excel.getColumnCount(sheetName); Object[][] data = new Object[rows - 1][1]; Hashtable<String, String> table = null; for (int rowNum = 2; rowNum <= rows; rowNum++) { // 2 table = new Hashtable<String, String>(); for (int colNum = 0; colNum < cols; colNum++) { // data[0][0] table.put(excel.getCellData(sheetName, colNum, 1), excel.getCellData(sheetName, colNum, rowNum)); data[rowNum - 2][0] = table; } } return data; } public static void main(String[] args) { // String sheetName = m.getName(); String sheetName = "validateCreateCustomerAPI"; int rows = excel.getRowCount(sheetName); int cols = excel.getColumnCount(sheetName); Object[][] data = new Object[rows - 1][1]; Hashtable<String, String> table = null; for (int rowNum = 2; rowNum <= rows; rowNum++) { // 2 table = new Hashtable<String, String>(); for (int colNum = 0; colNum < cols; colNum++) { // data[0][0] table.put(excel.getCellData(sheetName, colNum, 1), excel.getCellData(sheetName, colNum, rowNum)); data[rowNum - 2][0] = table; System.out.println(data[rowNum - 2][0]); } } // return data; } }
true
86f078a7fac6edd32eea12c3dd7253e22b776acf
Java
BedoRachi/eclipse-workspace
/chapter07/src/chapter07_Q/Q4_ArrayList_DogTest.java
UHC
692
3.25
3
[]
no_license
package chapter07_Q; import java.util.ArrayList; public class Q4_ArrayList_DogTest { public static void main(String[] args) { ArrayList<Q4_Array_Dog> dog = new ArrayList<Q4_Array_Dog>(); dog.add(new Q4_Array_Dog("鱸", "")); dog.add(new Q4_Array_Dog("Ȳ", "")); dog.add(new Q4_Array_Dog("汸", "")); dog.add(new Q4_Array_Dog("", "찳")); dog.add(new Q4_Array_Dog("һ", "찳")); for (int i = 0; i < dog.size(); i++) { System.out.println(dog.get(i).showDogInfo()); } System.out.println("##############################"); for(Q4_Array_Dog d : dog) { System.out.println(d.showDogInfo()); } } }
true
77e06745e52b06a212d711b9fae51b661aae3789
Java
Era-T/KNK20_21_Gr5
/stage3admin.java
UTF-8
11,952
2.046875
2
[]
no_license
package knk; import java.sql.*; import java.util.List; import com.mysql.cj.xdevapi.Table; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class stage3admin { private static Stage mainstage; private static Stage primaryStage = new Stage(); // Pjesa per tekst private static TextField idF = new TextField(); private static TextField subjectF = new TextField(); private static TextField ectsF = new TextField(); private static TextField profF = new TextField(); private static TextField assF = new TextField(); private static TextField Ldita = new TextField(); private static TextField Lora = new TextField(); private static TextField Lsalla = new TextField(); private static TextField Udita = new TextField(); private static TextField Uora = new TextField(); private static TextField Usalla = new TextField(); private static TextField nstud = new TextField(); private static TextField departamenti = new TextField(); private static TextField sem = new TextField(); private static TextField grupi = new TextField(); // Buttonat private static Button insertBtn = new Button("Insert"); private static Button logoutBtn = new Button("LogOut"); // Table views @SuppressWarnings("rawtypes") private static TableView OrariTbl = new TableView(); public static void adminStage(Stage stage3admin) { mainstage = stage3admin; // Form pane GridPane formPane = new GridPane(); Label ID = new Label("ID:"); ID.setStyle("-fx-font-size:10;-fx-text-fill: red;-fx-font-weight:bold;"); idF.setStyle("-fx-font-size:10;"); idF.setMaxWidth(1); formPane.add(ID, 0, 0); formPane.add(idF, 1, 0); Label Lenda = new Label("Lenda:"); Lenda.setStyle("-fx-font-size:10;-fx-text-fill: red;-fx-font-weight:bold;"); subjectF.setStyle("-fx-font-size:10;"); subjectF.setMaxWidth(150); formPane.add(Lenda, 0, 1); formPane.add(subjectF, 1, 1); Label Ects = new Label("Ects:"); Ects.setStyle("-fx-font-size:10;-fx-text-fill: red;-fx-font-weight:bold;"); ectsF.setStyle("-fx-font-size:10;"); ectsF.setMaxWidth(40); formPane.add(Ects, 2, 1); formPane.add(ectsF,3 ,1 ); Label Profesori = new Label("Profesori:"); Profesori.setStyle("-fx-font-size:10;-fx-text-fill: blue;-fx-font-weight:bold;"); profF.setStyle("-fx-font-size:10;"); profF.setMaxWidth(150); formPane.add(Profesori, 0, 2); formPane.add(profF,1 ,2 ); Label Asistenti = new Label("Asistenti:"); Asistenti.setStyle("-fx-font-size:10;-fx-text-fill: blue;-fx-font-weight:bold;"); assF.setStyle("-fx-font-size:10;"); assF.setMaxWidth(150); formPane.add(Asistenti, 2, 2); formPane.add(assF,3 ,2 ); Label Ligj = new Label("Ligj/Dita:"); Ligj.setStyle("-fx-font-size:10;-fx-text-fill: pink;-fx-font-weight:bold;"); Ldita.setStyle("-fx-font-size:10;"); Ldita.setMaxWidth(150); formPane.add(Ligj, 0, 3); formPane.add(Ldita,1 ,3 ); Label LigjO = new Label("Ligj/Ora:"); LigjO.setStyle("-fx-font-size:10;-fx-text-fill: pink;-fx-font-weight:bold;"); Lora.setStyle("-fx-font-size:10;"); Lora.setMaxWidth(150); formPane.add(LigjO, 2, 3); formPane.add(Lora,3 ,3 ); Label LigjS = new Label("Ligj/Salla:"); LigjS.setStyle("-fx-font-size:10;-fx-text-fill: pink;-fx-font-weight:bold;"); Lsalla.setStyle("-fx-font-size:10;"); Lsalla.setMaxWidth(150); formPane.add(LigjS, 0, 4); formPane.add(Lsalla,1 ,4 ); Label Usht = new Label("Usht/Dita:"); Usht.setStyle("-fx-font-size:10;-fx-text-fill: green;-fx-font-weight:bold;"); Udita.setStyle("-fx-font-size:10;"); Udita.setMaxWidth(150); formPane.add(Usht, 0, 5); formPane.add(Udita,1 ,5 ); Label UshtO = new Label("Usht/Ora:"); UshtO.setStyle("-fx-font-size:10;-fx-text-fill: green;-fx-font-weight:bold;"); Uora.setStyle("-fx-font-size:10;"); Uora.setMaxWidth(150); formPane.add(UshtO, 2, 5); formPane.add(Uora,3 ,5 ); Label UshtS = new Label("Usht/Salla:"); UshtS.setStyle("-fx-font-size:10;-fx-text-fill: green;-fx-font-weight:bold;"); Usalla.setStyle("-fx-font-size:10;"); Usalla.setMaxWidth(150); formPane.add(UshtS, 0, 6); formPane.add(Usalla,1 ,6 ); formPane.addRow(11, new Label("Niveli stud:"), nstud); formPane.addRow(12, new Label("Departamenti:"), departamenti); formPane.addRow(13, new Label("Semestri:"), sem); formPane.addRow(14, new Label("Grupi:"), grupi); formPane.setHgap(10); formPane.setVgap(5); idF.setDisable(true); // Pjesa e butonave HBox buttonsPane = new HBox(5); buttonsPane.getChildren().addAll(insertBtn, logoutBtn); insertBtn.setStyle("-fx-background-color:#41B3FF;-fx-font-weight:bold;-fx-text-fill: white;"); logoutBtn.setStyle("-fx-background-color:#41B3FF;-fx-font-weight:bold;-fx-text-fill: white;"); insertBtn.setMinWidth(50); logoutBtn.setMinWidth(70); logoutBtn.setOnAction(e ->{ Login l=new Login(); try { stage3admin.close(); l.start(primaryStage); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }); insertBtn.setOnAction(e -> { insertOrari(); }); VBox leftPane = new VBox(100); leftPane.getChildren().addAll(formPane, buttonsPane); @SuppressWarnings("rawtypes") TableColumn teacher = new TableColumn("Mesimdhenesi"); TableColumn ligjeratacol = new TableColumn("Ligjerata"); TableColumn ushtrimecol = new TableColumn("Ushtrime"); // Books table TableColumn<String, Orari> column1 = new TableColumn<>("ID:"); column1.setCellValueFactory(new PropertyValueFactory("id")); column1.setMinWidth(150); TableColumn<String, Orari> column2 = new TableColumn<>("Lendet"); column2.setCellValueFactory(new PropertyValueFactory("titlenda")); column2.setMinWidth(155); TableColumn<String, Orari> column3 = new TableColumn<>("Ects"); column3.setCellValueFactory(new PropertyValueFactory("ects")); column3.setMinWidth(30); TableColumn<String, Orari> column4 = new TableColumn<>("Profesori"); column4.setCellValueFactory(new PropertyValueFactory("profcol")); column4.setMinWidth(140); TableColumn<String, Orari> column5 = new TableColumn<>("Assistenti"); column5.setCellValueFactory(new PropertyValueFactory("asscol")); column5.setMinWidth(100); TableColumn<String, Orari> column6 = new TableColumn<>("Dita"); column6.setCellValueFactory(new PropertyValueFactory("ldita")); column6.setMinWidth(60); TableColumn<String, Orari> column7 = new TableColumn<>("Ora"); column7.setCellValueFactory(new PropertyValueFactory("lora")); column7.setMinWidth(70); TableColumn<String, Orari> column8 = new TableColumn<>("Salla"); column8.setCellValueFactory(new PropertyValueFactory("lsalla")); column8.setMinWidth(60); TableColumn<String, Orari> column9 = new TableColumn<>("Dita"); column9.setCellValueFactory(new PropertyValueFactory("udita")); column9.setMinWidth(70); TableColumn<String, Orari> column10 = new TableColumn<>("Ora"); column10.setCellValueFactory(new PropertyValueFactory("uora")); column10.setMinWidth(60); TableColumn<String, Orari> column11 = new TableColumn<>("Salla"); column11.setCellValueFactory(new PropertyValueFactory("usalla")); column11.setMinWidth(60); teacher.getColumns().addAll(column4,column5); ligjeratacol.getColumns().addAll(column6, column7, column8); ushtrimecol.getColumns().addAll(column9, column10, column11); OrariTbl.getColumns().add(column2); OrariTbl.getColumns().add(column3); OrariTbl.getColumns().add(teacher); OrariTbl.getColumns().add(ligjeratacol); OrariTbl.getColumns().add(ushtrimecol); OrariTbl.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); OrariTbl.setMinWidth(600); OrariTbl.setPrefHeight(200); // Main Pane ku duhet me bo me minus HBox mainPane = new HBox(100); mainPane.getChildren().addAll(leftPane, OrariTbl); mainPane.setPadding(new Insets(10, 10, 10 ,10)); Scene scene = new Scene(mainPane, 1000, 580); scene.getStylesheets().add("style.css"); stage3admin.setTitle("Admin Stage"); stage3admin.setScene(scene); showOrari(); stage3admin.show(); } public static void main(String[] args) { Application.launch(args); } public static void showOrari() { List<Orari> orariL = Orari.getOrari(); ObservableList<Orari> orariList = FXCollections.observableArrayList(); for(int i = 0; i < orariL.size(); i++) { orariList.add(orariL.get(i)); } OrariTbl.setItems(orariList); } public static void insertOrari() { if(Orari.addOrari(subjectF.getText(), Integer.parseInt(ectsF.getText()), profF.getText(), assF.getText(), Ldita.getText(), Lora.getText(), Integer.parseInt(Lsalla.getText()), Udita.getText(), Uora.getText(), Integer.parseInt(Usalla.getText()), nstud.getText(), departamenti.getText(), sem.getText(), grupi.getText() )) { showOrari(); clearOrari(); } } public static void clearOrari() { idF.setText(""); subjectF.setText(""); ectsF.setText(""); profF.setText(""); assF.setText(""); Ldita.setText(""); Lora.setText(""); Lsalla.setText(""); Udita.setText(""); Uora.setText(""); Usalla.setText(""); nstud.setText(""); departamenti.setText(""); sem.setText(""); grupi.setText(""); } public static boolean updateOrari(int id,String titlenda, int ects, String profcol, String asscol, String ldita, String lora, int lsalla, String udita, String uora, int usalla,String nstud, String departamenti, String sem, String grupi) { System.out.println(id); String query = "UPDATE orari SET titlenda=?, ects=?, profcol=?, asscol=?, ldita=?, lora=?, lsalla=?, udita=?, uora=?, usalla=?, nstud=?, departamenti=?, sem=?, grupi=? WHERE id=?"; try { PreparedStatement preparedStatement = DBConnection.getConnection().prepareStatement(query); preparedStatement.setString(1, titlenda); preparedStatement.setInt(2, ects); preparedStatement.setString(3, profcol); preparedStatement.setString(4, asscol); preparedStatement.setString(5, ldita); preparedStatement.setString(6, lora); preparedStatement.setInt(7, lsalla); preparedStatement.setString(8, udita); preparedStatement.setString(9, uora); preparedStatement.setInt(10, usalla); preparedStatement.setString(11, nstud); preparedStatement.setString(12, departamenti); preparedStatement.setString(13, sem); preparedStatement.setString(14, grupi); preparedStatement.setInt(15, id); return (preparedStatement.executeUpdate() > 0); } catch(SQLException ex) { ex.printStackTrace(); return false; } } public static boolean deleteOrari(int id) { String query = "Delete from orari where id=?"; try { PreparedStatement preparedStatement = DBConnection.getConnection().prepareStatement(query); preparedStatement.setInt(1, id); return (preparedStatement.executeUpdate() > 0); } catch(SQLException ex) { ex.printStackTrace(); return false; } } }
true
36ef800147adb6a7f6a87ce1a60ce6e91606f5b3
Java
vedask/exilant-java-dec16
/JavaWorks/src/com/exilant/day6/ThreadSyncTest.java
UTF-8
1,352
3.859375
4
[ "Apache-2.0" ]
permissive
package com.exilant.day6; class Account{ int balance; Account(int balance){ this.balance = balance; } public void withdraw(int amount){ if(amount < balance){ // we have amount and can we withdrawn // for transaction to simulate will we sleep for 1 sec try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } balance = balance - amount; System.out.println("Amt Req : " + amount +" by " + Thread.currentThread().getName() +" Remaining is " + balance); }else{ // no balance System.out.println("Sorry " + Thread.currentThread().getName() +" No Balance for Req Amt " + amount); } } } public class ThreadSyncTest implements Runnable { Account account; int amt; ThreadSyncTest(String name, int amount, Account account){ this.account = account; this.amt = amount; Thread t = new Thread(this, name); // will create a OS level thread and call run method t.start(); } @Override public void run() { synchronized (account) { account.withdraw(amt); } } public static void main(String[] args) { // assuming that this value 1000 will come from DB Account account = new Account(1000); new ThreadSyncTest("Mr. A", 500, account); new ThreadSyncTest("Mr. B", 750, account); } }
true
9076280e6d3a4e8b375cc89428c003584ed7cee4
Java
xlui/DsAlgoDp
/Java/src/design_pattern/structural/decorator/RedShapeDecorator.java
UTF-8
431
3.25
3
[ "MIT" ]
permissive
package design_pattern.structural.decorator; import design_pattern.structural.decorator.shape.Shape; public class RedShapeDecorator extends AbstractShapeDecorator { public RedShapeDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { super.draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape) { System.out.println("Border Color: Red"); } }
true
b59d3e2258181687aa104a0aed22718fccff87a5
Java
vetkolisanket/ds_algo
/java/graphs/trees/leetcode/binary_tree_level_order_traversal.java
UTF-8
2,440
3.90625
4
[]
no_license
/* 102. Binary Tree Level Order Traversal Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 2000]. -1000 <= Node.val <= 1000 */ //A better soln class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList(); dfs(res, root, 0); return res; } private void dfs(List<List<Integer>> list, TreeNode node, int height) { if (node == null) return; if (height == list.size()) { list.add(new LinkedList()); } list.get(height).add(node.val); dfs(list, node.left, height+1); dfs(list, node.right, height+1); } } //My soln /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) return new ArrayList(); List<List<TreeNode>> res = new ArrayList(); List<TreeNode> list = new ArrayList(); list.add(root); res.add(list); bfs(list, res); return createRes(res); } private void bfs(List<TreeNode> list, List<List<TreeNode>> res) { List<TreeNode> temp = new ArrayList(); for (TreeNode node: list) { if (node.left != null) temp.add(node.left); if (node.right != null) temp.add(node.right); } if (!temp.isEmpty()) { res.add(temp); bfs(temp, res); } } private List<List<Integer>> createRes(List<List<TreeNode>> res) { List<List<Integer>> list = new ArrayList(); for (List<TreeNode> nodes: res) { List<Integer> l = new ArrayList(); for (TreeNode node: nodes) { l.add(node.val); } list.add(l); } return list; } }
true
3b6126a9d3025e237e36aa93184fcdb95d61be5b
Java
lhj8770/Pokemon-HUFScampus.ver-
/Pocketmon/src/Pocketmon/Battle.java
UTF-8
12,237
2
2
[]
no_license
package Pocketmon; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.DebugGraphics; public class Battle { //Singleton pattern private static Battle battleInstance; public static int BATTLE_IN = 1; public static int BATTLE_NO = 0; public static int INI_1 =0; public static int INI_2 =1; public static int INI_3 =2; public static int INI_4 =3; public static int START = -2; //playerDoneState にかかわるコンスタント(キャラクターとnpcの行動が決められる) public static int MY_ITEM_PRI =10; public static int MY_CHANGE1_PRI =11; public static int MY_CHANGE2_PRI =12; public static int MY_CHANGE3_PRI = 29; public static int MY_ATTACK_PRI = 13; public static int ENEMY_TURN =14; public static int MY_TURN = 25; //enemy priority 設定コンスタント public static int ENEMY_ATTACK_PRI =15; public static int ENEMY_ITEM1_PRI =16; public static int ENEMY_ITEM2_PRI =17; public static int ENEMY_CHANGE1_PRI =18; public static int ENEMY_CHANGE2_PRI =19; //気絶に関するコンスタント public static int ENEMY_DEAD =-13; public static int ENEMY_FILL1 =-14; public static int ENEMY_FILL2 =-15; public static int ENEMY_LOSE1 =-16; public static int ENEMY_LOSE2 =-17; public static int MY_DEAD=-10; public static int MY_FILL1=-9; public static int MY_FILL2=-8; public static int MY_LOSE1=-7; public static int MY_LOSE2=-6; public static int YES =1; public static int NO =0; public static int RUN_ABLE =1; public static int RUN_DISABLE =0; public static int COMMAND_SELECT = 4; public static int SKILL_SELECT =5; //npcが最初に出すポケモンのインデクス public static int ENEMY_FIRST_POKEMON = 0; //command select 選択目録 public static int FIGHT =0; public static int BACK_PACK =1; public static int POKEMON =2; public static int RUN =3; public static int CANT_RUN_1 =1; public static int CANT_RUN_2 =2; public static int RUNABLE_1 =3; public static int RUNABLE_2 =4; public static int NONE =-1; public static int BATTLE_POSITION =0; public int stunState; //演出の途中に入力を防ぐためのstate public int inputBlock; //キャラクターの行動終了state public int PlayerDoneState; //このstateでマップ上のnpcが消えるようにできる。 public int winState; //バトル最初にキャラクターが持っているポケモンの中でインデクスの上から調べて気絶していないポケモンを出す。 public int startStillAliveIndex; public int myPokemonIndex; public int startCommentState; //敵の現在出ているポケモンのindex public int enemyPokemonIndex; //アイテムの使用 state public int itemUsedNumState; public int runState; public int itemToPokemon; public int commandSelectPointer; public int skillSelectPointer; public int battleSkillState; public int battleLoopState; //バトルに使われるディレイ public int potionDelay; public int changeDelay; public int enemyDelay; public int attackDelay; public int deadDelay; //スキルエフェクトのディレイ public int skillEffectDelay; //敵が倒れた場合にai.stateを一度だけ受け取るstate public int enemyDeadChangeState; //スキルエフェクトのインデクス public int skillEffectIndex; //バトルの優先順位 public int enemyPriority; public int battleState; public int wildPokemonMeetState; public Position position; // フレームイメージ public SpriteImg spriteBall; public BufferedImage pokemonStatusFrame; public BufferedImage[] ballIamge; public BufferedImage myHpFrame; public BufferedImage enemyHpFrame; public BufferedImage commandFrameSkillSelect; public BufferedImage commandFrameItemUseSelect; public BufferedImage commandFramePokemonSelect; public BufferedImage battleComentFrame; public BufferedImage commandFrame; public BufferedImage commentFrame; public BufferedImage pointer; // コメントイメージ public BufferedImage beHeal; public BufferedImage blind; public BufferedImage cantRunComment1; public BufferedImage cantRunComment2; public BufferedImage comeBack; public BufferedImage enemy; public BufferedImage enemyLoseComment; public BufferedImage exclamationText; public BufferedImage falling; public BufferedImage goText; public BufferedImage hpGa; public BufferedImage loser; public BufferedImage no; public BufferedImage nomore; public BufferedImage OOeega; public BufferedImage OOege; public BufferedImage OOeul; public BufferedImage OOis; public BufferedImage OOui; public BufferedImage redName; public BufferedImage sequenceText; public BufferedImage showBooText; public BufferedImage takeOut; public BufferedImage trainerText; public BufferedImage use; public BufferedImage winText; private Battle() throws IOException { enemyDeadChangeState=NONE; skillEffectIndex=0; runState=NONE; skillEffectDelay=0; startCommentState=NONE; battleLoopState=NONE; battleSkillState=NONE; battleState=BATTLE_NO; enemyPokemonIndex=ENEMY_FIRST_POKEMON; itemToPokemon=NO; PlayerDoneState=NO; commandSelectPointer=0; skillSelectPointer=0; itemUsedNumState=NONE; enemyPriority=NONE; winState=NONE; potionDelay=0; changeDelay=0; attackDelay=0; deadDelay=0; inputBlock=NONE; stunState=NONE; myPokemonIndex=BATTLE_POSITION; wildPokemonMeetState=NONE; startStillAliveIndex=0; enemyDelay=0; // frame Image load spriteBall= new SpriteImg(4,1,28,28,"./img/battle/frame/monsterstatus.png"); ballIamge=spriteBall.makeSpriteImg(); battleComentFrame=ImageIO.read(new File("./img/battle/frame/battlecomentFrame.png")); commandFrame=ImageIO.read(new File("./img/battle/frame/commandframe.png")); commandFrameItemUseSelect=ImageIO.read(new File("./img/battle/frame/commandframe_ItemUseselect.png"));; commandFramePokemonSelect=ImageIO.read(new File("./img/battle/frame/commandframe_pokemonselect.png"));; commandFrameSkillSelect=ImageIO.read(new File("./img/battle/frame/commandframe_skillselect.png")); commentFrame=ImageIO.read(new File("./img/battle/frame/comentframe.png")); enemyHpFrame=ImageIO.read(new File("./img/battle/frame/enemyHPframe.png")); myHpFrame=ImageIO.read(new File("./img/battle/frame/myHPframe.png")); pokemonStatusFrame=ImageIO.read(new File("./img/battle/frame/pokemonstatusframe.png")); pointer=ImageIO.read(new File("./img/battle/frame/pointer.png")); // comment Image load beHeal=ImageIO.read(new File("./img/battle/comment/Beheal.png")); blind=ImageIO.read(new File("./img/battle/comment/blind.png")); cantRunComment1=ImageIO.read(new File("./img/battle/comment/cantruncomment1.png")); cantRunComment2=ImageIO.read(new File("./img/battle/comment/cantruncomment2.png")); comeBack=ImageIO.read(new File("./img/battle/comment/comeback.png")); enemy=ImageIO.read(new File("./img/battle/comment/enemy.png")); enemyLoseComment=ImageIO.read(new File("./img/battle/comment/enemylosecomment.png")); exclamationText=ImageIO.read(new File("./img/battle/comment/exclamationtext.png")); falling=ImageIO.read(new File("./img/battle/comment/falling.png")); goText=ImageIO.read(new File("./img/battle/comment/gotext.png")); hpGa=ImageIO.read(new File("./img/battle/comment/HpGa.png")); loser=ImageIO.read(new File("./img/battle/comment/loser.png")); no=ImageIO.read(new File("./img/battle/comment/no.png")); nomore=ImageIO.read(new File("./img/battle/comment/nomore.png")); OOeega= ImageIO.read(new File("./img/battle/comment/OOeega.png")); OOege=ImageIO.read(new File("./img/battle/comment/OOege.png")); OOeul=ImageIO.read(new File("./img/battle/comment/OOeul.png")); OOis=ImageIO.read(new File("./img/battle/comment/OOis.png")); OOui=ImageIO.read(new File("./img/battle/comment/OOui.png")); redName=ImageIO.read(new File("./img/battle/comment/redname.png")); sequenceText=ImageIO.read(new File("./img/battle/comment/sequencetext.png")); showBooText=ImageIO.read(new File("./img/battle/comment/showbootext.png")); takeOut=ImageIO.read(new File("./img/battle/comment/takeout.png")); trainerText=ImageIO.read(new File("./img/battle/comment/trainertext.png")); use=ImageIO.read(new File("./img/battle/comment/Use.png")); winText=ImageIO.read(new File("./img/battle/comment/wintext.png")); //各 Imgの差表をもっているstruct class position= new Position(); } public static Battle getInstance(){ if(battleInstance==null){ try{ battleInstance= new Battle(); }catch (IOException e) { e.printStackTrace(); } } return battleInstance; } class Position{ //フレーム位置(ボールを除いてすべて0,0) public int[] enemyBallX; public int[] enemyBallY; public int[] myBallX; public int[] myBallY; //commandselect ポインターの位置 public int[][] commandSelectX; public int[][] commandSelectY; //skillselect ポインターの位置 public int[] skillPointerX; public int[] skillPointerY; //skillText ポインターの位置 public int[] skillTextX; public int[] skillTextY; //コメントの位置 public int BehealX; public int BehealY; public int blindX; public int blindY; public int cantRunComment1X; public int cantRunComment1Y; public int cantRunComment2X; public int cantRunComment2Y; public int comeBackX; public int comeBackY; public int enemyX; public int enemyY; public int enemyLoseCommentX; public int enemyLoseCommentY; public int exclamationTextX; public int exclamationTextY; public int fallingX; public int fallingY; public int goTextX; public int goTextY; public int healPoint50X; public int healPoint50Y; public int HPGaX; public int HPGaY; public int loserX; public int loserY; public int noX; public int noY; public int nomoreX; public int nomoreY; public int OOeegaX; public int OOeegaY; public int OOegeX; public int OOegeY; public int OOeulX; public int OOeulY; public int OOisX; public int OOisY; public int OOuiX; public int OOuiY; public int redNameX; public int redNameY; public int sequnceTextX; public int sequnceTextY; public int showBooTextX; public int showBooTextY; public int takOutX; public int takOutY; public int trainerTextX; public int trainerTextY; public int useX; public int useY; public int winTextX; public int winTextY; Position(){ enemyBallX=new int[6]; enemyBallY=new int[6]; myBallX=new int[6]; myBallY=new int[6]; makeBallPosition(); skillPointerX= new int[4]; skillPointerY= new int[4]; commandSelectX= new int[2][2]; commandSelectY= new int[2][2]; makePointerPosition(); skillTextX=new int[4]; skillTextY=new int[4]; makeSkillTextposition(); } public void makeSkillTextposition(){ int skillX=64; int skillY=300; for(int i=0;i<4;i++){ skillTextX[i]=skillX; skillTextY[i]=skillY; skillY+=64; } } public void makePointerPosition(){ int skillX=36; int skillY=320; for(int i=0;i<4;i++){ skillPointerX[i]=skillX; skillPointerY[i]=skillY; skillY+=64; } //戦う commandSelectX[0][0]=292; commandSelectY[0][0]=448; //バック commandSelectX[0][1]=452; commandSelectY[0][1]=448; //ポケモン commandSelectX[1][0]=292; commandSelectY[1][0]=512; //逃げる commandSelectX[1][1]=452; commandSelectY[1][1]=512; } public void makeBallPosition(){ int enemyX=100; int enemyY=68; int myX=356; int myY=324; for(int i=0;i<6;i++){ enemyBallX[i]=enemyX; enemyBallY[i]=enemyY; myBallX[i]=myX; myBallY[i]=myY; enemyX+=32; myX+=32; } } } }
true
d12ba05ff746eb8169ad929f6213f862435497e1
Java
sofwerx/OSUS-R
/mil.dod.th.core/src/mil/dod/th/core/remote/messaging/MessageRouter.java
UTF-8
1,917
2.15625
2
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//============================================================================== // This software is part of the Open Standard for Unattended Sensors (OSUS) // reference implementation (OSUS-R). // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along // with this software. If not, see // <http://creativecommons.org/publicdomain/zero/1.0/>. //============================================================================== package mil.dod.th.core.remote.messaging; import aQute.bnd.annotation.ProviderType; import mil.dod.th.core.remote.RemoteChannel; import mil.dod.th.core.remote.proto.RemoteBase.TerraHarvestMessage; /** * MessageRouter handles routing {@link TerraHarvestMessage}s received by the system to the appropriate service that * will handle parsing the message's content. * * @author Dave Humeniuk */ @ProviderType public interface MessageRouter { /** * Routes the given {@link TerraHarvestMessage} to the appropriate service that will handle the message. This * method can be used when the message is received through a means that is not associated with a * {@link RemoteChannel}. * * @param message * message that has been received */ void handleMessage(TerraHarvestMessage message); /** * Routes the given {@link TerraHarvestMessage} to the appropriate service that will handle the message. * * @param message * message that has been received * @param channel * channel the message was received on or null if the message is was not received through a channel */ void handleMessage(TerraHarvestMessage message, RemoteChannel channel); }
true
88c6601f1e03cf9968c4bd574fedba36c2538f70
Java
rajeevkrishnanr/hey.there
/app/src/main/java/in/heythere/heythere/RegActivity.java
UTF-8
14,720
2.0625
2
[]
no_license
package in.heythere.heythere; import android.app.Fragment; import android.app.FragmentManager; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v13.app.FragmentPagerAdapter; import android.support.v13.app.FragmentStatePagerAdapter; import android.support.v4.app.FragmentActivity; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Base64; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; /** * Demonstrates a "screen-slide" animation using a * automatically plays such an animation when * * <p>This sample shows a "next" button that advances the user to the next step in a wizard, * animating the current screen out (to the left) and the next screen in (from the right). The * reverse animation is played when the user presses the "previous" button.</p> * * */ public class RegActivity extends FragmentActivity { /** * The Variables * */ private String new_user, new_pass,new_name,new_emailid; private ProgressDialog pDialog; private static final String REG_URL="http://server.heyteam.me/reg_exec.php"; private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; private Uri imageUri; private Button finishbut; private static Bitmap dpImage = null; JSONParser jsonParser = new JSONParser(); int success=1; //Debug String String newdbgtext; /** * The pager widget, which handles animation and allows swiping horizontally to access previous * and next wizard steps. */ private ViewPager mPager; /** * The pager adapter, which provides the pages to the view pager widget. */ private PagerAdapter mPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reg); // Instantiate a ViewPager and a PagerAdapter. mPager = (ViewPager) findViewById(R.id.pager); mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager()); mPager.setAdapter(mPagerAdapter); //Init The UI Fields mPager.setOnTouchListener(new ViewPager.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }); mPager.setOnFocusChangeListener(new ViewPager.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus == false){ //get text from edittext field... /* new_user = (EditText) mPager.findViewById(R.id.new_username); new_pass = (EditText) mPager.findViewById(R.id.new_password); new_name = (EditText) mPager.findViewById(R.id.new_fullname); new_emailid = (EditText) mPager.findViewById(R.id.new_email); */ Log.d("In Onfocus Change", "Possible Fail Point!"); // newdbgtext = new_user.getText().toString(); Log.d("In Onfocus Change", "Fail Point Over."); } } }); } public void toastfinishReg(String displayToastText) { Toast.makeText(this, displayToastText, Toast.LENGTH_LONG).show(); } public void nextPage(View view) { mPager.setCurrentItem(mPager.getCurrentItem() + 1); } public void finishPage(View view) { Log.d("Finish Button Clicked", "starting"); //String new_username_data = new_user.getText().toString(); //Log.d("*** DEBUG ***The Usernames : ", new_username_data); //Log.d("*** DEBUG ***The Usernames : ", newdbgtext); //startAsyncInfo(); toastfinishReg(newdbgtext); new AttemptReg().execute(new_user,new_pass,new_name,new_emailid); Log.d("AttemptReg()", "Completed"); } //TODO public void getDatafromFragment1(String username_frag,String pass_frag,String pass_frag_verify) { Log.d("Datafrom Fragment in activity()", "Working"); new_user= username_frag; new_pass = pass_frag; //mPager.setCurrentItem(2); Log.d("Data from frgament received", "data is" + newdbgtext); } public void getDatafromFragment2(String fullname_frag, String email_frag) { new_name=fullname_frag; new_emailid=email_frag; } public void actionNextPage() { mPager.setCurrentItem(mPager.getCurrentItem() + 1); } public void actionBackPage() {mPager.setCurrentItem(mPager.getCurrentItem() - 1); } /** * A simple pager adapter that represents 3 objects, in * sequence. */ private class ScreenSlidePagerAdapter extends FragmentPagerAdapter { public ScreenSlidePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: // Top Rated fragment activity return new regscreen1(); case 1: // Games fragment activity return new regscreen2(); case 2: // Movies fragment activity return new regscreen3(); } return null; } @Override public int getCount() { // get item count - equal to number of tabs return 3; } } /**************************************************************************************************************/ class AttemptReg extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { Log.d("Inside AttemptReg()", "OnPreExec start"); super.onPreExecute(); Log.d("Inside AttemptReg()", "OnPreExec super"); pDialog = new ProgressDialog(RegActivity.this); Log.d("Inside AttemptReg()", "OnPreExec Dialog Made"); pDialog.setMessage("Registration: Getting you Abroad..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); Log.d("Inside AttemptReg()", "OnPreExec Completed"); } @Override protected String doInBackground(String... args) { /* here Check for success tag */ Log.d("Background AttemptReg()", "Background Starting"); String msg = "0"; Log.d("Background AttemptReg()", "Creating Input Objects "); Log.d("Background AttemptReg()", "String to store obj data"); //TODO Debug /*Debug Code Log.d("Async Background ", "Taking String Params"); */String new_username_Asyncdata = args[0]; String new_password_Asyncdata = args[1]; String new_fullname_Asyncdata = args[2]; String new_email_Asyncdata = args[3]; Log.d("AttemptReg() Params are", new_username_Asyncdata + "..." + new_password_Asyncdata + "..." + new_fullname_Asyncdata + "..." + new_email_Asyncdata ); Log.d("Background AttemptReg()", "Going to Try Block"); //todo ByteArrayOutputStream baos = new ByteArrayOutputStream(); dpImage.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); Log.d("AttemptReg() Background", "DP Encoding..."); String dpImage_encoded = Base64.encodeToString(imageBytes, Base64.DEFAULT); try { Log.d("AttemptReg() Background", "DP encoded!"); List<NameValuePair> params = new ArrayList<>(); Log.d("AttemptReg() Background", "Try Block: Adding Params"); params.add(new BasicNameValuePair("username", new_username_Asyncdata)); params.add(new BasicNameValuePair("password", new_password_Asyncdata)); params.add(new BasicNameValuePair("fullname", new_fullname_Asyncdata)); params.add(new BasicNameValuePair("email", new_email_Asyncdata)); // TODO params.add(new BasicNameValuePair("dpimage", dpImage_encoded)); Log.d("JSON request!", "starting"); JSONObject json = jsonParser.makeHttpRequest( REG_URL, "POST", params); success = json.getInt(TAG_SUCCESS); if (success == 1) { //Log.d("Successfully Login!", json.toString()); msg = "1"; Intent ii = new Intent(RegActivity.this, login.class); finish(); // this finish() method is used to tell android os that we are done with current // activity now! Moving to other activity startActivity(ii); //return json.getString(TAG_MESSAGE); return msg; } else { //return json.getString(TAG_MESSAGE); msg = "0"; return msg; } } catch (JSONException jexp) { jexp.printStackTrace(); } return msg; } @Override protected void onPostExecute(String result){ int status = Integer.parseInt(result) ; String disp_text="Try Again"; switch (status){ case 0: disp_text = "Registration Failed";break; case 1:disp_text= "Registration Successful! \n Kindly Login ";break; case 2: disp_text= "Username already taken!"; mPager.setCurrentItem(0);break; default:break; } pDialog.dismiss(); Toast.makeText(getApplicationContext(),disp_text , Toast.LENGTH_LONG).show(); } } /***************************************************************************************************************/ //The below part Refer http://shaikhhamadali.blogspot.in/2013/09/capture-images-and-crop-images-using.html public void uploadDP(View view) { /* create an instance of intent * pass action android.media.action.IMAGE_CAPTURE * as argument to launch camera */ // Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); /*create instance of File with name img.jpg*/ // File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg"); /*put uri as extra in intent object*/ // intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); //My code: Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); /*start activity for result pass intent as argument and request code */ startActivityForResult(intent, 1); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //if request code is same we pass as argument in startActivityForResult if(requestCode==1){ //Crop the captured image using an other intent try { /*the user's device may not support cropping*/ imageUri = data.getData(); cropCapturedImage(imageUri); } catch(ActivityNotFoundException aNFE){ //display an error message if user device doesn't support String errorMessage = "Sorry - your device doesn't support the crop action!"; Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT); toast.show(); } } if(requestCode==2){ ImageView dpPreview = (ImageView)findViewById(R.id.dp_preview); //APP Crash on dpPreview Bitmap set Log.d("Req Code 2", "Going to set null"); if (dpImage != null) dpImage.recycle(); //Create an instance of bundle and get the returned data Bundle extras = data.getExtras(); //get the cropped bitmap from extras Bitmap dpPic = extras.getParcelable("data"); //set image bitmap to image view dpPreview.setImageBitmap(dpPic); dpImage=dpPic; Log.d("Req Code 2", "Image set-up Completed"); } } //create helping method cropCapturedImage(Uri picUri) public void cropCapturedImage(Uri picUri){ //call the standard crop action intent Intent cropIntent = new Intent("com.android.camera.action.CROP"); //indicate image type and Uri of image //cropIntent.setDataAndType(picUri, "image/*"); cropIntent.setType("image/*"); Log.d("Crop Fn", "Set pic URI"); cropIntent.setData(picUri); Log.d("Crop Fn", "PicUri is: " + picUri); //set crop properties cropIntent.putExtra("crop", "true"); //indicate aspect of desired crop cropIntent.putExtra("aspectX", 1); cropIntent.putExtra("aspectY", 1); //indicate output X and Y cropIntent.putExtra("outputX", 200); cropIntent.putExtra("outputY", 200); //retrieve data on return Log.d("Crop Fn:", "Extra title:" + cropIntent.EXTRA_TITLE); cropIntent.putExtra("return-data", true); Log.d("Crop Fn", "After Put Extra"); //start the activity - we handle returning in onActivityResult startActivityForResult(cropIntent, 2); } /**********************************************************************************************************/ }
true
a4b1992bf18182b61a55391694de422f2db866de
Java
176wer/song.ADSN
/src/test/TestFrame.java
UTF-8
1,515
2.921875
3
[]
no_license
package test; import java.awt.EventQueue; import java.awt.FlowLayout; import javax.swing.JFrame; import java.awt.GridLayout; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JPanel; import javax.swing.JButton; public class TestFrame { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { TestFrame window = new TestFrame(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public TestFrame() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JScrollPane scrollPane = new JScrollPane(); frame.getContentPane().add(scrollPane, BorderLayout.CENTER); JPanel panel = new JPanel(); scrollPane.setViewportView(panel); panel.setLayout(new GridLayout(0,10 )); JButton btnNewButton4 = new JButton("6"); panel.add(btnNewButton4); for(int i=0;i<20;i++){ MyJButton btnNewButton6 = new MyJButton(String.valueOf(i)); panel.add(btnNewButton6); } } class MyJButton extends JButton{ public MyJButton(String agrs){ super(agrs); } public Dimension getPreferredSize(){ return new Dimension(100,100); } } }
true
ea8557278e97125a7a5fb08ebfa9b00bdde8a9b3
Java
charan69/selenium_cucumber_bddframework
/src/test/java/utilities/WaitHelper.java
UTF-8
758
2.53125
3
[]
no_license
package utilities; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class WaitHelper { public WebDriver driver; public WaitHelper(WebDriver driver) { this.driver = driver; } public void waitForElementforVisibilty(WebElement element, long waittime) { WebDriverWait wait = new WebDriverWait(driver, waittime); wait.until(ExpectedConditions.visibilityOf(element)); } public void waitforElementTobeClickable(By element, int waittime) { WebDriverWait wait = new WebDriverWait(driver, waittime); wait.until(ExpectedConditions.elementToBeClickable(element)); } }
true
777ced15e29fa96304fb68afbbf9365ad69224ed
Java
ashwinyes/gatk
/src/main/java/org/broadinstitute/hellbender/tools/funcotator/Funcotator.java
UTF-8
19,380
2.09375
2
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
package org.broadinstitute.hellbender.tools.funcotator; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFHeader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.broadinstitute.barclay.argparser.ArgumentCollection; import org.broadinstitute.barclay.argparser.BetaFeature; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import org.broadinstitute.barclay.help.DocumentedFeature; import org.broadinstitute.hellbender.cmdline.StandardArgumentDefinitions; import org.broadinstitute.hellbender.engine.*; import org.broadinstitute.hellbender.engine.filters.CountingVariantFilter; import org.broadinstitute.hellbender.exceptions.UserException; import org.broadinstitute.hellbender.tools.funcotator.dataSources.DataSourceUtils; import org.broadinstitute.hellbender.tools.funcotator.metadata.VcfFuncotationMetadata; import org.broadinstitute.hellbender.transformers.VariantTransformer; import org.broadinstitute.hellbender.utils.SequenceDictionaryUtils; import picard.cmdline.programgroups.VariantEvaluationProgramGroup; import java.nio.file.Path; import java.util.*; /** * Funcotator (FUNCtional annOTATOR) analyzes given variants for their function (as retrieved from a set of data sources) and produces the analysis in a specified output file. * * <p> * This tool is a functional annotation tool that allows a user to add annotations to called variants based on a set of data sources, each with its own matching criteria. * Data sources are expected to be in folders that are specified as input arguments. While multiple data source folders can be specified, <b>no two data sources can have the same name</b>. * </p> * <h3>Data Source Folders</h3> * <p> * In each main data source folder, there should be sub-directories for each individual data source, with further sub-directories for a specific reference (i.e. <i>hg19</i> or <i>hg38</i>). * In the reference-specific data source directory, there is a configuration file detailing information about the data source and how to match it to a variant. This configuration file is required. * </p> * <p> * An example of a data source directory is the following: * * <pre> * dataSourcesFolder/ * Data_Source_1/ * hg19 * data_source_1.config * data_source_1.data.file.one * data_source_1.data.file.two * data_source_1.data.file.three * ... * hg38 * data_source_1.config * data_source_1.data.file.one * data_source_1.data.file.two * data_source_1.data.file.three * ... * Data_Source_2/ * hg19 * data_source_2.config * data_source_2.data.file.one * data_source_2.data.file.two * data_source_2.data.file.three * ... * hg38 * data_source_2.config * data_source_2.data.file.one * data_source_2.data.file.two * data_source_2.data.file.three * ... * ... * </pre> * <b>Versioned gzip archives of data source files are provided here: <a href="ftp://gsapubftp-anonymous@ftp.broadinstitute.org/bundle/funcotator/">ftp://gsapubftp-anonymous@ftp.broadinstitute.org/bundle/funcotator/</a>.</b> * </p> * <h4>User-Defined Data Sources</h4> * <p> * Users can define their own data sources by creating a new correctly-formatted data source sub-directory in the main data sources folder. In this sub-directory, the user must create an additional folder for the reference for which the data source is valid. If the data source is valid for multiple references, then multiple reference folders should be created. * Inside each reference folder, the user should place the file(s) containing the data for the data source. Additionally the user <b>must</b> create a configuration file containing metadata about the data source. * </p> * <p> * There are several formats allowed for data sources, however the two most useful are arbitrarily separated value (XSV) files, such as comma-separated value (CSV), tab-separated value (TSV). These files contain a table of data that can be matched to a variant by <i>gene name</i>, <i>transcript ID</i>, or <i>genome position</i>. * In the case of <i>gene name</i> and <i>transcript ID</i>, one column must contain the <i>gene name</i> or <i>transcript ID</i> for each row's data. * <ul> * <li>For <i>gene name</i>, when a variant is annotated with a gene name that <i>exactly matches</i> an entry in the gene name column for a row, that row's other fields will be added as annotations to the variant.</li> * <li>For <i>transcript ID</i>, when a variant is annotated with a transcript ID that <i>exactly matches</i> an entry in the transcript ID column for a row, that row's other fields will be added as annotations to the variant.</li> * <li>For <i>genome position</i>, one column must contain the contig ID, another column must contain the start position (1-based, inclusive), and a column must contain the stop position (1-based, inclusive). The start and stop columns may be the same column. When a variant is annotated with a genome position that <i>overlaps</i> an entry in the three genome position columns for a row, that row's other fields will be added as annotations to the variant.</li> * </ul> * </p> * <h4>Configuration File Format</h4> * <p> * The configuration file is a standard Java properties-style configuration file with key-value pairs. This file name <b>must end in .config</b>. * </p> * <p> * The following is an example of a genome position XSV configuration file (for the ORegAnno data source): * <pre> * name = Oreganno * version = 20160119 * src_file = oreganno.tsv * origin_location = http://www.oreganno.org/dump/ORegAnno_Combined_2016.01.19.tsv * preprocessing_script = getOreganno.py * * # Supported types: * # simpleXSV -- Arbitrary separated value table (e.g. CSV), keyed off Gene Name OR Transcript ID * # locatableXSV -- Arbitrary separated value table (e.g. CSV), keyed off a genome location * # gencode -- Custom datasource class for GENCODE * # cosmic -- Custom datasource class for COSMIC * # vcf -- Custom datasource class for Variant Call Format (VCF) files * type = locatableXSV * * # Required field for GENCODE files. * # Path to the FASTA file from which to load the sequences for GENCODE transcripts: * gencode_fasta_path = * * # Required field for simpleXSV files. * # Valid values: * # GENE_NAME * # TRANSCRIPT_ID * xsv_key = * * # Required field for simpleXSV files. * # The 0-based index of the column containing the key on which to match * xsv_key_column = * * # Required field for simpleXSV AND locatableXSV files. * # The delimiter by which to split the XSV file into columns. * xsv_delimiter = \t * * # Required field for simpleXSV files. * # Whether to permissively match the number of columns in the header and data rows * # Valid values: * # true * # false * xsv_permissive_cols = true * * # Required field for locatableXSV files. * # The 0-based index of the column containing the contig for each row * contig_column = 1 * * # Required field for locatableXSV files. * # The 0-based index of the column containing the start position for each row * start_column = 2 * * # Required field for locatableXSV files. * # The 0-based index of the column containing the end position for each row * end_column = 3 * </pre> * </p> * * <h3>Inputs</h3> * <ul> * <li>A reference genome sequence.</li> * <li>The version of the reference genome sequence being used (e.g. <i>hg19</i>, <i>hg38</i>, etc.).</li> * <li>A VCF of variant calls to annotate.</li> * <li>The path to a folder of data sources formatted for use by Funcotator.</li> * <li>The desired output format for the annotated vaiants file (either <i>MAF</i> or <i>VCF</i>)</li> * </ul> * * <h3>Output</h3> * <ul> * <li>A MAF or VCF file containing all variants from the input file with added annotations corresponding to annotations from each data source that matched a given variant according to that data source's matching criteria.</li> * </ul> * * <h3>Usage example</h3> * <pre> * ./gatk Funcotator \ * -R reference.fasta \ * -V input.vcf \ * -O outputFile \ * --output-file-format MAF \ * --data-sources-path dataSourcesFolder/ \ * --ref-version hg19 * </pre> * * <h3>Notes</h3> * <ul> * <li>This is a beta tool, and as such may generate errors or warnings.</li> * <li>This tool is the successor to <a href="http://portals.broadinstitute.org/oncotator/">Oncotator</a>, with better support for germline data.</li> * </ul> * * <h3>Known Issues</h3> * <p>A complete list of known open issues can be found on <a href="https://github.com/broadinstitute/gatk/issues?q=is%3Aopen+is%3Aissue+label%3AFuncotator">the GATK github entry for funcotator here.</a></p> */ @CommandLineProgramProperties( summary = "Create functional annotations on given variants cross-referenced by a given set of data sources.\n" + "A GATK functional annotation tool.", oneLineSummary = "Functional Annotator", programGroup = VariantEvaluationProgramGroup.class ) @DocumentedFeature @BetaFeature public class Funcotator extends VariantWalker { private static final Logger logger = LogManager.getLogger(Funcotator.class); //================================================================================================================== // Arguments: @ArgumentCollection private final FuncotatorArgumentCollection funcotatorArgs = new FuncotatorArgumentCollection(); //================================================================================================================== private OutputRenderer outputRenderer; private FuncotatorEngine funcotatorEngine; //================================================================================================================== /** * @return The {@link Funcotator}-specific arguments used to instantiate this {@link Funcotator} instance. */ public FuncotatorArgumentCollection getArguments() { return funcotatorArgs; } @Override public boolean requiresReference() { return true; } @Override public void onTraversalStart() { logger.info("Validating Sequence Dictionaries..."); if (seqValidationArguments.performSequenceDictionaryValidation()) { // Ensure that the reference dictionary is a superset of the variant dictionary: checkReferenceDictionaryIsSupersetOfVariantDictionary(); } logger.info("Processing user transcripts/defaults/overrides..."); // Next set up our transcript list: final Set<String> finalUserTranscriptIdSet = FuncotatorEngine.processTranscriptList(funcotatorArgs.userTranscriptIdSet); // Get our overrides for annotations: final LinkedHashMap<String, String> annotationDefaultsMap = FuncotatorEngine.splitAnnotationArgsIntoMap(funcotatorArgs.annotationDefaults); final LinkedHashMap<String, String> annotationOverridesMap = FuncotatorEngine.splitAnnotationArgsIntoMap(funcotatorArgs.annotationOverrides); // Get the header for our variants: final VCFHeader vcfHeader = getHeaderForVariants(); logger.info("Initializing data sources..."); // Initialize all of our data sources: // Sort data sources to make them process in the same order each time: funcotatorArgs.dataSourceDirectories.sort(Comparator.naturalOrder()); final Map<Path, Properties> configData = DataSourceUtils.getAndValidateDataSourcesFromPaths(funcotatorArgs.referenceVersion, funcotatorArgs.dataSourceDirectories); logger.info("Finalizing data sources (this step can be long if data sources are cloud-based)..."); // Create the data sources from the input: // This will also create and register the FeatureInputs (created by the Data Sources) // with the GATK Engine, so we do not have to plumb them in after the fact. final List<DataSourceFuncotationFactory> dataSourceFuncotationFactories = DataSourceUtils.createDataSourceFuncotationFactoriesForDataSources( configData, annotationOverridesMap, funcotatorArgs.transcriptSelectionMode, finalUserTranscriptIdSet, this, funcotatorArgs.lookaheadFeatureCachingInBp, new FlankSettings(funcotatorArgs.fivePrimeFlankSize, funcotatorArgs.threePrimeFlankSize) ); logger.info("Initializing Funcotator Engine..."); // Create our engine to do our work and drive this Funcotation train! funcotatorEngine = new FuncotatorEngine( funcotatorArgs, getSequenceDictionaryForDrivingVariants(), VcfFuncotationMetadata.create( new ArrayList<>(vcfHeader.getInfoHeaderLines()) ), dataSourceFuncotationFactories ); // Create our output renderer: logger.info("Creating a " + funcotatorArgs.outputFormatType + " file for output: " + funcotatorArgs.outputFile.toURI()); outputRenderer = funcotatorEngine.createOutputRenderer( annotationDefaultsMap, annotationOverridesMap, vcfHeader, getDefaultToolVCFHeaderLines(), this ); } /** * Checks to see that the given reference's sequence dictionary is a * superset of the given variant file's dictionary. * * This is a more strict check than the one found in {@link GATKTool#validateSequenceDictionaries()}. */ private void checkReferenceDictionaryIsSupersetOfVariantDictionary() { final SAMSequenceDictionary referenceDictionary = getReferenceDictionary(); final SAMSequenceDictionary variantDictionary = getSequenceDictionaryForDrivingVariants(); if ( referenceDictionary == null ) { throw new UserException.BadInput("Reference fasta sequence dictionary is null!"); } if ( variantDictionary == null ) { throw new UserException.BadInput("Funcotator by default requires that the variant input have a sequence dictionary in its header. To disable this safety check, use argument --" + StandardArgumentDefinitions.DISABLE_SEQUENCE_DICT_VALIDATION_NAME); } SequenceDictionaryUtils.validateDictionaries( "Reference", getReferenceDictionary(), "Driving Variants", getSequenceDictionaryForDrivingVariants(), true, false ); } @Override protected CountingVariantFilter makeVariantFilter() { return new CountingVariantFilter(funcotatorEngine.makeVariantFilter()); } @Override public VariantTransformer makePostVariantFilterTransformer(){ return funcotatorEngine.getDefaultVariantTransformer(); } @Override public void apply(final VariantContext variant, final ReadsContext readsContext, final ReferenceContext referenceContext, final FeatureContext featureContext) { // Get the correct reference for B37/HG19 compliance: // This is necessary because of the variant transformation that gets applied in VariantWalkerBase::apply. final ReferenceContext correctReferenceContext = funcotatorEngine.getCorrectReferenceContext(variant, referenceContext); // Place the variant on our queue to be funcotated: enqueueAndHandleVariant(variant, correctReferenceContext, featureContext); } @Override public Object onTraversalSuccess() { // If we only saw IGRs, we most likely have a configuration issue. // Make sure the user knows this by making a HUGE stink about it. if ( funcotatorEngine.onlyProducedIGRs() ) { logger.warn("================================================================================"); logger.warn("\u001B[43m _ _ _ __ __ _ _ _ _ "); logger.warn(" | || || | \\ \\ / /_ _ _ __ _ __ (_)_ __ __ _ | || || | "); logger.warn(" | || || | \\ \\ /\\ / / _` | '__| '_ \\| | '_ \\ / _` | | || || | "); logger.warn(" |_||_||_| \\ \\V V / (_| | | | | | | | | | | (_| | |_||_||_| "); logger.warn(" (_)(_)(_) \\_/\\_/ \\__,_|_| |_| |_|_|_| |_|\\__, | (_)(_)(_) "); logger.warn(" |___/ \u001B[0;0m"); logger.warn("--------------------------------------------------------------------------------"); logger.warn(" Only IGRs were produced for this dataset. This STRONGLY indicates that this "); logger.warn(" run was misconfigured. "); logger.warn(" You MUST check your data sources to make sure they are correct for these data."); logger.warn("================================================================================"); } return true; } @Override public void closeTool() { if ( funcotatorEngine != null) { funcotatorEngine.close(); } if ( outputRenderer != null ) { outputRenderer.close(); } } //================================================================================================================== /** * Creates an annotation on the given {@code variant} or enqueues it to be processed during a later call to this method. * @param variant {@link VariantContext} to annotate. * @param referenceContext {@link ReferenceContext} corresponding to the given {@code variant}. * @param featureContext {@link FeatureContext} corresponding to the given {@code variant}. */ private void enqueueAndHandleVariant(final VariantContext variant, final ReferenceContext referenceContext, final FeatureContext featureContext) { final FuncotationMap funcotationMap = funcotatorEngine.createFuncotationMapForVariant(variant, referenceContext, featureContext); // At this point there is only one transcript ID in the funcotation map if canonical or best effect are selected outputRenderer.write(variant, funcotationMap); } }
true
78da86a635711276382116c7519f683cd24753c8
Java
jhonnatanBezerra/sisHotel
/src/jhonnatan/hotel/model/Reserva.java
UTF-8
1,624
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 jhonnatan.hotel.model; import java.sql.Date; /** * * @author Jhonnatan */ public class Reserva { private Integer id; private String nome; private Date dataChegada; private Integer qtdPessoas; private Integer diarias; private Boolean status; private Usuario usuario; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Date getDataChegada() { return dataChegada; } public void setDataChegada(Date dataChegada) { this.dataChegada = dataChegada; } public Integer getQtdPessoas() { return qtdPessoas; } public void setQtdPessoas(Integer qtdPessoas) { this.qtdPessoas = qtdPessoas; } public Integer getDiarias() { return diarias; } public void setDiarias(Integer diarias) { this.diarias = diarias; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } }
true
6c30f8b65e1ff22e1309f7e4c6e6fda71f52e0e8
Java
liangjinx/ssh_drools
/ssh_entity/src/main/java/zhinan/liang/entitys/FlowEvent.java
UTF-8
1,315
2.265625
2
[ "Apache-2.0" ]
permissive
package zhinan.liang.entitys; import javax.persistence.*; import java.io.Serializable; import static javax.persistence.GenerationType.SEQUENCE; /** * Created by liang on 2016/6/7. */ @Entity @Table public class FlowEvent implements Serializable{ private static final long serialVersionUID = 9080268225625336475L; @Id @GeneratedValue(strategy=SEQUENCE, generator="id_flowsEvent") @SequenceGenerator(name="id_flowsEvent",sequenceName = "flowsEvent_id" ,allocationSize = 25,schema="scott",initialValue=0) private Integer id; private String flowEventId; private String flowEventName; private String FlowEventValue; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFlowEventId() { return flowEventId; } public void setFlowEventId(String flowEventId) { this.flowEventId = flowEventId; } public String getFlowEventName() { return flowEventName; } public void setFlowEventName(String flowEventName) { this.flowEventName = flowEventName; } public String getFlowEventValue() { return FlowEventValue; } public void setFlowEventValue(String flowEventValue) { FlowEventValue = flowEventValue; } }
true
b9d4aa57116dbdeddc39ecace5c214a847c96300
Java
martbogdan/shop
/src/main/java/com/smallshop/shop/dao/repository/UserRepository.java
UTF-8
480
2.015625
2
[]
no_license
package com.smallshop.shop.dao.repository; import com.smallshop.shop.dao.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findUserByEmail (String email); User findUserByFirstName (String firstName); Optional<User> findUserByUsername (String username); }
true
ba25d0df72dfd182d248c312fea0b53640c528da
Java
nauman-khattak/Zayed-University-Grading-System
/src/grading/system/Course.java
UTF-8
3,889
3.21875
3
[]
no_license
package grading.system; import java.text.DecimalFormat; import java.util.ArrayList; public class Course { Student student; ArrayList<Integer> credits; ArrayList<String> grades; String[] possibleGrades; double[] pointsAgainstGrades; int creditsCompleted; double sgpa; DecimalFormat df; public Course(Student student) { this.student = student; credits = new ArrayList<>(); grades = new ArrayList<>(); possibleGrades = new String[]{"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F", "WF"}; pointsAgainstGrades = new double[]{4, 4, 3.7, 3.3, 3, 2.7, 2.3, 2, 1.7, 1.3, 1, 0.7, 0, 0}; creditsCompleted = Integer.valueOf(student.creditsCompleted.getText()); df = new DecimalFormat("#.00"); getCreditsAndGrades(); } public void getCreditsAndGrades() { for (int i = 0; i < 6; i++) { switch (i) { case 0: credits.add(Integer.parseInt(student.credit1.getText())); grades.add(student.grade1.getText()); break; case 1: credits.add(Integer.parseInt(student.credit2.getText())); grades.add(student.grade2.getText()); break; case 2: credits.add(Integer.parseInt(student.credit3.getText())); grades.add(student.grade3.getText()); break; case 3: credits.add(Integer.parseInt(student.credit4.getText())); grades.add(student.grade4.getText()); break; case 4: credits.add(Integer.parseInt(student.credit5.getText())); grades.add(student.grade5.getText()); break; case 5: credits.add(Integer.parseInt(student.credit6.getText())); grades.add(student.grade6.getText()); break; } } } public double calculateGPA() { double multiplicationPart = 0; // ((P1 * U1) + (P2 * U2)+ (P3 *U3) + (P4*U4) + (P5*U5)) int totalCreditUnits = 0; for (int i = 0; i < 6; i++) { multiplicationPart += (creditForParticularGrade(grades.get(i)) * credits.get(i)); totalCreditUnits += credits.get(i); } sgpa = Double.valueOf(df.format(multiplicationPart / totalCreditUnits)); //Semester GPA = ((P1 * U1) + (P2 * U2)+ (P3 *U3) + (P4*U4) + (P5*U5)) / Total credit units return sgpa; } //Grade Points Table provided in project requirement document public double creditForParticularGrade(String grade) { for (int j = 0; j < possibleGrades.length; j++) { if (grade.equals(possibleGrades[j])) { return pointsAgainstGrades[j]; } } return 0; } public String getStanding() { if (sgpa >= 0 && sgpa <= 0.9) { return "Poor"; } else if (sgpa >= 1 && sgpa < 1) { return "Satisfactory"; } else if (sgpa >= 2 && sgpa < 3) { return "Good"; } else if (sgpa >= 3 && sgpa <= 4) { return "Excellent"; } return ""; } public String getRank() { if (creditsCompleted >= 0 && creditsCompleted <= 30) { return "Freshman"; } else if (creditsCompleted >= 31 && creditsCompleted <= 60) { return "Sophomore"; } else if (creditsCompleted >= 61 && creditsCompleted < 90) { return "Junior"; } else if (creditsCompleted >= 90) { return "Senior"; } return ""; } }
true
5d3b775281d88ed06e9cb26cbb6098e01b4deb6b
Java
gwon-bin/GB
/src/day16Test/문제해결연습.java
UHC
1,386
3.515625
4
[]
no_license
package day16Test; import java.util.Random; public class ذῬ { public static Random r = new Random(); public static int[] myPoint = new int[3]; public static int[] myBonus = new int[3]; public static void main(String[] args) { for (int i = 1; i < 4; i++) { System.out.println(i + " "); int point = r.nextInt(10) + 1; System.out.println(point); myPoint[i-1]=point; bonusPoint(point,i-1); // ʽ ޼ҵ ۼ // 1 : point ӿ ̸ ι ȹ(ù ش) // 2 : point ¦̸ point ʽ ȹ // 3 : point 3 ̸ -3 } // ϴ ޼ҵ ۼ sum(); } private static void sum() { int totalsum=0; for(int i = 0 ; i < myPoint.length; i++) { System.out.println(myPoint[i]+"/"+myBonus[i]); totalsum = totalsum + myPoint[i]+myBonus[i]; } System.out.println(totalsum); } private static void bonusPoint(int point, int k) { int bPoint = 0; for(int i = 0 ; i < k; i++) { if(myPoint[i]==point) { bPoint=1; } } if(bPoint==1) { myBonus[k]=point*2; }else if(point%2==0) { myBonus[k]=point/2; }else if(point%3==0) { myBonus[k]=-3; } } }
true
f09b9a7bc1f584a3a60d79b08ddd5180ed4bba7c
Java
MattBlissett/registry
/registry-ws-client/src/test/java/org/gbif/registry/util/IdentityUpdateValidationCheck.java
UTF-8
4,515
2.421875
2
[ "Apache-2.0" ]
permissive
package org.gbif.registry.util; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.model.common.paging.PagingResponse; import org.gbif.api.model.registry.Contact; import org.gbif.api.model.registry.Contactable; import org.gbif.api.model.registry.NetworkEntity; import org.gbif.api.service.registry.DatasetService; import org.gbif.api.service.registry.InstallationService; import org.gbif.api.service.registry.NetworkEntityService; import org.gbif.api.service.registry.NetworkService; import org.gbif.api.service.registry.NodeService; import org.gbif.api.service.registry.OrganizationService; import org.gbif.registry.ws.client.guice.RegistryWsClientModule; import org.gbif.ws.client.guice.GbifApplicationAuthModule; import java.util.Properties; import com.google.inject.Guice; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class does the identity function update for entities in the registry. That is to say that it reads and updates * all entities. * Because the database was migrated, and we have Java validation rules, this will ensure that all migrated data can be * used in updates. */ public class IdentityUpdateValidationCheck { private static final Logger LOG = LoggerFactory.getLogger(IdentityUpdateValidationCheck.class); /** * Runs the validation. To run, add the necessary properties as arguments. The key and password are * authenticated by the web services, so check they match a key/password combination the web services' know of. * * @param args Base url */ public static void main(String[] args) { Properties p = new Properties(); p.put("registry.ws.url", args[0]); p.setProperty("application.key", args[1]); p.setProperty("application.secret", args[2]); // Create authentication module, and set principal name, equal to a GBIF User unique account name GbifApplicationAuthModule auth = new GbifApplicationAuthModule(p); auth.setPrincipal("admin"); Injector injector = Guice.createInjector(new RegistryWsClientModule(p), auth); LOG.info("Starting Node tests"); int nodeErrorCount = verifyEntity(injector.getInstance(NodeService.class)); LOG.info("Node tests produced {} errors", nodeErrorCount); LOG.info("Starting Organization tests"); int organizationErrorCount = verifyEntity(injector.getInstance(OrganizationService.class)); LOG.info("Organization tests produced {} errors", organizationErrorCount); LOG.info("Starting Installation tests"); int installationErrorCount = verifyEntity(injector.getInstance(InstallationService.class)); LOG.info("Installation tests produced {} errors", installationErrorCount); LOG.info("Starting Dataset tests"); int datasetErrorCount = verifyEntity(injector.getInstance(DatasetService.class)); LOG.info("Dataset tests produced {} errors", datasetErrorCount); LOG.info("Starting Network tests"); int networkErrorCount = verifyEntity(injector.getInstance(NetworkService.class)); LOG.info("Network tests produced {} errors", networkErrorCount); // summarise again jsut for ease of reading LOG.info("Test results:"); LOG.info("Node tests produced {} errors", nodeErrorCount); LOG.info("Organization tests produced {} errors", organizationErrorCount); LOG.info("Installation tests produced {} errors", installationErrorCount); LOG.info("Dataset tests produced {} errors", datasetErrorCount); LOG.info("Network tests produced {} errors", networkErrorCount); } private static <T extends NetworkEntity> int verifyEntity(NetworkEntityService<T> service) { int errorCount = 0; PagingRequest page = new PagingRequest(0, 100); PagingResponse<T> response = null; do { response = service.list(page); LOG.debug("Page with offset[{}] return[{}] records", page.getOffset(), response.getCount()); for (T e : response.getResults()) { LOG.debug("Updating entity[{}]", e.getKey()); try { service.update(e); if (e instanceof Contactable) { Contactable contactable = (Contactable) e; for (Contact c : contactable.getContacts()) { service.updateContact(e.getKey(), c); } } } catch (Exception ex) { LOG.error("Unable to update entity[{}]", e.getKey(), ex); errorCount++; } } page.nextPage(); } while (!response.isEndOfRecords()); return errorCount; } }
true
455c61295e8aea2c128378fdc8cd76b450584888
Java
phoebemoon16/MoBook
/src/com/kzw/gym/entity/ShareReading.java
UTF-8
2,383
2.09375
2
[]
no_license
package com.kzw.gym.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.kzw.system.entity.Department; import com.kzw.system.entity.Dictionary; @Entity @Table(name="share_read") public class ShareReading { @Id @GeneratedValue private Integer id; //书名 private String bookName; // //类别 // @ManyToOne // @JoinColumn(name="dict_category") // private Dictionary category; private String bookType; //详细说明 private String deTail; //借书人 private String perName; //库存量 private int stock; //图片 private String imgUrl; //结束日期 private Date beginTime; //还书日期 private Date endTime; //联系人方式 private long telNum; @ManyToOne @JoinColumn(name="dept_id") private Department dept; // public Dictionary getCategory() { // return category; // } // public void setCategory(Dictionary category) { // this.category = category; // } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getDeTail() { return deTail; } public void setDeTail(String deTail) { this.deTail = deTail; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String img) { this.imgUrl = img; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public String getBookType() { return bookType; } public void setBookType(String bookType) { this.bookType = bookType; } public String getPerName() { return perName; } public void setPerName(String perName) { this.perName = perName; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public long getTelNum() { return telNum; } public void setTelNum(long telNum) { this.telNum = telNum; } public Department getDept() { return dept; } public void setDept(Department dept) { this.dept = dept; } }
true
b4922c14fc9e368c08e86a878971abcd6de99df9
Java
coffeerr/bytemall
/bytemall-order/src/main/java/com/iat/bytemall/order/service/RefundInfoService.java
UTF-8
441
1.585938
2
[]
no_license
package com.iat.bytemall.order.service; import com.baomidou.mybatisplus.extension.service.IService; import com.iat.common.utils.PageUtils; import com.iat.bytemall.order.entity.RefundInfoEntity; import java.util.Map; /** * 退款信息 * * @author desmand * @email chris1998@qq.com * @date 2021-03-13 11:42:37 */ public interface RefundInfoService extends IService<RefundInfoEntity> { PageUtils queryPage(Map<String, Object> params); }
true
3e4d06471737f79b580f590c3138eec8cbd31765
Java
rajvimalc/adobe-roman-numerals
/src/main/java/com/adobe/assessment/romannumerals/framework/security/WebFilterConfiguration.java
UTF-8
2,361
2.359375
2
[]
no_license
package com.adobe.assessment.romannumerals.framework.security; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; /** * @author Vimalraj Chandra Sekaran (rajvimalc) * Email: rajvimalc@gmail.com * Created on: 8/5/2021 10:18 PM * * WebFilter Configuration class for mutating URIs with context path */ @Configuration @Slf4j public class WebFilterConfiguration { @Bean @ConditionalOnProperty("server.servlet.context-path") public WebFilter contextPathWebFilter(ServerProperties serverProperties) { final String contextPath = serverProperties.getServlet().getContextPath(); log.info("Webflux base path is set to '{}'", contextPath); return (exchange, chain) -> filter(exchange, chain, contextPath); } /** * Mutate the incoming request with context path, except health check api * * @param contextPath Configured by application config 'server.servlet.context-path' */ protected Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain, String contextPath) { final String requestPath = exchange.getRequest().getURI().getPath(); if (requestPath.equals("/")) { return mutateContextPath(exchange, chain, ""); } else if (requestPath.startsWith(contextPath + "/") || requestPath.equals(contextPath)) { return mutateContextPath(exchange, chain, contextPath); } else { throw new ResponseStatusException(HttpStatus.NOT_FOUND); } } protected Mono<Void> mutateContextPath(ServerWebExchange exchange, WebFilterChain chain, String contextPath) { return chain.filter( exchange .mutate() .request(exchange.getRequest().mutate().contextPath(contextPath).build()) .build() ); } }
true
5e603f6a5b5a9f0c88cbb1d612434ffed3fe6fb8
Java
EEIT107Team003/iCook
/icook/src/main/java/recipe/controller/RecipeImageController.java
UTF-8
10,416
2.15625
2
[]
no_license
package recipe.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; //import java.util.ArrayList; //import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.CacheControl; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import recipe.model.RecipeBean; //import recipe.model.RecipeUnitBean; import recipe.service.IRecipeService; //import recipe.service.IRecipeUnitService; //專門處理圖片 @Controller public class RecipeImageController { private ServletContext servletContext = null; private IRecipeService recipeService = null; // private IRecipeUnitService recipeUnitService = null; @Autowired public RecipeImageController(ServletContext servletContext, IRecipeService recipeService) { this.servletContext = servletContext; this.recipeService = recipeService; } @RequestMapping(value = "/recipe/icookAddRecipe", method = RequestMethod.GET) public String insertGet(Model model) { return "recipe/icookAddRecipe";// 呼叫recipeInsert.jsp檔案 } // 回傳圖片給網頁的函數,回傳食譜步驟圖片. @SuppressWarnings("null") @RequestMapping(value = "/getRecipePicture2/{pk_recipe_id}/{stepNo}", method = RequestMethod.GET) public ResponseEntity<byte[]> getPictureUnit(HttpServletResponse response, @PathVariable Integer pk_recipe_id, @PathVariable Integer stepNo) { // System.out.println("資料進得去,圖片出不來,bug解不完。"); // System.out.println("開始抓取食譜步驟圖片-start"); String filePath = "/resources/images/NoImage.png"; byte[] media = null; HttpHeaders headers = new HttpHeaders(); Blob blob = null; String filename = ""; int len = 0; // JDBC-start Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionURL = "jdbc:sqlserver://localhost:1433;databaseName=icook"; connection = DriverManager.getConnection(connectionURL, "sa", "passw0rd"); connection.setAutoCommit(false);// 關閉自動交易模式,開啟隱性交易模式。 String qryStmt = "SELECT unit_image, file_name FROM recipe_unit WHERE (fk_recipe_id = " + String.valueOf(pk_recipe_id) + " AND stepNo = " + String.valueOf(stepNo) + ")"; statement = connection.createStatement(); resultSet = statement.executeQuery(qryStmt); while (resultSet.next()) { blob = resultSet.getBlob("unit_image"); // System.out.println("#2 blob -> " + blob); filename = resultSet.getString("file_name"); // System.out.println("#2 filename -> " + filename); } connection.commit();// commit把資料 新、刪、改、查 結果送出去 } catch (ClassNotFoundException e1) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } e1.printStackTrace(); } catch (SQLException e1) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } e1.printStackTrace(); } finally { if (connection != null) { try { // 開啟自動交易模式,關閉隱性交易模式。 connection.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } } if (resultSet != null) { try { resultSet.close(); resultSet = null; } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); statement = null; } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); connection = null; } catch (SQLException e) { e.printStackTrace(); } } } // JDBC-end // System.out.println("喔 77777, 為什麼食譜步驟圖片就是出不來?"); if (blob != null) { try { len = (int) blob.length(); // System.out.println("#2 blob.length() -> " + blob.length()); media = blob.getBytes(1, len); // blob.getBytes(1, len): 是 1 開頭。Jdbc相關的類別都是1 開頭。 // System.out.println("#2 media -> " + media); } catch (SQLException e) { throw new RuntimeException("#2 getPicture()發生SQLException:" + e); } } else { media = toByteArray(filePath); filename = filePath; } headers.setCacheControl(CacheControl.noCache().getHeaderValue()); String mimeType = servletContext.getMimeType(filename); // System.out.println("#2 mimeType -> " + mimeType); MediaType mediaType = MediaType.valueOf(mimeType); // System.out.println("#2 mediaType -> " + mediaType); headers.setContentType(mediaType); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(media, headers, HttpStatus.OK); // System.out.println("開始抓取食譜步驟圖片-end"); return responseEntity; } // // 回傳圖片給網頁的函數,回傳食譜步驟圖片. // //error-抓取食譜步驟圖片功能失敗。 // @RequestMapping(value = "/getRecipePicture2/{pk_recipe_id}/{stepNo}", method = RequestMethod.GET) // public ResponseEntity<byte[]> getPictureUnit(HttpServletResponse response, @PathVariable Integer pk_recipe_id, // @PathVariable Integer stepNo) throws ClassNotFoundException, SQLException { // // System.out.println("資料進得去,圖片出不來,bug解不完。"); // System.out.println("開始抓取食譜步驟圖片-start"); // String filePath = "/resources/images/NoImage.png"; // byte[] media = null; // HttpHeaders headers = new HttpHeaders(); // String filename = ""; // int len = 0; // RecipeUnitBean recipeUnit = recipeUnitService.getRecipeUnitByFkAndStepNo(pk_recipe_id, stepNo); // // System.out.println("喔 77777, 為什麼圖片就是出不來?"); // if (recipeUnit != null) { // Blob blob = recipeUnit.getUnit_image(); // filename = recipeUnit.getFile_name(); // if (blob != null) { // try { // len = (int) blob.length(); // media = blob.getBytes(1, len); // blob.getBytes(1, len): 是 1 開頭。Jdbc相關的類別都是1 開頭。 // } catch (SQLException e) { // throw new RuntimeException("#2 getPicture()發生SQLException:" + e); // } // } else { // media = toByteArray(filePath); // filename = filePath; // } // } // headers.setCacheControl(CacheControl.noCache().getHeaderValue()); // String mimeType = servletContext.getMimeType(filename); // System.out.println("#2 mimeType -> " + mimeType); // MediaType mediaType = MediaType.valueOf(mimeType); // System.out.println("#2 mediaType -> " + mediaType); // headers.setContentType(mediaType); // ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(media, headers, HttpStatus.OK); // System.out.println("開始抓取食譜步驟圖片-end"); // return responseEntity; // } // 回傳圖片給網頁的函數,回傳食譜封面主圖片. @RequestMapping(value = "/getRecipePicture/{pk_recipe_id}", method = RequestMethod.GET) public ResponseEntity<byte[]> getPicture(HttpServletResponse response, @PathVariable Integer pk_recipe_id) { // String filePath = "/resources/images/NoImage.jpg"; // System.out.println("@RequestMapping(value = \"/getRecipePicture/{pk_recipe_id}\", method = RequestMethod.GET)"); String filePath = "/resources/images/NoImage.png"; byte[] media = null; HttpHeaders headers = new HttpHeaders(); String filename = ""; int len = 0; RecipeBean recipe = recipeService.getRecipeById(pk_recipe_id); if (recipe != null) { Blob blob = recipe.getRecipe_image(); filename = recipe.getFile_name(); if (blob != null) { try { len = (int) blob.length(); media = blob.getBytes(1, len); // blob.getBytes(1, len): 是 1 開頭。Jdbc相關的類別都是1 開頭。 } catch (SQLException e) { throw new RuntimeException("#1 getPicture()發生SQLException:" + e); } } else { media = toByteArray(filePath); filename = filePath; } } else { media = toByteArray(filePath); filename = filePath; } headers.setCacheControl(CacheControl.noCache().getHeaderValue()); String mimeType = servletContext.getMimeType(filename); // System.out.println("#1 mimeType -> " + mimeType); MediaType mediaType = MediaType.valueOf(mimeType); // System.out.println("#1 mediaType -> " + mediaType); headers.setContentType(mediaType); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(media, headers, HttpStatus.OK); return responseEntity; } private byte[] toByteArray(String filePath) { // System.out.println("private byte[] toByteArray(String filepath) { -> start"); byte[] byteArray = null; InputStream fileInputStream = null; try { // System.out.println("filePath -> " + filePath); String realPath = servletContext.getRealPath(filePath); // System.out.println("realPath -> " + realPath); File file = new File(realPath); long size = file.length(); byteArray = new byte[(int) size]; // System.out.println("size = " + size); fileInputStream = servletContext.getResourceAsStream(filePath); // System.out.println("fis = " + fileInputStream); fileInputStream.read(byteArray); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); fileInputStream = null; } catch (IOException e) { e.printStackTrace(); } } } return byteArray; } }
true
65945a4399237f47c265a5d1e81b616192fbf43d
Java
manjumjs/Stockmarket_test
/StockMarketStockExchangeService/src/main/java/com/spring/manju/repository/IpoRepository.java
UTF-8
373
1.789063
2
[]
no_license
package com.spring.manju.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.spring.manju.bean.IpoDetail; @Repository public interface IpoRepository extends JpaRepository<IpoDetail, Long>{ public List<IpoDetail> getAllByStockExchange(String stockExchange); }
true
6a7314126832eb9b12a5cf408401d5b1934e4d26
Java
virtushawk/SimpleWebProject
/src/test/java/edu/epam/swp/model/service/impl/CreatureServiceImplTest.java
UTF-8
16,649
2.34375
2
[]
no_license
package edu.epam.swp.model.service.impl; import edu.epam.swp.exception.DaoException; import edu.epam.swp.exception.ServiceException; import edu.epam.swp.model.dao.CreatureDao; import edu.epam.swp.model.entity.Creature; import edu.epam.swp.model.service.CreatureService; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class CreatureServiceImplTest { @Mock private CreatureDao dao; @InjectMocks private CreatureService service; @BeforeClass public void beforeClass() { service = CreatureServiceImpl.getInstance(); MockitoAnnotations.openMocks(this); } @DataProvider public Object[][] creatureData() { return new Object[][] { {new Creature.CreatureBuilder().withName("test Name").withDescription("Test description").build(),true}, {new Creature.CreatureBuilder().withName("плохое имя").withDescription("Test description").build(),false}, {new Creature.CreatureBuilder().withName("test Name").withDescription("плохое описание").build(),false}, {new Creature.CreatureBuilder().withName("").withDescription("Test description").build(),false}, {new Creature.CreatureBuilder().withName("test Name").withDescription("").build(),false}, }; } @DataProvider public Object[][] uncheckedCreatureData() { return new Object[][] { {1,new Creature.CreatureBuilder().withName("test unchecked name").withDescription("Test unchecked description").build(),true}, {2,new Creature.CreatureBuilder().withName("плохое имя").withDescription("Test unchecked description").build(),false}, {3,new Creature.CreatureBuilder().withName("test unchecked Name").withDescription("плохое описание").build(),false}, {4,new Creature.CreatureBuilder().withName("").withDescription("Test unchecked description").build(),false}, {5,new Creature.CreatureBuilder().withName("test unchecked Name").withDescription("").build(),false}, }; } @Test public void findNewCreaturesTest() throws DaoException, ServiceException { int limit = 3; List<Creature> expected = new ArrayList<>(); Mockito.when(dao.findNewCreatures(Mockito.anyInt())).thenReturn(expected); List<Creature> actual = service.findNewCreatures(limit); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "findNewCreaturesTest",expectedExceptions = ServiceException.class) public void findNewCreaturesExceptionTest() throws DaoException,ServiceException { int limit = 3; Mockito.when(dao.findNewCreatures(Mockito.anyInt())).thenThrow(new DaoException()); service.findNewCreatures(limit); } @Test public void findPopularCreaturesTest() throws DaoException,ServiceException { int limit = 3; List<Creature> expected = new ArrayList<>(); Mockito.when(dao.findPopularCreatures(limit)).thenReturn(expected); List<Creature> actual = service.findPopularCreatures(limit); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "findPopularCreaturesTest",expectedExceptions = ServiceException.class) public void findPopularCreaturesExceptionTest() throws DaoException, ServiceException { int limit = 3; Mockito.when(dao.findPopularCreatures(Mockito.anyInt())).thenThrow(new DaoException()); service.findPopularCreatures(limit); } @Test(dataProvider = "creatureData") public void createCreatureTest(Creature creature,boolean expected) throws DaoException, ServiceException { Mockito.when(dao.create(creature)).thenReturn(true); boolean actual = service.createCreature(creature); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "createCreatureTest",expectedExceptions = ServiceException.class) public void createCreatureExceptionTest() throws DaoException, ServiceException { Creature creature = new Creature.CreatureBuilder().withName("test Name").withDescription("Test description").build(); Mockito.when(dao.create(creature)).thenThrow(new DaoException()); service.createCreature(creature); } @Test public void getCreatureTest() throws DaoException, ServiceException { long id = 1; Creature creature = new Creature.CreatureBuilder().withName("Test name").build(); Optional<Creature> expected = Optional.of(creature); Mockito.when(dao.find(Mockito.anyLong())).thenReturn(expected); Optional<Creature> actual = service.findCreature(id); Assert.assertEquals(actual,expected); } @Test public void getEmptyTest() throws DaoException, ServiceException { long id = 1; Optional<Creature> expected = Optional.empty(); Mockito.when(dao.find(Mockito.anyLong())).thenReturn(expected); Optional<Creature> actual = service.findCreature(id); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = {"getCreatureTest","getEmptyTest"},expectedExceptions = ServiceException.class) public void getExceptionTest() throws DaoException, ServiceException { long id = 1; Mockito.when(dao.find(Mockito.anyLong())).thenThrow(new DaoException()); service.findCreature(id); } @Test public void findAllTest() throws DaoException, ServiceException { List<Creature> expected = new ArrayList<>(); Mockito.when(dao.findAll()).thenReturn(expected); List<Creature> actual = service.findAll(); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "findAllTest",expectedExceptions = ServiceException.class) public void findAllExceptionTest() throws DaoException, ServiceException { Mockito.when(dao.findAll()).thenThrow(new DaoException()); service.findAll(); } @Test public void changeImageTrueTest() throws DaoException, ServiceException { String image = "path to picture"; long id = 1; Mockito.when(dao.updateImageById(Mockito.anyLong(),Mockito.anyString())).thenReturn(true); boolean actual = service.changeImage(id,image); Assert.assertTrue(actual); } @Test public void changeImageFalseTest() throws DaoException, ServiceException { String image = "path to picture"; long id = 1; Mockito.when(dao.updateImageById(Mockito.anyLong(),Mockito.anyString())).thenReturn(false); boolean actual = service.changeImage(id,image); Assert.assertFalse(actual); } @Test(dependsOnMethods = {"changeImageTrueTest","changeImageFalseTest"},expectedExceptions = ServiceException.class) public void changeImageExceptionTest() throws DaoException, ServiceException { String image = "path to picture"; long id = 1; Mockito.when(dao.updateImageById(Mockito.anyLong(),Mockito.anyString())).thenThrow(new DaoException()); service.changeImage(id,image); } @Test public void changeUncheckedImageTrueTest() throws DaoException, ServiceException { String image = "path to picture"; long creatureId = 1; long accountId = 1; Mockito.when(dao.updateUncheckedImageByCreatureId(Mockito.anyLong(),Mockito.anyLong(),Mockito.anyString())).thenReturn(true); boolean actual = service.changeUncheckedImage(creatureId,accountId,image); Assert.assertTrue(actual); } @Test public void changeUncheckedImageFalseTest() throws DaoException, ServiceException { String image = "path to picture"; long creatureId = 1; long accountId = 1; Mockito.when(dao.updateUncheckedImageByCreatureId(Mockito.anyLong(),Mockito.anyLong(),Mockito.anyString())).thenReturn(false); boolean actual = service.changeUncheckedImage(creatureId,accountId,image); Assert.assertFalse(actual); } @Test(dependsOnMethods = {"changeUncheckedImageTrueTest","changeUncheckedImageFalseTest"},expectedExceptions = ServiceException.class) public void changeUncheckedImageExceptionTest() throws DaoException, ServiceException { String image = "path to picture"; long creatureId = 1; long accountId = 1; Mockito.when(dao.updateUncheckedImageByCreatureId(Mockito.anyLong(),Mockito.anyLong(),Mockito.anyString())).thenThrow(new DaoException()); service.changeUncheckedImage(creatureId,accountId,image); } @Test(dataProvider = "creatureData") public void editCreatureTest(Creature creature,boolean expected) throws DaoException, ServiceException { Mockito.when(dao.update(creature)).thenReturn(true); boolean actual = service.editCreature(creature); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "editCreatureTest",expectedExceptions = ServiceException.class) public void editCreatureExceptionTest() throws DaoException, ServiceException { Creature creature = new Creature.CreatureBuilder().withName("test Name").withDescription("Test description").build(); Mockito.when(dao.update(creature)).thenThrow(new DaoException()); service.createCreature(creature); } @Test(dataProvider = "uncheckedCreatureData") public void editUncheckedCreatureTest(long accountId,Creature creature,boolean expected) throws DaoException, ServiceException { Mockito.when(dao.updateUncheckedCreature(Mockito.anyLong(),Mockito.eq(creature))).thenReturn(true); boolean actual = service.editUncheckedCreature(accountId,creature); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "editUncheckedCreatureTest",expectedExceptions = ServiceException.class) public void editUncheckedCreatureExceptionTest() throws DaoException, ServiceException { long accountId = 1; Creature creature = new Creature.CreatureBuilder().withName("test Name").withDescription("Test description").build(); Mockito.when(dao.updateUncheckedCreature(Mockito.anyLong(),Mockito.eq(creature))).thenThrow(new DaoException()); service.editUncheckedCreature(accountId,creature); } @Test public void deleteTrueTest() throws DaoException,ServiceException { long id = 1; Mockito.when(dao.delete(Mockito.anyLong())).thenReturn(true); boolean actual = service.delete(id); Assert.assertTrue(actual); } @Test public void deleteFalseTest() throws DaoException,ServiceException { long id = 1; Mockito.when(dao.delete(Mockito.anyLong())).thenReturn(false); boolean actual = service.delete(id); Assert.assertFalse(actual); } @Test(dependsOnMethods = {"deleteTrueTest","deleteFalseTest"},expectedExceptions = ServiceException.class) public void deleteExceptionTest() throws DaoException,ServiceException { long id = 1; Mockito.when(dao.delete(Mockito.anyLong())).thenThrow(new DaoException()); service.delete(id); } @Test public void deleteWithAccountIdTrueTest() throws DaoException,ServiceException { long accountId = 1; long creatureId = 1; Mockito.when(dao.delete(Mockito.anyLong(),Mockito.anyLong())).thenReturn(true); boolean actual = service.delete(accountId,creatureId); Assert.assertTrue(actual); } @Test public void deleteWithAccountIdFalseTest() throws DaoException,ServiceException { long accountId = 1; long creatureId = 1; Mockito.when(dao.delete(Mockito.anyLong(),Mockito.anyLong())).thenReturn(false); boolean actual = service.delete(accountId,creatureId); Assert.assertFalse(actual); } @Test(dependsOnMethods = {"deleteWithAccountIdTrueTest","deleteWithAccountIdFalseTest"},expectedExceptions = ServiceException.class) public void deleteWithAccountIdExceptionTest() throws DaoException,ServiceException { long accountId = 1; long creatureId = 1; Mockito.when(dao.delete(Mockito.anyLong(),Mockito.anyLong())).thenThrow(new DaoException()); service.delete(accountId,creatureId); } @Test public void findUserCreaturesTest() throws DaoException, ServiceException { long accountId = 1; List<Creature> expected = new ArrayList<>(); Mockito.when(dao.findCreaturesByAccountId(Mockito.anyLong())).thenReturn(expected); List<Creature> actual = service.findUserCreatures(accountId); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "findUserCreaturesTest",expectedExceptions = ServiceException.class) public void findUserCreaturesExceptionTest() throws DaoException, ServiceException { long accountId = 1; Mockito.when(dao.findCreaturesByAccountId(Mockito.anyLong())).thenThrow(new DaoException()); service.findUserCreatures(accountId); } @Test public void findUncheckedCreaturesTest() throws DaoException, ServiceException { List<Creature> expected = new ArrayList<>(); Mockito.when(dao.findUncheckedCreatures()).thenReturn(expected); List<Creature> actual = service.findUncheckedCreatures(); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "findUncheckedCreaturesTest",expectedExceptions = ServiceException.class) public void findUncheckedCreaturesExceptionTest() throws DaoException, ServiceException { Mockito.when(dao.findUncheckedCreatures()).thenThrow(new DaoException()); service.findUncheckedCreatures(); } @Test public void approveCreatureTrueTest() throws DaoException, ServiceException { long creatureId = 1; Mockito.when(dao.approveCreature(Mockito.anyLong())).thenReturn(true); boolean actual = service.approveCreature(creatureId); Assert.assertTrue(actual); } @Test public void approveCreatureFalseTest() throws DaoException, ServiceException { long creatureId = 1; Mockito.when(dao.approveCreature(Mockito.anyLong())).thenReturn(false); boolean actual = service.approveCreature(creatureId); Assert.assertFalse(actual); } @Test(dependsOnMethods = {"approveCreatureTrueTest","approveCreatureFalseTest"},expectedExceptions = ServiceException.class) public void approveCreatureExceptionTest() throws DaoException, ServiceException { long creatureId = 1; Mockito.when(dao.approveCreature(Mockito.anyLong())).thenThrow(new DaoException()); service.approveCreature(creatureId); } @Test public void searchTest() throws DaoException, ServiceException { String text = "search text"; List<Creature> expected = new ArrayList<>(); Mockito.when(dao.search(Mockito.anyString())).thenReturn(expected); List<Creature> actual = service.search(text); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "searchTest",expectedExceptions = ServiceException.class) public void searchExceptionTest() throws DaoException, ServiceException { String text = "search text"; Mockito.when(dao.search(Mockito.anyString())).thenThrow(new DaoException()); service.search(text); } @Test public void findUserSuggestedCreaturesTest() throws DaoException, ServiceException { long accountId = 1; List<Creature> expected = new ArrayList<>(); Mockito.when(dao.findUncheckedCreaturesByAccountId(Mockito.anyLong())).thenReturn(expected); List<Creature> actual = service.findUserSuggestedCreatures(accountId); Assert.assertEquals(actual,expected); } @Test(dependsOnMethods = "findUserSuggestedCreaturesTest",expectedExceptions = ServiceException.class) public void findUserSuggestedCreaturesExceptionTest() throws DaoException, ServiceException { long accountId = 1; Mockito.when(dao.findUncheckedCreaturesByAccountId(Mockito.anyLong())).thenThrow(new DaoException()); service.findUserSuggestedCreatures(accountId); } @AfterClass public void afterClass() throws Exception { MockitoAnnotations.openMocks(this).close(); } }
true
de9e8b2e155989cb8dd91018fe1347b5efe16907
Java
dayagz/petstore
/src/main/java/com/mypetstore/PetStore.java
UTF-8
2,698
3.125
3
[]
no_license
package com.mypetstore; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; public class PetStore { public static void main(String[] args) { try { Map<Parameter, String> params = processArgs(args); List<Pet> matchingPets = new PetsRepository(params.get(Parameter.file)).search(createSearchCriteria(params)); printSearchResults(matchingPets); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); printUsage(); System.exit(1); } catch (IOException e) { System.out.println("Error while accessing file:" + e.getMessage()); } } static Map<Parameter, String> processArgs(String[] args) throws FileNotFoundException{ Map<Parameter, String> params = new HashMap<>(); for (int i = 0; i < args.length; i += 2) { Parameter parameter = Enum.valueOf(Parameter.class, args[i].replace("-", "")); if (args.length - 1 == i) { throw new IllegalArgumentException(String.format("Value needed for %s", args[i])); } params.put(parameter, args[i + 1]); } if (!params.containsKey(Parameter.file)) { throw new IllegalArgumentException(String.format("Missing required argument: %s %n", Parameter.file.name())); } if (Files.notExists(Paths.get(params.get(Parameter.file)))) { throw new FileNotFoundException(String.format("File not found: %s %n", params.get(Parameter.file))); } return params; } private static void printUsage() { StringBuilder usageMessageBuilder = new StringBuilder("Usage: java ").append(PetStore.class.getSimpleName()).append(" "); for (Parameter parameter : Parameter.values()) { usageMessageBuilder.append(String.format("-%s <value> ", parameter.name())); } System.out.println(usageMessageBuilder.toString()); } private static Pet createSearchCriteria(Map<Parameter, String> params) { return new Pet(-1l, params.get(Parameter.name), params.get(Parameter.type), params.get(Parameter.gender), params.get(Parameter.zipcode)); } private static void printSearchResults(List<Pet> searchResults) { if (searchResults.isEmpty()) { System.out.println("No Pets found matching the search criteria!"); return; } System.out.println("Pets matching the search criteria:"); searchResults.forEach(System.out::println); } }
true
ccbbe611f1fa835a89c60e7a2a1d1ce468e7f271
Java
Meemaw/Insight
/backend/beacon/beacon-api/src/main/java/com/meemaw/rec/beacon/resource/v1/BeaconResource.java
UTF-8
947
2.046875
2
[]
no_license
package com.meemaw.rec.beacon.resource.v1; import com.meemaw.auth.organization.model.validation.OrganizationId; import java.util.UUID; import java.util.concurrent.CompletionStage; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path(BeaconResource.PATH) public interface BeaconResource { String PATH = "/v1/beacon"; @POST @Consumes({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON}) @Path("/beat") CompletionStage<Response> beacon( @OrganizationId @QueryParam("organizationId") String organizationId, @NotNull(message = "Required") @QueryParam("sessionId") UUID sessionId, @NotNull(message = "Required") @QueryParam("deviceId") UUID deviceId, @NotNull(message = "Required") @QueryParam("pageId") UUID pageId, String body); }
true
fddf0aec2b67ea9ab5e848d5663e349ae1882fdc
Java
NovaViper/DoggyTalents
/src-mc-1.11.2/doggytalents/item/ItemDT.java
UTF-8
251
1.8125
2
[]
no_license
package doggytalents.item; import doggytalents.api.DoggyTalentsAPI; import net.minecraft.item.Item; /** * @author ProPercivalalb **/ public class ItemDT extends Item { public ItemDT() { this.setCreativeTab(DoggyTalentsAPI.CREATIVE_TAB); } }
true
1cbbdc1a4a256171e22d65d3a91d0bb42031f367
Java
zhiqinghuang/zest-java
/core/runtime/src/test/java/org/qi4j/test/composite/CleanStackTraceTest.java
UTF-8
4,989
2.0625
2
[ "Apache-2.0", "BSD-3-Clause", "MIT", "W3C" ]
permissive
/* * Copyright (c) 2008, Rickard Öberg. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.qi4j.test.composite; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import org.junit.BeforeClass; import org.junit.Test; import org.qi4j.api.concern.Concerns; import org.qi4j.api.concern.GenericConcern; import org.qi4j.api.mixin.Mixins; import org.qi4j.bootstrap.AssemblyException; import org.qi4j.bootstrap.ModuleAssembly; import org.qi4j.test.AbstractQi4jTest; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; /** * Test if the stacktrace is cleaned up properly. * <p> * NOTE: This satisfiedBy MUST NOT be inside package org.qi4j.runtime, or it will fail. * </p> */ public class CleanStackTraceTest extends AbstractQi4jTest { @BeforeClass public static void beforeClass_IBMJDK() { assumeTrue( !( System.getProperty( "java.vendor" ).contains( "IBM" ) ) ); } @Override public void assemble( ModuleAssembly module ) throws AssemblyException { module.transients( CleanStackTraceTest.TestComposite.class ); } /** * Tests that stack trace is cleaned up on an application exception. */ @Test public void cleanStackTraceOnApplicationException() { // Don't run the satisfiedBy if compacttrace is set to anything else but proxy String compactTracePropertyValue = System.getProperty( "qi4j.compacttrace" ); if( compactTracePropertyValue != null && !"proxy".equals( compactTracePropertyValue ) ) { return; } TestComposite composite = module.newTransient( TestComposite.class ); try { composite.doStuff(); } catch( RuntimeException e ) { String separator = System.getProperty( "line.separator" ); String correctTrace1 = "java.lang.RuntimeException: level 2" + separator + "\tat org.qi4j.test.composite.CleanStackTraceTest$DoStuffMixin.doStuff(CleanStackTraceTest.java:122)" + separator + "\tat org.qi4j.test.composite.CleanStackTraceTest$NillyWilly.invoke(CleanStackTraceTest.java:135)" + separator + "\tat org.qi4j.test.composite.CleanStackTraceTest.cleanStackTraceOnApplicationException(CleanStackTraceTest.java:73)"; assertEquality( e, correctTrace1 ); String correctTrace2 = "java.lang.RuntimeException: level 1" + separator + "\tat org.qi4j.test.composite.CleanStackTraceTest$DoStuffMixin.doStuff(CleanStackTraceTest.java:118)" + separator + "\tat org.qi4j.test.composite.CleanStackTraceTest$NillyWilly.invoke(CleanStackTraceTest.java:135)" + separator + "\tat org.qi4j.test.composite.CleanStackTraceTest.cleanStackTraceOnApplicationException(CleanStackTraceTest.java:73)"; assertThat( e.getCause(), notNullValue() ); assertEquality( e.getCause(), correctTrace2 ); } } private void assertEquality( Throwable e, String correctTrace ) { StringWriter actualTrace = new StringWriter(); e.printStackTrace( new PrintWriter( actualTrace ) ); String actual = actualTrace.toString(); actual = actual.substring( 0, correctTrace.length() ); assertEquals( correctTrace, actual ); } @Concerns( NillyWilly.class ) @Mixins(DoStuffMixin.class) public interface TestComposite { void doStuff(); } public static class DoStuffMixin implements TestComposite { @Override public void doStuff() { try { throw new RuntimeException( "level 1" ); } catch( RuntimeException e ) { throw new RuntimeException( "level 2", e ); } } } static class NillyWilly extends GenericConcern implements InvocationHandler { @Override public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { return next.invoke( proxy, method, args ); } } }
true
c691bfdb45dd648609378920f45b68ca8ebeae0a
Java
joseeg23/libreria
/src/main/java/web/egg/libreria/repositorios/EditorialRepositorio.java
UTF-8
888
1.914063
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 web.egg.libreria.repositorios; import java.util.ArrayList; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import web.egg.libreria.entidades.Editorial; @Repository public interface EditorialRepositorio extends JpaRepository<Editorial, String> { @Query("Select A from Editorial A where A.nombre = :nombre") public Editorial buscarEditorialPorNombre(@Param ("nombre") String nombre); @Query("Select l from Editorial l where baja is false") public ArrayList<Editorial> listar(); }
true
c3e9eccf70dd9369a23349b1f083ea806379b22a
Java
irwindiho/SS_crmeducativo_v2
/app/src/main/java/com/consultoraestrategia/ss_crmeducativo/entities/RecursoDidacticoEvento.java
UTF-8
4,698
2.015625
2
[]
no_license
package com.consultoraestrategia.ss_crmeducativo.entities; import com.consultoraestrategia.ss_crmeducativo.lib.AppDatabase; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.annotation.Unique; import com.raizlabs.android.dbflow.structure.BaseModel; /** * Created by irvinmarin on 29/06/2017. */ @Table(database = AppDatabase.class) public class RecursoDidacticoEvento extends BaseModel { @Unique @PrimaryKey private int recursoDidacticoId; @Column private String titulo; @Column private String descripcion; @Column private int tipoId; @Column private int silaboEventoId; @Column private int unidadAprendizajeId; @Column private int sesionAprendizajeId; @Column private int actividadAprendizajeId; @Column private boolean estado; @Column private int usuarioCreador; @Column private String fechaCreacion; @Column private int usuarioAccion; @Column private String fechaAccion; @Column private int planCursoId; public RecursoDidacticoEvento() { } public RecursoDidacticoEvento(int recursoDidacticoId, String titulo, String descripcion, int tipoId, int silaboEventoId, int unidadAprendizajeId, int sesionAprendizajeId, int actividadAprendizajeId, boolean estado, int usuarioCreador, String fechaCreacion, int usuarioAccion, String fechaAccion, int planCursoId) { this.recursoDidacticoId = recursoDidacticoId; this.titulo = titulo; this.descripcion = descripcion; this.tipoId = tipoId; this.silaboEventoId = silaboEventoId; this.unidadAprendizajeId = unidadAprendizajeId; this.sesionAprendizajeId = sesionAprendizajeId; this.actividadAprendizajeId = actividadAprendizajeId; this.estado = estado; this.usuarioCreador = usuarioCreador; this.fechaCreacion = fechaCreacion; this.usuarioAccion = usuarioAccion; this.fechaAccion = fechaAccion; this.planCursoId = planCursoId; } public int getRecursoDidacticoId() { return recursoDidacticoId; } public void setRecursoDidacticoId(int recursoDidacticoId) { this.recursoDidacticoId = recursoDidacticoId; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getTipoId() { return tipoId; } public void setTipoId(int tipoId) { this.tipoId = tipoId; } public int getSilaboEventoId() { return silaboEventoId; } public void setSilaboEventoId(int silaboEventoId) { this.silaboEventoId = silaboEventoId; } public int getUnidadAprendizajeId() { return unidadAprendizajeId; } public void setUnidadAprendizajeId(int unidadAprendizajeId) { this.unidadAprendizajeId = unidadAprendizajeId; } public int getSesionAprendizajeId() { return sesionAprendizajeId; } public void setSesionAprendizajeId(int sesionAprendizajeId) { this.sesionAprendizajeId = sesionAprendizajeId; } public int getActividadAprendizajeId() { return actividadAprendizajeId; } public void setActividadAprendizajeId(int actividadAprendizajeId) { this.actividadAprendizajeId = actividadAprendizajeId; } public boolean isEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public int getUsuarioCreador() { return usuarioCreador; } public void setUsuarioCreador(int usuarioCreador) { this.usuarioCreador = usuarioCreador; } public String getFechaCreacion() { return fechaCreacion; } public void setFechaCreacion(String fechaCreacion) { this.fechaCreacion = fechaCreacion; } public int getUsuarioAccion() { return usuarioAccion; } public void setUsuarioAccion(int usuarioAccion) { this.usuarioAccion = usuarioAccion; } public String getFechaAccion() { return fechaAccion; } public void setFechaAccion(String fechaAccion) { this.fechaAccion = fechaAccion; } public int getPlanCursoId() { return planCursoId; } public void setPlanCursoId(int planCursoId) { this.planCursoId = planCursoId; } }
true
578f8e76d90bf670debdd1ac2e1bebd3e23d415b
Java
karthik-git-user/SAP-Stage
/core-customize/hybris/bin/modules/sap-customerlookup/sapcpicustomerexchangemdm/src/de/hybris/platform/sap/sapcpicustomerexchangemdm/inbound/SapMDMCustomerImportService.java
UTF-8
616
1.898438
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. */ package de.hybris.platform.sap.sapcpicustomerexchangemdm.inbound; import de.hybris.platform.core.model.user.CustomerModel; /** * SapMDMCustomerImportService Handles Customer In Bound Object Processing */ public interface SapMDMCustomerImportService { /** * Process the In Bound Message of Consumer Creation Notification From Back End * * @param sapCpiInboundCustomerModel - Inbound customer model */ public void processConsumerReplicationNotificationFromMDM(final CustomerModel sapCpiInboundCustomerModel); }
true
91e7da2afa732cb8a18cbe42c41dc09a088df04f
Java
google/j2objc
/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/HashMap.java
UTF-8
101,073
2.203125
2
[ "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-taligent-jdk", "LicenseRef-scancode-proprietary-license", "Classpath-exception-2.0", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "APSL-1.0", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-generic-exception", "LicenseRef-scancode-red-hat-attribution", "ICU", "MIT", "CPL-1.0", "NAIST-2003", "GPL-2.0-or-later", "APSL-2.0", "LicenseRef-scancode-oracle-openjdk-exception-2.0", "SunPro", "W3C", "LicenseRef-scancode-generic-cla", "W3C-19980720" ]
permissive
/* * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import com.google.j2objc.annotations.Weak; import com.google.j2objc.annotations.WeakOuter; import java.io.IOException; import java.io.InvalidObjectException; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; /*-[ #include "JreRetainedWith.h" ]-*/ /** * Hash table based implementation of the {@code Map} interface. This * implementation provides all of the optional map operations, and permits * {@code null} values and the {@code null} key. (The {@code HashMap} * class is roughly equivalent to {@code Hashtable}, except that it is * unsynchronized and permits nulls.) This class makes no guarantees as to * the order of the map; in particular, it does not guarantee that the order * will remain constant over time. * * <p>This implementation provides constant-time performance for the basic * operations ({@code get} and {@code put}), assuming the hash function * disperses the elements properly among the buckets. Iteration over * collection views requires time proportional to the "capacity" of the * {@code HashMap} instance (the number of buckets) plus its size (the number * of key-value mappings). Thus, it's very important not to set the initial * capacity too high (or the load factor too low) if iteration performance is * important. * * <p>An instance of {@code HashMap} has two parameters that affect its * performance: <i>initial capacity</i> and <i>load factor</i>. The * <i>capacity</i> is the number of buckets in the hash table, and the initial * capacity is simply the capacity at the time the hash table is created. The * <i>load factor</i> is a measure of how full the hash table is allowed to * get before its capacity is automatically increased. When the number of * entries in the hash table exceeds the product of the load factor and the * current capacity, the hash table is <i>rehashed</i> (that is, internal data * structures are rebuilt) so that the hash table has approximately twice the * number of buckets. * * <p>As a general rule, the default load factor (.75) offers a good * tradeoff between time and space costs. Higher values decrease the * space overhead but increase the lookup cost (reflected in most of * the operations of the {@code HashMap} class, including * {@code get} and {@code put}). The expected number of entries in * the map and its load factor should be taken into account when * setting its initial capacity, so as to minimize the number of * rehash operations. If the initial capacity is greater than the * maximum number of entries divided by the load factor, no rehash * operations will ever occur. * * <p>If many mappings are to be stored in a {@code HashMap} * instance, creating it with a sufficiently large capacity will allow * the mappings to be stored more efficiently than letting it perform * automatic rehashing as needed to grow the table. Note that using * many keys with the same {@code hashCode()} is a sure way to slow * down performance of any hash table. To ameliorate impact, when keys * are {@link Comparable}, this class may use comparison order among * keys to help break ties. * * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a hash map concurrently, and at least one of * the threads modifies the map structurally, it <i>must</i> be * synchronized externally. (A structural modification is any operation * that adds or deletes one or more mappings; merely changing the value * associated with a key that an instance already contains is not a * structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the map. * * If no such object exists, the map should be "wrapped" using the * {@link Collections#synchronizedMap Collections.synchronizedMap} * method. This is best done at creation time, to prevent accidental * unsynchronized access to the map:<pre> * Map m = Collections.synchronizedMap(new HashMap(...));</pre> * * <p>The iterators returned by all of this class's "collection view methods" * are <i>fail-fast</i>: if the map is structurally modified at any time after * the iterator is created, in any way except through the iterator's own * {@code remove} method, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class is a member of the * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework"> * Java Collections Framework</a>. * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Doug Lea * @author Josh Bloch * @author Arthur van Hoff * @author Neal Gafter * @see Object#hashCode() * @see Collection * @see Map * @see TreeMap * @see Hashtable * @since 1.2 */ public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { @java.io.Serial private static final long serialVersionUID = 362498820763181265L; /* * Implementation notes. * * This map usually acts as a binned (bucketed) hash table, but * when bins get too large, they are transformed into bins of * TreeNodes, each structured similarly to those in * java.util.TreeMap. Most methods try to use normal bins, but * relay to TreeNode methods when applicable (simply by checking * instanceof a node). Bins of TreeNodes may be traversed and * used like any others, but additionally support faster lookup * when overpopulated. However, since the vast majority of bins in * normal use are not overpopulated, checking for existence of * tree bins may be delayed in the course of table methods. * * Tree bins (i.e., bins whose elements are all TreeNodes) are * ordered primarily by hashCode, but in the case of ties, if two * elements are of the same "class C implements Comparable<C>", * type then their compareTo method is used for ordering. (We * conservatively check generic types via reflection to validate * this -- see method comparableClassFor). The added complexity * of tree bins is worthwhile in providing worst-case O(log n) * operations when keys either have distinct hashes or are * orderable, Thus, performance degrades gracefully under * accidental or malicious usages in which hashCode() methods * return values that are poorly distributed, as well as those in * which many keys share a hashCode, so long as they are also * Comparable. (If neither of these apply, we may waste about a * factor of two in time and space compared to taking no * precautions. But the only known cases stem from poor user * programming practices that are already so slow that this makes * little difference.) * * Because TreeNodes are about twice the size of regular nodes, we * use them only when bins contain enough nodes to warrant use * (see TREEIFY_THRESHOLD). And when they become too small (due to * removal or resizing) they are converted back to plain bins. In * usages with well-distributed user hashCodes, tree bins are * rarely used. Ideally, under random hashCodes, the frequency of * nodes in bins follows a Poisson distribution * (http://en.wikipedia.org/wiki/Poisson_distribution) with a * parameter of about 0.5 on average for the default resizing * threshold of 0.75, although with a large variance because of * resizing granularity. Ignoring variance, the expected * occurrences of list size k are (exp(-0.5) * pow(0.5, k) / * factorial(k)). The first values are: * * 0: 0.60653066 * 1: 0.30326533 * 2: 0.07581633 * 3: 0.01263606 * 4: 0.00157952 * 5: 0.00015795 * 6: 0.00001316 * 7: 0.00000094 * 8: 0.00000006 * more: less than 1 in ten million * * The root of a tree bin is normally its first node. However, * sometimes (currently only upon Iterator.remove), the root might * be elsewhere, but can be recovered following parent links * (method TreeNode.root()). * * All applicable internal methods accept a hash code as an * argument (as normally supplied from a public method), allowing * them to call each other without recomputing user hashCodes. * Most internal methods also accept a "tab" argument, that is * normally the current table, but may be a new or old one when * resizing or converting. * * When bin lists are treeified, split, or untreeified, we keep * them in the same relative access/traversal order (i.e., field * Node.next) to better preserve locality, and to slightly * simplify handling of splits and traversals that invoke * iterator.remove. When using comparators on insertion, to keep a * total ordering (or as close as is required here) across * rebalancings, we compare classes and identityHashCodes as * tie-breakers. * * The use and transitions among plain vs tree modes is * complicated by the existence of subclass LinkedHashMap. See * below for hook methods defined to be invoked upon insertion, * removal and access that allow LinkedHashMap internals to * otherwise remain independent of these mechanics. (This also * requires that a map instance be passed to some utility methods * that may create new nodes.) * * The concurrent-programming-like SSA-based coding style helps * avoid aliasing errors amid all of the twisty pointer operations. */ /** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */ static final int TREEIFY_THRESHOLD = 8; /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6; /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; /** * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; // BEGIN Android-changed: Patternmatching for instanceof is not available yet. /* return o instanceof Map.Entry<?, ?> e && Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue()); */ if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; // END Android-changed: Patternmatching for instanceof is not available yet. } } /* ---------------- Static utilities -------------- */ /** * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds. */ static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } /** * Returns x's Class if it is of the form "class C implements * Comparable<C>", else null. */ static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) { Class<?> c; Type[] ts, as; ParameterizedType p; if ((c = x.getClass()) == String.class) // bypass checks return c; if ((ts = c.getGenericInterfaces()) != null) { for (Type t : ts) { if ((t instanceof ParameterizedType) && ((p = (ParameterizedType) t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) // type arg is c return c; } } } return null; } /** * Returns k.compareTo(x) if x matches kc (k's screened comparable * class), else 0. */ @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); } /** * Returns a power of two size for the given target capacity. */ static final int tableSizeFor(int cap) { int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1); return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } /* ---------------- Fields -------------- */ /** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size; /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ transient int modCount; /** * The next size value at which to resize (capacity * load factor). * * @serial */ // (The javadoc description is true upon serialization. // Additionally, if the table array has not been allocated, this // field holds the initial array capacity, or zero signifying // DEFAULT_INITIAL_CAPACITY.) int threshold; /** * The load factor for the hash table. * * @serial */ final float loadFactor; /* ---------------- Public operations -------------- */ /** * Constructs an empty {@code HashMap} with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); } /** * Constructs an empty {@code HashMap} with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs an empty {@code HashMap} with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } /** * Constructs a new {@code HashMap} with the same mappings as the * specified {@code Map}. The {@code HashMap} is created with * default load factor (0.75) and an initial capacity sufficient to * hold the mappings in the specified {@code Map}. * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } /** * Implements Map.putAll and Map constructor. * * @param m the map * @param evict false when initially constructing this map, else * true (relayed to method afterNodeInsertion). */ final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); if (s > 0) { if (table == null) { // pre-size float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); } else { // Because of linked-list bucket constraints, we cannot // expand all at once, but can reduce total resize // effort by repeated doubling now vs later while (s > threshold && table.length < MAXIMUM_CAPACITY) resize(); } for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); } } } /** * Returns the number of key-value mappings in this map. * * @return the number of key-value mappings in this map */ public int size() { return size; } /** * Returns {@code true} if this map contains no key-value mappings. * * @return {@code true} if this map contains no key-value mappings */ public boolean isEmpty() { return size == 0; } /** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key) { Node<K,V> e; return (e = getNode(key)) == null ? null : e.value; } /** * Implements Map.get and related methods. * * @param key the key * @return the node, or null if none */ final Node<K,V> getNode(Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & (hash = hash(key))]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } /** * Returns {@code true} if this map contains a mapping for the * specified key. * * @param key The key whose presence in this map is to be tested * @return {@code true} if this map contains a mapping for the specified * key. */ public boolean containsKey(Object key) { return getNode(key) != null; } /** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with {@code key}, or * {@code null} if there was no mapping for {@code key}. * (A {@code null} return can also indicate that the map * previously associated {@code null} with {@code key}.) */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } /** * Implements Map.put and related methods. * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; } /** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */ final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; } /** * Replaces all linked nodes in bin at index for given hash unless * table is too small, in which case resizes instead. */ final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } } /** * Copies all of the mappings from the specified map to this map. * These mappings will replace any mappings that this map had for * any of the keys currently in the specified map. * * @param m mappings to be stored in this map * @throws NullPointerException if the specified map is null */ public void putAll(Map<? extends K, ? extends V> m) { putMapEntries(m, true); } /** * Removes the mapping for the specified key from this map if present. * * @param key key whose mapping is to be removed from the map * @return the previous value associated with {@code key}, or * {@code null} if there was no mapping for {@code key}. * (A {@code null} return can also indicate that the map * previously associated {@code null} with {@code key}.) */ public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } /** * Implements Map.remove and related methods. * * @param hash hash for key * @param key the key * @param value the value to match if matchValue, else ignored * @param matchValue if true only remove if value is equal * @param movable if false do not move other nodes while removing * @return the node, or null if none */ final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node<K,V> node = null, e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) { if (p instanceof TreeNode) node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; } /** * Removes all of the mappings from this map. * The map will be empty after this call returns. */ public void clear() { Node<K,V>[] tab; modCount++; if ((tab = table) != null && size > 0) { size = 0; for (int i = 0; i < tab.length; ++i) tab[i] = null; } } /** * Returns {@code true} if this map maps one or more keys to the * specified value. * * @param value value whose presence in this map is to be tested * @return {@code true} if this map maps one or more keys to the * specified value */ public boolean containsValue(Object value) { Node<K,V>[] tab; V v; if ((tab = table) != null && size > 0) { for (Node<K,V> e : tab) { for (; e != null; e = e.next) { if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false; } /** * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator's own {@code remove} operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * {@code Iterator.remove}, {@code Set.remove}, * {@code removeAll}, {@code retainAll}, and {@code clear} * operations. It does not support the {@code add} or {@code addAll} * operations. * * @return a set view of the keys contained in this map */ public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; } /** * Prepares the array for {@link Collection#toArray(Object[])} implementation. * If supplied array is smaller than this map size, a new array is allocated. * If supplied array is bigger than this map size, a null is written at size index. * * @param a an original array passed to {@code toArray()} method * @param <T> type of array elements * @return an array ready to be filled and returned from {@code toArray()} method. */ @SuppressWarnings("unchecked") final <T> T[] prepareArray(T[] a) { int size = this.size; if (a.length < size) { return (T[]) java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); } if (a.length > size) { a[size] = null; } return a; } /** * Fills an array with this map keys and returns it. This method assumes * that input array is big enough to fit all the keys. Use * {@link #prepareArray(Object[])} to ensure this. * * @param a an array to fill * @param <T> type of array elements * @return supplied array */ <T> T[] keysToArray(T[] a) { Object[] r = a; Node<K,V>[] tab; int idx = 0; if (size > 0 && (tab = table) != null) { for (Node<K,V> e : tab) { for (; e != null; e = e.next) { r[idx++] = e.key; } } } return a; } /** * Fills an array with this map values and returns it. This method assumes * that input array is big enough to fit all the values. Use * {@link #prepareArray(Object[])} to ensure this. * * @param a an array to fill * @param <T> type of array elements * @return supplied array */ <T> T[] valuesToArray(T[] a) { Object[] r = a; Node<K,V>[] tab; int idx = 0; if (size > 0 && (tab = table) != null) { for (Node<K,V> e : tab) { for (; e != null; e = e.next) { r[idx++] = e.value; } } } return a; } @WeakOuter final class KeySet extends AbstractSet<K> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<K> iterator() { return new KeyIterator(); } public final boolean contains(Object o) { return containsKey(o); } public final boolean remove(Object key) { return removeNode(hash(key), key, null, false, true) != null; } public final Spliterator<K> spliterator() { return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0); } public Object[] toArray() { return keysToArray(new Object[size]); } public <T> T[] toArray(T[] a) { return keysToArray(prepareArray(a)); } public final void forEach(Consumer<? super K> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { NSUInteger objCount = [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; for (id *e = state->itemsPtr, *end = e + objCount; e < end; e++) { *e = ((JavaUtilHashMap_Node *) *e)->key_; } return objCount; } RETAINED_WITH_CHILD(this$0_) ]-*/ } /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own {@code remove} operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the {@code Iterator.remove}, * {@code Collection.remove}, {@code removeAll}, * {@code retainAll} and {@code clear} operations. It does not * support the {@code add} or {@code addAll} operations. * * @return a view of the values contained in this map */ public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; } @WeakOuter final class Values extends AbstractCollection<V> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<V> iterator() { return new ValueIterator(); } public final boolean contains(Object o) { return containsValue(o); } public final Spliterator<V> spliterator() { return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0); } public Object[] toArray() { return valuesToArray(new Object[size]); } public <T> T[] toArray(T[] a) { return valuesToArray(prepareArray(a)); } public final void forEach(Consumer<? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { NSUInteger objCount = [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; for (id *e = state->itemsPtr, *end = e + objCount; e < end; e++) { *e = ((JavaUtilHashMap_Node *) *e)->value_; } return objCount; } RETAINED_WITH_CHILD(this$0_) ]-*/ } /** * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator's own {@code remove} operation, or through the * {@code setValue} operation on a map entry returned by the * iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding * mapping from the map, via the {@code Iterator.remove}, * {@code Set.remove}, {@code removeAll}, {@code retainAll} and * {@code clear} operations. It does not support the * {@code add} or {@code addAll} operations. * * @return a set view of the mappings contained in this map */ public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; } @WeakOuter final class EntrySet extends AbstractSet<Map.Entry<K,V>> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { // BEGIN Android-changed: Patternmatching for instanceof is not available yet. /* if (!(o instanceof Map.Entry<?, ?> e)) */ if (!(o instanceof Map.Entry)) // END Android-changed: Patternmatching for instanceof is not available yet. return false; Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Node<K,V> candidate = getNode(key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { // BEGIN Android-changed: Patternmatching for instanceof is not available yet. /* if (o instanceof Map.Entry<?, ?> e) { */ if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>) o; // END Android-changed: Patternmatching for instanceof is not available yet. Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator<Map.Entry<K,V>> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super Map.Entry<K,V>> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && modCount == mc); ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } /*-[ - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len]; } RETAINED_WITH_CHILD(this$0_) ]-*/ } // Overrides of JDK8 Map extension methods @Override public V getOrDefault(Object key, V defaultValue) { Node<K,V> e; return (e = getNode(key)) == null ? defaultValue : e.value; } @Override public V putIfAbsent(K key, V value) { return putVal(hash(key), key, value, true, true); } @Override public boolean remove(Object key, Object value) { return removeNode(hash(key), key, value, true, true) != null; } @Override public boolean replace(K key, V oldValue, V newValue) { Node<K,V> e; V v; if ((e = getNode(key)) != null && ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) { e.value = newValue; afterNodeAccess(e); return true; } return false; } @Override public V replace(K key, V value) { Node<K,V> e; if ((e = getNode(key)) != null) { V oldValue = e.value; e.value = value; afterNodeAccess(e); return oldValue; } return null; } /** * {@inheritDoc} * * <p>This method will, on a best-effort basis, throw a * {@link ConcurrentModificationException} if it is detected that the * mapping function modifies this map during computation. * * @throws ConcurrentModificationException if it is detected that the * mapping function modified this map */ @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { if (mappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } V oldValue; if (old != null && (oldValue = old.value) != null) { afterNodeAccess(old); return oldValue; } } int mc = modCount; V v = mappingFunction.apply(key); if (mc != modCount) { throw new ConcurrentModificationException(); } if (v == null) { return null; } else if (old != null) { old.value = v; afterNodeAccess(old); return v; } else if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } modCount = mc + 1; ++size; afterNodeInsertion(true); return v; } /** * {@inheritDoc} * * <p>This method will, on a best-effort basis, throw a * {@link ConcurrentModificationException} if it is detected that the * remapping function modifies this map during computation. * * @throws ConcurrentModificationException if it is detected that the * remapping function modified this map */ @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); Node<K,V> e; V oldValue; if ((e = getNode(key)) != null && (oldValue = e.value) != null) { int mc = modCount; V v = remappingFunction.apply(key, oldValue); if (mc != modCount) { throw new ConcurrentModificationException(); } if (v != null) { e.value = v; afterNodeAccess(e); return v; } else { int hash = hash(key); removeNode(hash, key, null, false, true); } } return null; } /** * {@inheritDoc} * * <p>This method will, on a best-effort basis, throw a * {@link ConcurrentModificationException} if it is detected that the * remapping function modifies this map during computation. * * @throws ConcurrentModificationException if it is detected that the * remapping function modified this map */ @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } V oldValue = (old == null) ? null : old.value; int mc = modCount; V v = remappingFunction.apply(key, oldValue); if (mc != modCount) { throw new ConcurrentModificationException(); } if (old != null) { if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); } else if (v != null) { if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } modCount = mc + 1; ++size; afterNodeInsertion(true); } return v; } /** * {@inheritDoc} * * <p>This method will, on a best-effort basis, throw a * {@link ConcurrentModificationException} if it is detected that the * remapping function modifies this map during computation. * * @throws ConcurrentModificationException if it is detected that the * remapping function modified this map */ @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null || remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } if (old != null) { V v; if (old.value != null) { int mc = modCount; v = remappingFunction.apply(old.value, value); if (mc != modCount) { throw new ConcurrentModificationException(); } } else { v = value; } if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); return v; } else { if (t != null) t.putTreeVal(this, tab, hash, key, value); else { tab[i] = newNode(hash, key, value, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); return value; } } @Override public void forEach(BiConsumer<? super K, ? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; // Android-changed: Detect changes to modCount early. for (int i = 0; (i < tab.length && mc == modCount); ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key, e.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Node<K,V>[] tab; if (function == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (Node<K,V> e : tab) { for (; e != null; e = e.next) { e.value = function.apply(e.key, e.value); } } if (modCount != mc) throw new ConcurrentModificationException(); } } /* ------------------------------------------------------------ */ // Cloning and serialization /** * Returns a shallow copy of this {@code HashMap} instance: the keys and * values themselves are not cloned. * * @return a shallow copy of this map */ @SuppressWarnings("unchecked") @Override public Object clone() { HashMap<K,V> result; try { result = (HashMap<K,V>)super.clone(); } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } result.reinitialize(); result.putMapEntries(this, false); return result; } // These methods are also used when serializing HashSets final float loadFactor() { return loadFactor; } final int capacity() { return (table != null) ? table.length : (threshold > 0) ? threshold : DEFAULT_INITIAL_CAPACITY; } /** * Saves this map to a stream (that is, serializes it). * * @param s the stream * @throws IOException if an I/O error occurs * @serialData The <i>capacity</i> of the HashMap (the length of the * bucket array) is emitted (int), followed by the * <i>size</i> (an int, the number of key-value * mappings), followed by the key (Object) and value (Object) * for each key-value mapping. The key-value mappings are * emitted in no particular order. */ @java.io.Serial private void writeObject(java.io.ObjectOutputStream s) throws IOException { int buckets = capacity(); // Write out the threshold, loadfactor, and any hidden stuff s.defaultWriteObject(); s.writeInt(buckets); s.writeInt(size); internalWriteEntries(s); } /** * Reconstitute the {@code HashMap} instance from a stream (i.e., * deserialize it). */ private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the threshold (ignored), loadfactor, and any hidden stuff s.defaultReadObject(); reinitialize(); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new InvalidObjectException("Illegal load factor: " + loadFactor); s.readInt(); // Read and ignore number of buckets int mappings = s.readInt(); // Read number of mappings (size) if (mappings < 0) throw new InvalidObjectException("Illegal mappings count: " + mappings); else if (mappings > 0) { // (if zero, use defaults) // Size the table using given load factor only if within // range of 0.25...4.0 float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f); float fc = (float)mappings / lf + 1.0f; int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ? DEFAULT_INITIAL_CAPACITY : (fc >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int)fc)); float ft = (float)cap * lf; threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ? (int)ft : Integer.MAX_VALUE); @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] tab = (Node<K,V>[])new Node[cap]; table = tab; // Read the keys and values, and put the mappings in the HashMap for (int i = 0; i < mappings; i++) { @SuppressWarnings("unchecked") K key = (K) s.readObject(); @SuppressWarnings("unchecked") V value = (V) s.readObject(); putVal(hash(key), key, value, false, false); } } } /* ------------------------------------------------------------ */ // iterators @WeakOuter abstract class HashIterator { Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; if (t != null && size > 0) { // advance to first entry do {} while (index < t.length && (next = t[index++]) == null); } } public final boolean hasNext() { return next != null; } final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; } public final void remove() { Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; removeNode(p.hash, p.key, null, false, false); expectedModCount = modCount; } } final class KeyIterator extends HashIterator implements Iterator<K> { public final K next() { return nextNode().key; } } final class ValueIterator extends HashIterator implements Iterator<V> { public final V next() { return nextNode().value; } } final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); } } /* ------------------------------------------------------------ */ // spliterators static class HashMapSpliterator<K,V> { final HashMap<K,V> map; Node<K,V> current; // current node int index; // current index, modified on advance/split int fence; // one past last index int est; // size estimate int expectedModCount; // for comodification checks HashMapSpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { this.map = m; this.index = origin; this.fence = fence; this.est = est; this.expectedModCount = expectedModCount; } final int getFence() { // initialize fence and size on first use int hi; if ((hi = fence) < 0) { HashMap<K,V> m = map; est = m.size; expectedModCount = m.modCount; Node<K,V>[] tab = m.table; hi = fence = (tab == null) ? 0 : tab.length; } return hi; } public final long estimateSize() { getFence(); // force init return (long) est; } } static final class KeySpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<K> { KeySpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount); } public KeySpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new KeySpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super K> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p.key); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super K> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { K k = current.key; current = current.next; action.accept(k); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) | Spliterator.DISTINCT; } } static final class ValueSpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<V> { ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount); } public ValueSpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new ValueSpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super V> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p.value); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super V> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { V v = current.value; current = current.next; action.accept(v); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0); } } static final class EntrySpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<Map.Entry<K,V>> { EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount); } public EntrySpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new EntrySpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { Node<K,V> e = current; current = current.next; action.accept(e); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) | Spliterator.DISTINCT; } } /* ------------------------------------------------------------ */ // LinkedHashMap support /* * The following package-protected methods are designed to be * overridden by LinkedHashMap, but not by any other subclass. * Nearly all other internal methods are also package-protected * but are declared final, so can be used by LinkedHashMap, view * classes, and HashSet. */ // Create a regular (non-tree) node Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next); } // For conversion from TreeNodes to plain nodes Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) { return new Node<>(p.hash, p.key, p.value, next); } // Create a tree bin node TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) { return new TreeNode<>(hash, key, value, next); } // For treeifyBin TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) { return new TreeNode<>(p.hash, p.key, p.value, next); } /** * Reset to initial default state. Called by clone and readObject. */ void reinitialize() { table = null; entrySet = null; keySet = null; values = null; modCount = 0; threshold = 0; size = 0; } // Callbacks to allow LinkedHashMap post-actions void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { } // Called only from writeObject, to ensure compatible ordering. void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException { Node<K,V>[] tab; if (size > 0 && (tab = table) != null) { for (Node<K,V> e : tab) { for (; e != null; e = e.next) { s.writeObject(e.key); s.writeObject(e.value); } } } } /* ------------------------------------------------------------ */ // Tree bins /** * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */ static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<K,V> { @Weak TreeNode<K,V> parent; // red-black tree links @Weak TreeNode<K,V> left; @Weak TreeNode<K,V> right; @Weak TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } /** * Returns root of tree containing this node. */ final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } /** * Ensures that the given root is the first node of its bin. */ static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) { int n; if (root != null && tab != null && (n = tab.length) > 0) { int index = (n - 1) & root.hash; TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; if (root != first) { Node<K,V> rn; tab[index] = root; TreeNode<K,V> rp = root.prev; if ((rn = root.next) != null) ((TreeNode<K,V>)rn).prev = rp; if (rp != null) rp.next = rn; if (first != null) first.prev = root; root.next = first; root.prev = null; } assert checkInvariants(root); } } /** * Finds the node starting at root p with the given hash and key. * The kc argument caches comparableClassFor(key) upon first use * comparing keys. */ final TreeNode<K,V> find(int h, Object k, Class<?> kc) { TreeNode<K,V> p = this; do { int ph, dir; K pk; TreeNode<K,V> pl = p.left, pr = p.right, q; if ((ph = p.hash) > h) p = pl; else if (ph < h) p = pr; else if ((pk = p.key) == k || (k != null && k.equals(pk))) return p; else if (pl == null) p = pr; else if (pr == null) p = pl; else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0) p = (dir < 0) ? pl : pr; else if ((q = pr.find(h, k, kc)) != null) return q; else p = pl; } while (p != null); return null; } /** * Calls find for root node. */ final TreeNode<K,V> getTreeNode(int h, Object k) { return ((parent != null) ? root() : this).find(h, k, null); } /** * Tie-breaking utility for ordering insertions when equal * hashCodes and non-comparable. We don't require a total * order, just a consistent insertion rule to maintain * equivalence across rebalancings. Tie-breaking further than * necessary simplifies testing a bit. */ static int tieBreakOrder(Object a, Object b) { int d; if (a == null || b == null || (d = a.getClass().getName(). compareTo(b.getClass().getName())) == 0) d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1); return d; } /** * Forms tree of the nodes linked from this node. */ final void treeify(Node<K,V>[] tab) { TreeNode<K,V> root = null; for (TreeNode<K,V> x = this, next; x != null; x = next) { next = (TreeNode<K,V>)x.next; x.left = x.right = null; if (root == null) { x.parent = null; x.red = false; root = x; } else { K k = x.key; int h = x.hash; Class<?> kc = null; for (TreeNode<K,V> p = root;;) { int dir, ph; K pk = p.key; if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) dir = tieBreakOrder(k, pk); TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { x.parent = xp; if (dir <= 0) xp.left = x; else xp.right = x; root = balanceInsertion(root, x); break; } } } } moveRootToFront(tab, root); } /** * Returns a list of non-TreeNodes replacing those linked from * this node. */ final Node<K,V> untreeify(HashMap<K,V> map) { Node<K,V> hd = null, tl = null; for (Node<K,V> q = this; q != null; q = q.next) { Node<K,V> p = map.replacementNode(q, null); if (tl == null) hd = p; else tl.next = p; tl = p; } return hd; } /** * Tree version of putVal. */ final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab, int h, K k, V v) { Class<?> kc = null; boolean searched = false; TreeNode<K,V> root = (parent != null) ? root() : this; for (TreeNode<K,V> p = root;;) { int dir, ph; K pk; if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((pk = p.key) == k || (k != null && k.equals(pk))) return p; else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) { if (!searched) { TreeNode<K,V> q, ch; searched = true; if (((ch = p.left) != null && (q = ch.find(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.find(h, k, kc)) != null)) return q; } dir = tieBreakOrder(k, pk); } TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { Node<K,V> xpn = xp.next; TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn); if (dir <= 0) xp.left = x; else xp.right = x; xp.next = x; x.parent = x.prev = xp; if (xpn != null) ((TreeNode<K,V>)xpn).prev = x; moveRootToFront(tab, balanceInsertion(root, x)); return null; } } } /** * Removes the given node, that must be present before this call. * This is messier than typical red-black deletion code because we * cannot swap the contents of an interior node with a leaf * successor that is pinned by "next" pointers that are accessible * independently during traversal. So instead we swap the tree * linkages. If the current tree appears to have too few nodes, * the bin is converted back to a plain bin. (The test triggers * somewhere between 2 and 6 nodes, depending on tree structure). */ final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab, boolean movable) { int n; if (tab == null || (n = tab.length) == 0) return; int index = (n - 1) & hash; TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl; TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev; if (pred == null) tab[index] = first = succ; else pred.next = succ; if (succ != null) succ.prev = pred; if (first == null) return; if (root.parent != null) root = root.root(); if (root == null || (movable && (root.right == null || (rl = root.left) == null || rl.left == null))) { tab[index] = first.untreeify(map); // too small return; } TreeNode<K,V> p = this, pl = left, pr = right, replacement; if (pl != null && pr != null) { TreeNode<K,V> s = pr, sl; while ((sl = s.left) != null) // find successor s = sl; boolean c = s.red; s.red = p.red; p.red = c; // swap colors TreeNode<K,V> sr = s.right; TreeNode<K,V> pp = p.parent; if (s == pr) { // p was s's direct parent p.parent = s; s.right = p; } else { TreeNode<K,V> sp = s.parent; if ((p.parent = sp) != null) { if (s == sp.left) sp.left = p; else sp.right = p; } if ((s.right = pr) != null) pr.parent = s; } p.left = null; if ((p.right = sr) != null) sr.parent = p; if ((s.left = pl) != null) pl.parent = s; if ((s.parent = pp) == null) root = s; else if (p == pp.left) pp.left = s; else pp.right = s; if (sr != null) replacement = sr; else replacement = p; } else if (pl != null) replacement = pl; else if (pr != null) replacement = pr; else replacement = p; if (replacement != p) { TreeNode<K,V> pp = replacement.parent = p.parent; if (pp == null) (root = replacement).red = false; else if (p == pp.left) pp.left = replacement; else pp.right = replacement; p.left = p.right = p.parent = null; } TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement); if (replacement == p) { // detach TreeNode<K,V> pp = p.parent; p.parent = null; if (pp != null) { if (p == pp.left) pp.left = null; else if (p == pp.right) pp.right = null; } } if (movable) moveRootToFront(tab, r); } /** * Splits nodes in a tree bin into lower and upper tree bins, * or untreeifies if now too small. Called only from resize; * see above discussion about split bits and indices. * * @param map the map * @param tab the table for recording bin heads * @param index the index of the table being split * @param bit the bit of hash to split on */ final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) { TreeNode<K,V> b = this; // Relink into lo and hi lists, preserving order TreeNode<K,V> loHead = null, loTail = null; TreeNode<K,V> hiHead = null, hiTail = null; int lc = 0, hc = 0; for (TreeNode<K,V> e = b, next; e != null; e = next) { next = (TreeNode<K,V>)e.next; e.next = null; if ((e.hash & bit) == 0) { if ((e.prev = loTail) == null) loHead = e; else loTail.next = e; loTail = e; ++lc; } else { if ((e.prev = hiTail) == null) hiHead = e; else hiTail.next = e; hiTail = e; ++hc; } } if (loHead != null) { if (lc <= UNTREEIFY_THRESHOLD) tab[index] = loHead.untreeify(map); else { tab[index] = loHead; if (hiHead != null) // (else is already treeified) loHead.treeify(tab); } } if (hiHead != null) { if (hc <= UNTREEIFY_THRESHOLD) tab[index + bit] = hiHead.untreeify(map); else { tab[index + bit] = hiHead; if (loHead != null) hiHead.treeify(tab); } } } /* ------------------------------------------------------------ */ // Red-black tree methods, all adapted from CLR static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) { TreeNode<K,V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) rl.parent = p; if ((pp = r.parent = p.parent) == null) (root = r).red = false; else if (pp.left == p) pp.left = r; else pp.right = r; r.left = p; p.parent = r; } return root; } static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root, TreeNode<K,V> p) { TreeNode<K,V> l, pp, lr; if (p != null && (l = p.left) != null) { if ((lr = p.left = l.right) != null) lr.parent = p; if ((pp = l.parent = p.parent) == null) (root = l).red = false; else if (pp.right == p) pp.right = l; else pp.left = l; l.right = p; p.parent = l; } return root; } static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) { x.red = true; for (TreeNode<K,V> xp, xpp, xppl, xppr;;) { if ((xp = x.parent) == null) { x.red = false; return x; } else if (!xp.red || (xpp = xp.parent) == null) return root; if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp); } } } } else { if (xppl != null && xppl.red) { xppl.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateLeft(root, xpp); } } } } } } static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root, TreeNode<K,V> x) { for (TreeNode<K,V> xp, xpl, xpr;;) { if (x == null || x == root) return root; else if ((xp = x.parent) == null) { x.red = false; return x; } else if (x.red) { x.red = false; return root; } else if ((xpl = xp.left) == x) { if ((xpr = xp.right) != null && xpr.red) { xpr.red = false; xp.red = true; root = rotateLeft(root, xp); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr == null) x = xp; else { TreeNode<K,V> sl = xpr.left, sr = xpr.right; if ((sr == null || !sr.red) && (sl == null || !sl.red)) { xpr.red = true; x = xp; } else { if (sr == null || !sr.red) { if (sl != null) sl.red = false; xpr.red = true; root = rotateRight(root, xpr); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr != null) { xpr.red = (xp == null) ? false : xp.red; if ((sr = xpr.right) != null) sr.red = false; } if (xp != null) { xp.red = false; root = rotateLeft(root, xp); } x = root; } } } else { // symmetric if (xpl != null && xpl.red) { xpl.red = false; xp.red = true; root = rotateRight(root, xp); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl == null) x = xp; else { TreeNode<K,V> sl = xpl.left, sr = xpl.right; if ((sl == null || !sl.red) && (sr == null || !sr.red)) { xpl.red = true; x = xp; } else { if (sl == null || !sl.red) { if (sr != null) sr.red = false; xpl.red = true; root = rotateLeft(root, xpl); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl != null) { xpl.red = (xp == null) ? false : xp.red; if ((sl = xpl.left) != null) sl.red = false; } if (xp != null) { xp.red = false; root = rotateRight(root, xp); } x = root; } } } } } /** * Recursive invariant check */ static <K,V> boolean checkInvariants(TreeNode<K,V> t) { TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode<K,V>)t.next; if (tb != null && tb.next != t) return false; if (tn != null && tn.prev != t) return false; if (tp != null && t != tp.left && t != tp.right) return false; if (tl != null && (tl.parent != t || tl.hash > t.hash)) return false; if (tr != null && (tr.parent != t || tr.hash < t.hash)) return false; if (t.red && tl != null && tl.red && tr != null && tr.red) return false; if (tl != null && !checkInvariants(tl)) return false; if (tr != null && !checkInvariants(tr)) return false; return true; } } /*-[ - (NSUInteger)enumerateEntriesWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id *)stackbuf count:(NSUInteger)len { // Note: Must not use extra[4] because it is set by HashSet. if (state->state == 0) { state->state = 1; state->extra[0] = 0; state->extra[1] = 0; // Detect mutations here to properly raise ConcurrentModificationException. state->mutationsPtr = &state->state; state->extra[3] = modCount_; } if (state->extra[3] != modCount_) { @throw create_JavaUtilConcurrentModificationException_init(); } if (size_ == 0 || table_ == nil) { return 0; } NSUInteger position = state->extra[0]; JavaUtilHashMap_Node *entry = (JavaUtilHashMap_Node *) state->extra[1]; state->itemsPtr = stackbuf; NSUInteger objCount = 0; while (objCount < len) { if (entry) { entry = entry->next_; } while (!entry && position < (NSUInteger) table_->size_) { entry = table_->buffer_[position++]; } if (!entry) { break; } *stackbuf++ = entry; objCount++; } state->extra[0] = position; state->extra[1] = (unsigned long) entry; return objCount; } ]-*/ }
true
6e828a85273bfe71d8dbeec98a1dcf05c065bddf
Java
BrunoSouzaDev/talentos-techbank
/src/br/com/techbank/semana_2/aula_12/heranca/CarroUmPontoZero.java
UTF-8
204
2.09375
2
[]
no_license
package br.com.techbank.semana_2.aula_12.heranca; public class CarroUmPontoZero extends Carro{ CarroUmPontoZero(){ this.motor = "Motor 1.0"; //this.rodas = 1; > INACESSÍVEL } }
true
a7974a63f05398191dafaac7da8d4b4d4637a296
Java
abdibouh1/MY-FIRST-PROJET-IN-JAVA-RADIALOGIE-
/src/DAO/DAO_ajouter_patient.java
UTF-8
1,540
2.375
2
[]
no_license
package DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import application.Adminstrateur_model; import application.Patient; public class DAO_ajouter_patient { public static Connection conn = Connexion.getConnexion(); public static PreparedStatement preparStat; public static ResultSet rs; public static int Ajouter(Patient Patient) throws SQLException { int st = 1; Connection cnx=Connexion.getConnexion(); String requet="SELECT * from PATIENT where CIN =?"; preparStat=cnx.prepareStatement(requet); preparStat.setInt(1, Patient.getCIN()); ResultSet rs = preparStat.executeQuery(); if(rs.next()){ return st; } else { String Requete = "INSERT INTO PATIENT(NOM,LASTNAME,DATEBIRTH,CIN,PHONENUMBER,ADRESS) VALUES(?,?,?,?,?,?)"; try { preparStat = conn.prepareStatement(Requete); preparStat.setString(1, Patient.getNom()); preparStat.setString(2, Patient.getPrenom()); preparStat.setString(3, Patient.getDate_ofbirth()); preparStat.setInt(4, Patient.getCIN()); preparStat.setInt(5, Patient.getPhonenumber()); preparStat.setString(6, Patient.getAdress()); preparStat.executeQuery(); } catch (SQLException ex) { ex.printStackTrace(); st = 0; return st; } } st=2; return st; } }
true
080e008de343a9f9d4655418d4d5f55de2d21b3d
Java
trongnsiwa/carrental-javaweb
/SE140037_J3LP0015/src/java/trongns/type/TypeDAO.java
UTF-8
3,172
2.40625
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 trongns.type; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import javax.naming.NamingException; import trongns.util.MyConnection; /** * * @author TrongNS */ public class TypeDAO implements Serializable{ private ArrayList<TypeDTO> typeList = null; /** * @return the typeList */ public ArrayList<TypeDTO> getTypeList() { return typeList; } public void loadTypeList() throws NamingException, SQLException { Connection con = null; PreparedStatement stm = null; ResultSet rs = null; try { con = MyConnection.makeConnection(); if (con != null) { String sql = "SELECT TypeID, TypeName, Seat, Image " + "FROM [Type] "; stm = con.prepareStatement(sql); rs = stm.executeQuery(); int typeId, seat; String typeName, imageLink; while (rs.next()) { typeId = rs.getInt("TypeID"); typeName = rs.getString("TypeName"); seat = rs.getInt("Seat"); imageLink = rs.getString("Image"); if (this.typeList == null) { this.typeList = new ArrayList<>(); } TypeDTO dto = new TypeDTO(typeId, typeName, seat, imageLink); this.typeList.add(dto); } } } finally { if (rs != null) { rs.close(); } if (stm != null) { stm.close(); } if (con != null) { con.close(); } } } private String typeName = null; /** * @return the typeName */ public String getTypeName() { return typeName; } public void getTypeNameById(int id) throws NamingException, SQLException { Connection con = null; PreparedStatement stm = null; ResultSet rs = null; try { con = MyConnection.makeConnection(); if (con != null) { String sql = "SELECT TypeName " + "FROM [Type] " + "WHERE TypeID = ?"; stm = con.prepareStatement(sql); stm.setInt(1, id); rs = stm.executeQuery(); if (rs.next()) { this.typeName = rs.getString("TypeName"); } } } finally { if (rs != null) { rs.close(); } if (stm != null) { stm.close(); } if (con != null) { con.close(); } } } }
true
5ab0687c133d9915cfc68ba7d6bf45e8e20e3fb0
Java
fredpaw/struts_tuts
/test_servlet/WebContent/WEB-INF/src/org/zjh/servlet/UserManager.java
UTF-8
493
2.390625
2
[]
no_license
package org.zjh.servlet; import java.util.*; public class UserManager { public void add(String name){ System.out.println("add " + name); } public void del(String name){ System.out.println("del " + name); } public void modify(String name){ System.out.println("modify " + name); } public List query(String name){ System.out.println("query " + name); List userList = new ArrayList(); userList.add("A"); userList.add("B"); userList.add("C"); return userList; } }
true
8f7ce5d6ee38cd04e3953bc82dcc537d7ef8a354
Java
antonchirikalov/HW20
/src/main/java/com/toennies/ci1429/app/ui/components/AbstractDevicePanel.java
UTF-8
1,050
2.953125
3
[]
no_license
package com.toennies.ci1429.app.ui.components; import com.toennies.ci1429.app.model.ADevice; import com.toennies.ci1429.app.model.IDevice; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; /** * Abstract Panel that displays {@link ADevice} objects. See subclasses */ @SuppressWarnings("serial") public abstract class AbstractDevicePanel extends FormLayout { protected final IDevice aDevice; /** * Takes an {@link ADevice} and prepares everything to display it. */ public AbstractDevicePanel(IDevice aDevice) { this.aDevice = aDevice; if (this.aDevice != null) { // only display the device, if it's valid addComponents(); } else { showDeviceNotValidText(); } } /** * This method adds respective GUI components to display the device. * Implemenation depends on Subclass. */ protected abstract void addComponents(); /** * Adds components for signal a invalid device. Override if you want to! */ protected void showDeviceNotValidText() { addComponent(new Label("Device is not valid!")); } }
true
9e2e009c9d1af2097ecb9549fdc6305b38687e5a
Java
eXsio/querydsl-entityql-examples
/java-gradle-spring-data-jdbc-dynamic/src/main/java/pl/exsio/querydsl/entityql/examples/spring_data_jdbc/example/dynamic/QJDBCAdvSelectDynamicExample.java
UTF-8
3,979
2.40625
2
[ "MIT" ]
permissive
package pl.exsio.querydsl.entityql.examples.spring_data_jdbc.example.dynamic; import com.querydsl.core.types.Projections; import com.querydsl.sql.SQLExpressions; import com.querydsl.sql.SQLQueryFactory; import org.springframework.stereotype.Service; import pl.exsio.querydsl.entityql.EntityQL; import pl.exsio.querydsl.entityql.Q; import pl.exsio.querydsl.entityql.entity.scanner.QEntityScanner; import pl.exsio.querydsl.entityql.entity.scanner.SpringDataJdbcQEntityScanner; import pl.exsio.querydsl.entityql.examples.Example; import pl.exsio.querydsl.entityql.examples.configuration.UpperCaseWithUnderscoresNamingStrategy; import pl.exsio.querydsl.entityql.examples.dto.OrderItemBookCountDto; import pl.exsio.querydsl.entityql.examples.spring_data_jdbc.entity.Book; import pl.exsio.querydsl.entityql.examples.spring_data_jdbc.entity.Order; import pl.exsio.querydsl.entityql.examples.spring_data_jdbc.entity.OrderItem; import pl.exsio.querydsl.entityql.examples.spring_data_jdbc.entity.User; import java.math.BigDecimal; import java.util.List; import static com.querydsl.sql.SQLExpressions.count; @Service class QJDBCAdvSelectDynamicExample implements Example { private final SQLQueryFactory queryFactory; private final QEntityScanner scanner = new SpringDataJdbcQEntityScanner(new UpperCaseWithUnderscoresNamingStrategy()); public QJDBCAdvSelectDynamicExample(SQLQueryFactory queryFactory) { this.queryFactory = queryFactory; } private void useAggregateFunctions() { Q<OrderItem> orderItem = EntityQL.qEntity(OrderItem.class, scanner); List<OrderItemBookCountDto> result = queryFactory .select( Projections.constructor( OrderItemBookCountDto.class, orderItem.longNumber("orderId"), SQLExpressions.count(orderItem.longNumber("bookId")))) .from(orderItem) .groupBy(orderItem.longNumber("orderId")) .orderBy(orderItem.longNumber("orderId").asc()) .fetch(); System.out.println(result); } private void useSubQueries() { Q<User> user = EntityQL.qEntity(User.class, scanner); Q<Book> book = EntityQL.qEntity(Book.class, scanner); Q<Order> order = EntityQL.qEntity(Order.class, scanner); Q<OrderItem> orderItem = EntityQL.qEntity(OrderItem.class, scanner); List<String> result = queryFactory.select(user.string("name")) .from(user) .where(user.longNumber("id").in( SQLExpressions.select(order.longNumber("userId")) .from(orderItem) .innerJoin(orderItem.<Book>joinColumn("book"), book) .innerJoin(orderItem.<Order>joinColumn("order"), order) .where(book.decimalNumber("price").gt(new BigDecimal("80"))) )).fetch(); System.out.println(result); } private void useNestedSelects() { Q<Book> book = EntityQL.qEntity(Book.class, scanner); Q<Order> order = EntityQL.qEntity(Order.class, scanner); Q<OrderItem> orderItem = EntityQL.qEntity(OrderItem.class, scanner); Long result = queryFactory.select(count()) .from( SQLExpressions.select(order.longNumber("userId")) .from(orderItem) .innerJoin(orderItem.<Book>joinColumn("book"), book) .innerJoin(orderItem.<Order>joinColumn("order"), order) .where(book.decimalNumber("price").gt(new BigDecimal("80"))) ).fetchOne(); System.out.println(result); } @Override public void run() { useAggregateFunctions(); useSubQueries(); useNestedSelects(); } }
true
d29b35627134074f8a15e46fd5fed0e2162d9925
Java
shovalsolo/SeleniumJavaFullFramework
/FullSeleniumFramework/src/test/java/screenShotPrintScreen/ScreenshotOnFailure.java
UTF-8
1,435
2.671875
3
[]
no_license
/* * This class is taking a screen shot on failure using class ScreenshotManager.cuptureScreenshot */ package screenShotPrintScreen; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import io.github.bonigarcia.wdm.WebDriverManager; public class ScreenshotOnFailure { static WebDriver driver = null; @Test public void ScreenshotOnMethodFailure() { WebDriverManager.chromedriver().setup(); //Setting ChromeDriver driver = new ChromeDriver(); //Setting browser as Chrome driver.get("https://opensource-demo.orangehrmlive.com/"); //Going to URL driver.findElement(By.id("txtUsername11")).sendKeys("11111"); //This will fail and will go to @AfterMethod and will take the screenshot with the class name as the picture file name } @AfterMethod //Will run after every function %%% public void tearDown(ITestResult result) { if (ITestResult.FAILURE == result.getStatus()) { ScreenshotManager.cuptureScreenshot(driver , result.getName()); // %%% This is calling ScreenshotManager.cuptureScreenshot with file name and the WebDriver to get a screenshot with the name of the function that was failed } driver.quit(); } }
true
acf6d5bad63a9b789d5742f8408b31a1fada4a9a
Java
cqqyd2014/finance
/src/main/java/test/MessagePrinter.java
UTF-8
462
1.914063
2
[]
no_license
package test; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import gov.cqaudit.finance.dao.BillMDAOPostgresql; @Component @Scope("prototype") public class MessagePrinter { @Resource BillMDAOPostgresql billMDAOPostgresql; public void printMessage() { System.out.println("testok"); } }
true
14095e00dc453fe41fcc7fb43ba4d8ef7b98c3d9
Java
canhtommy99dev/MongCaiFood
/app/src/main/java/com/alexmedia/mongcaifood/Activity/Camerakit.java
UTF-8
7,242
1.835938
2
[]
no_license
package com.alexmedia.mongcaifood.Activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.alexmedia.mongcaifood.R; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.ml.vision.FirebaseVision; import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode; import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector; import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions; import com.google.firebase.ml.vision.common.FirebaseVisionImage; import com.google.firebase.ml.vision.common.FirebaseVisionImageMetadata; import com.karumi.dexter.Dexter; import com.karumi.dexter.MultiplePermissionsReport; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.multi.MultiplePermissionsListener; import com.otaliastudios.cameraview.CameraView; import com.otaliastudios.cameraview.frame.Frame; import com.otaliastudios.cameraview.frame.FrameProcessor; import java.util.List; public class Camerakit extends AppCompatActivity { CameraView cameraView; boolean isDetected = false; Button btnClickScan; FirebaseVisionBarcodeDetector dectector; FirebaseVisionBarcodeDetectorOptions options; ImageView imgBack; String textSearch; public static final String TENCH = "tench"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camerakit); imgBack = findViewById(R.id.clickReturn); imgBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); Dexter.withActivity(this) .withPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}) .withListener(new MultiplePermissionsListener() { @Override public void onPermissionsChecked(MultiplePermissionsReport report) { setupCamera(); } @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) { } }).check(); } private void setupCamera() { btnClickScan = findViewById(R.id.btnclickchup); btnClickScan.setEnabled(isDetected); btnClickScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isDetected = !isDetected; } }); cameraView = findViewById(R.id.camermc); cameraView.setLifecycleOwner(this); cameraView.addFrameProcessor(new FrameProcessor() { @Override public void process(@NonNull Frame frame) { processImage(getVisionImageFromFrame(frame)); } }); options = new FirebaseVisionBarcodeDetectorOptions.Builder() .setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE).build(); dectector = FirebaseVision.getInstance().getVisionBarcodeDetector(options); } private void processImage(FirebaseVisionImage visionImageFromFrame) { if (!isDetected) { dectector.detectInImage(visionImageFromFrame) .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() { @Override public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) { processResult(firebaseVisionBarcodes); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } } private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes) { if (firebaseVisionBarcodes.size() > 0) { isDetected = true; btnClickScan.setEnabled(isDetected); for (FirebaseVisionBarcode item:firebaseVisionBarcodes){ int value_type = item.getValueType(); switch (value_type){ case FirebaseVisionBarcode.TYPE_TEXT:{ createDialog(item.getRawValue()); textSearch = item.getRawValue(); } break; case FirebaseVisionBarcode.TYPE_URL:{ Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(item.getRawValue())); startActivity(intent); } break; case FirebaseVisionBarcode.TYPE_CONTACT_INFO:{ String info = new StringBuilder("Name: ") .append(item.getContactInfo().getName().getFormattedName()) .append("\n") .append("Address: ") .append(item.getContactInfo().getAddresses().get(0).getAddressLines()) .append("\n") .append("Email: ") .append(item.getContactInfo().getEmails().get(0).getAddress()) .toString(); createDialog(info); } break; } } } } private void createDialog(String text) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(text) .setPositiveButton("Oke", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).setPositiveButton("Oke", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog2 = builder.create(); dialog2.show(); } private FirebaseVisionImage getVisionImageFromFrame(Frame frame) { byte[] data = frame.getData(); FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder() .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21) .setHeight(frame.getSize().getHeight()) .setWidth(frame.getSize().getWidth()) .build(); return FirebaseVisionImage.fromByteArray(data,metadata); } }
true
9e43c890bdbf56f6a31e722cdee436138e6d5de8
Java
willislin0222/hairdressing
/src/com/offer/model/OfferDAO.java
UTF-8
1,474
2.46875
2
[]
no_license
package com.offer.model; import java.sql.Date; import java.util.List; import org.springframework.orm.hibernate5.HibernateTemplate; public class OfferDAO implements OfferDAO_interface{ private static final String GET_ALL_STMT="from OfferVO order by off_no"; private static final String GET_OFFER_BY_TODAY="from OfferVO where off_end=?"; //springframework hibernate5 private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } @Override public void insert(OfferVO offerVO) { hibernateTemplate.saveOrUpdate(offerVO); } @Override public void update(OfferVO offerVO) { hibernateTemplate.update(offerVO); } @Override public void delete(String off_no) { OfferVO offerVO = (OfferVO) hibernateTemplate.get(OfferVO.class, off_no); hibernateTemplate.delete(offerVO); } @Override public OfferVO findByPrimaryKey(String off_no) { OfferVO offerVO = (OfferVO) hibernateTemplate.get(OfferVO.class, off_no); return offerVO; } @Override public List<OfferVO> getAll() { List<OfferVO> list = null; list = (List<OfferVO>) hibernateTemplate.find(GET_ALL_STMT); return list; } @Override public List<OfferVO> getOfferBYToday() { List<OfferVO> list = null; Date today = new Date(System.currentTimeMillis()); list = (List<OfferVO>) hibernateTemplate.find(GET_OFFER_BY_TODAY,today); return list; } }
true
4e03d02c7ab9ed6f171af24488ab6a5047c3c41a
Java
anthonycanino1/entbench-pi
/batik/classes/org/apache/batik/gvt/font/UnresolvedFontFamily.java
UTF-8
15,581
1.648438
2
[ "Apache-2.0" ]
permissive
package org.apache.batik.gvt.font; public class UnresolvedFontFamily implements org.apache.batik.gvt.font.GVTFontFamily { protected org.apache.batik.gvt.font.GVTFontFace fontFace; public UnresolvedFontFamily(org.apache.batik.gvt.font.GVTFontFace fontFace) { super( ); this. fontFace = fontFace; } public UnresolvedFontFamily(java.lang.String familyName) { this( new org.apache.batik.gvt.font.GVTFontFace( familyName)); } public org.apache.batik.gvt.font.GVTFontFace getFontFace() { return fontFace; } public java.lang.String getFamilyName() { return fontFace. getFamilyName( ); } public org.apache.batik.gvt.font.GVTFont deriveFont(float size, java.text.AttributedCharacterIterator aci) { return null; } public org.apache.batik.gvt.font.GVTFont deriveFont(float size, java.util.Map attrs) { return null; } public static final java.lang.String jlc$CompilerVersion$jl7 = "2.7.0"; public static final long jlc$SourceLastModified$jl7 = 1471109864000L; public static final java.lang.String jlc$ClassType$jl7 = ("H4sIAAAAAAAAAL1ZfXBU1RW/uwkhH+STT0ECCQEK6K5YtWLUGmICoRtICcZx" + "UcLL27vZR96+93jvbrKJxSrTjtROqSJ+tCP5p1goojCdOq21OjhO/RhpO+BX" + "raMy1Zn6UUcZq+3Utvace9/b97EflFa7M+/u23vPufeec8/5nXPPHn6fTLFM" + "0kw1FmHjBrUiXRrrk0yLJjpVybI2Qd+gfE+Z9NGWt9evCpOKOKlLSVavLFm0" + "W6FqwoqT+YpmMUmTqbWe0gRy9JnUouaoxBRdi5OZitWTNlRFVlivnqBIMCCZ" + "MdIoMWYqQxlGe+wJGJkfg51E+U6iHcHh9hiZJuvGuEs+x0Pe6RlByrS7lsVI" + "Q2ybNCpFM0xRozHFYu1Zk6wwdHV8WNVZhGZZZJt6sa2CdbGL81TQerT+k09v" + "TzVwFUyXNE1nXDxrI7V0dZQmYqTe7e1SadraTm4iZTFS4yFmpC3mLBqFRaOw" + "qCOtSwW7r6VaJt2pc3GYM1OFIeOGGGnxT2JIppS2p+nje4YZKpktO2cGaRfm" + "pBVS5ol414ro3nu2NPy0jNTHSb2i9eN2ZNgEg0XioFCaHqKm1ZFI0EScNGpw" + "2P3UVCRVmbBPuslShjWJZeD4HbVgZ8agJl/T1RWcI8hmZmSmmznxktyg7F9T" + "kqo0DLLOcmUVEnZjPwhYrcDGzKQEdmezlI8oWoKRBUGOnIxtXwMCYJ2apiyl" + "55Yq1yToIE3CRFRJG472g+lpw0A6RQcDNBmZW3RS1LUhySPSMB1EiwzQ9Ykh" + "oKriikAWRmYGyfhMcEpzA6fkOZ/311+++0ZtrRYmIdhzgsoq7r8GmJoDTBtp" + "kpoU/EAwTlseu1ua9diuMCFAPDNALGh+/o3TV53XfOwZQTOvAM2GoW1UZoPy" + "/qG6E+d2LltVhtuoNHRLwcP3Sc69rM8eac8agDCzcjPiYMQZPLbxqetuPkTf" + "C5PqHlIh62omDXbUKOtpQ1GpuYZq1JQYTfSQKqolOvl4D5kK7zFFo6J3QzJp" + "UdZDylXeVaHz36CiJEyBKqqGd0VL6s67IbEUf88ahJCp8JDL4FlAxId/MyJF" + "U3qaRiVZ0hRNj/aZOspvRQFxhkC3qegQWP1I1NIzJphgVDeHoxLYQYraA8Oj" + "LJoExUSv0Uzb7rvhZ7eUVtTxCJqa8f9YJIuSTh8LheAQzg1CgAres1ZXE9Qc" + "lPdmVnedfmjwOWFe6BK2jhiJwLoRsW6ErxuBdSO4bqTQuiQU4svNwPXFecNp" + "jYDfA/BOW9Z/w7qtu1rLwNCMsXJQdRhIW30BqNMFBwfRB+UjTbUTLa+vfDJM" + "ymOkSZJZRlIxnnSYw4BU8ojtzNOGIDS5EWKhJ0JgaDN1mSYAoIpFCnuWSn2U" + "mtjPyAzPDE78Qk+NFo8eBfdPjt07dsvANy8Ik7A/KOCSUwDPkL0PoTwH2W1B" + "MCg0b/2tb39y5O4dugsLvijjBMc8TpShNWgQQfUMyssXSg8PPrajjau9CmCb" + "SeBmgIjNwTV8qNPuIDjKUgkCJ3UzLak45Oi4mqVMfczt4ZbayN9ngFnUOL74" + "Jdsv+TeOzjKwnS0sG+0sIAWPEFf0G/t+/9t3vszV7QSTek8W0E9ZuwfAcLIm" + "DlWNrtluMikFutfu7bvzrvdv3cxtFigWFVqwDdtOAC44QlDzt5/Z/sobr+9/" + "IZyz8xCDCJ4ZgkQomxMS+0l1CSFhtSXufgAAVcAHtJq2azSwTyWpSEMqRcf6" + "R/3ilQ//eXeDsAMVehwzOu/ME7j956wmNz+35a/NfJqQjAHY1ZlLJlB9ujtz" + "h2lK47iP7C0n5//gaWkfxAfAZEuZoBxmQ0IHXPI5jCwuDilrBjYJLJEpP+KL" + "Oc8FvL0I1cNnInxsFTaLLa+r+L3Rk1YNyre/8GHtwIePn+ay+fMyr2X0Ska7" + "MEZslmRh+tlBKFsrWSmgu+jY+usb1GOfwoxxmFEGkLY2mICnWZ8d2dRTpv7h" + "iSdnbT1RRsLdpFrVpQQIiS5JqsAXqJUCKM4aX71KmMJYJTQNXFSSJ3xeBx7H" + "gsIH3ZU2GD+aiV/M/tnlByZf5zZp8Cnm5/vbStsUVxb2N2yXYrMi34qLsQZO" + "MGALDXzbmHdFRN7FV+opcey92FzNhy7Dpkvo44r/UnXY0WmIgXn23iBa+mIS" + "v+24sHjo+a+8eOCOu8dEvrSseCwI8M35+wZ1aOcf/5ZngjwKFMjlAvzx6OH7" + "5nZe+R7nd+EYuduy+REeQprLe+Gh9Mfh1opfh8nUOGmQ7dvFgKRmEOTikFFb" + "zpUDbiC+cX92LFLB9ly4OTcYCjzLBgOBm1nAO1Lje20A++vwXBbB02IbVEvQ" + "FkOEv1wnzJG3y7E534HaKsPUGeySJgJoW1tiWkYqkzb04O9LXIvnZhYvYWbZ" + "Qo7BPxUkkFsGHWOe3x2W/gfQiGkW4tL8YtcFftXZv3PvZGLD/SuFkTb5U/Au" + "uGE++NI/j0fuPfVsgZyviunG+Sodpapnj+W4pM8tevlNyrWx1+r2vPlI2/Dq" + "s8nSsK/5DHkY/l4AQiwv7mnBrTy98925m65MbT2LhGtBQJ3BKX/Se/jZNUvk" + "PWF+bRTGn3fd9DO1+02+2qRwP9Y2+Qx/Uc5gZqN9tMJzqW0wl549CBdjLYGn" + "mRJjY9iAQdQMU9btdQ7XL7Z/HvDL+9WcOE2Ou3TY4nScvSaKsZaQdmeJsW9h" + "s4ORWtQEd8H19sGuc3Vx0xegi+k4Nh+eXlug3rPXRTHWgLzhQlcydOD+zJAF" + "1yclDdnyqF1YuLBvq7yrre8tgS/nFGAQdDMPRr838PK249wTK9H1c/bvcXuA" + "CM9FoEGI8Bl8QvD8Cx/cOnbgN0SkTrtKsDBXJjAMBMUS0TggQHRH0xsj9739" + "oBAgGHoDxHTX3ts+i+zeK8BS1JoW5ZV7vDyi3iTEweZO3F1LqVU4R/efjux4" + "9OCOW8O23aUYhlBdYnkJFNx9/EoXO736O/W/ur2prBtAuIdUZjRle4b2JPxA" + "NNXKDHlOwS1OubBk7xk1zkhouWFnSJi984wN64KRXJU20ZkCLIWAa/Ywyq9A" + "fJLvl3CoH2FzGyPVkDCDAhBdnBVazhgEXZf77hfpctfafnPt2btcMdbCLoc/" + "9/jja86NNkpjPLIPytcvbZjVtuqjVttiC9B6Koa7H/1lPL60QRbEhRw6UCk8" + "eKBSfjX91FuO5d3hz8ga4TllC3VKOOH1/2MBC9jSUQYeAGnlJiVNE1g6x43a" + "BbIvdH5+s/OlM66iHxhROz649MdXCN21FIEUl/6Rr586sW/iyGGBDohxjKwo" + "VuzP/4cBqzGLS1SU3EP9eM1lx955c+AG54zqsHk455q17h0QbpzY+VgQNvDn" + "ZJYzHy3hnU9g84DPO7HnftfxDn8u1y5GZhSqIuKFdk7efxaizi4/NFlfOXvy" + "mpd5mpmrhU+D6JLMqKr3iuF5rzBMmlS4bNPEhcPgX88yck5RuGGkPOmgzTOC" + "/jjsuBA9I2XQeil/B5fbICWAOf/20p0ELbt0jFSIFy/JizA7kODrS0aBm7O4" + "k2VDnmzd1jk/qplnOqoci7e8hXbI/11ycCPTZ5v7kcl16288fcn9orwmq9LE" + "BM5SA4FFVPpyOXVL0dmcuSrWLvu07mjVYseiG8WGXYCd57HKTjBgA21jbqD2" + "ZLXlSlCv7L/88d/sqjgJvriZhCRGpm/Ov71mjQyA7eZYfgCF+wcvirUv++H4" + "leclP3iV10tIXlUgSD8ov3Dghuf3zNnfHCY1PWQKhHKa5dfqq8e1jVQeNeOk" + "VrG6srBFmEWRVF90rkMzlrD+wfViq7M214vFWUZa8zOO/JJ2taqPUXO1ntES" + "dnyvcXt8f3vZrlGdMYwAg9vjycr2iZRAYH/ZYKzXMJyErPwvBvfoycJwg+07" + "/BWbd/8NX/n6eXkeAAA="); public static final java.lang.String jlc$CompilerVersion$jl5 = "2.7.0"; public static final long jlc$SourceLastModified$jl5 = 1471109864000L; public static final java.lang.String jlc$ClassType$jl5 = ("H4sIAAAAAAAAAL1aeczsVnX3+/LykryQvJcEkpCShIQXlhg+jz2bzYM2Y8/Y" + "Y49n7BnP6gIPj/cZb+NtFpoWUFkEFaU0UCqR/NGCWmhYWhW1FQKlaikgEFIQ" + "6iYVUFupUIpE/oBWpS299nz7W0Io6ki+Y9977r1n+Z1zj+/1k9+Dro9CCA58" + "Z206fryrr+LdmVPejdeBHu1yfFlUwkjXKEeJoj6ou6Q++KlzP/zRe63zO9AZ" + "GbpD8Tw/VmLb96KeHvlOqms8dO6wtuHobhRD5/mZkipIEtsOwttRfJGHbj7S" + "NYYu8PssIIAFBLCA5CwgtUMq0OkW3UtcKuuheHG0gH4ZOsVDZwI1Yy+GHjg+" + "SKCEirs3jJhLAEa4MXseAqHyzqsQevGB7FuZLxP4/TDy2G+94fwfXQedk6Fz" + "tidl7KiAiRhMIkPPc3V3qodRTdN0TYZu83Rdk/TQVhx7k/MtQ7dHtukpcRLq" + "B0rKKpNAD/M5DzX3PDWTLUzU2A8PxDNs3dH2n643HMUEst55KOtWQjqrBwKe" + "tQFjoaGo+n6X03Pb02Lo/pM9DmS80AIEoOsNrh5b/sFUpz0FVEC3b23nKJ6J" + "SHFoeyYgvd5PwCwxdM9VB810HSjqXDH1SzF090k6cdsEqG7KFZF1iaEXnCTL" + "RwJWuueElY7Y53ud17znTV7T28l51nTVyfi/EXS670Snnm7ooe6p+rbj8x7m" + "P6Dc+dl37kAQIH7BCeItzZ/80jOPvPK+p764pfm5K9AI05muxpfUD09vffpF" + "1CuI6zI2bgz8yM6Mf0zyHP7iXsvFVQA8786DEbPG3f3Gp3p/NXnzx/Tv7kBn" + "WeiM6juJC3B0m+q7ge3oIaN7eqjEusZCN+meRuXtLHQDuOdtT9/WCoYR6TEL" + "nXbyqjN+/gxUZIAhMhXdAO5tz/D37wMltvL7VQBB0A3ggl4Nrvuh7S//jyEF" + "sXxXRxRV8WzPR8TQz+SPEN2Lp0C3FjIFqJ8jkZ+EAIKIH5qIAnBg6XsNZhoj" + "BlAMMvDCPdzT4JFWXNtZ72ZQC/4/Jlllkp5fnjoFjPCikyHAAd7T9B1NDy+p" + "jyVk45lPXPryzoFL7OkohnbBvLvbeXfzeXfBvLvZvLtXmhc6dSqf7vnZ/Ft7" + "A2vNgd+DiPi8V0iv5974zgevA0ALlqeBqncAKXL1wEwdRgo2j4cqgCv01AeX" + "bxn+SmEH2jkeYTOeQdXZrLuYxcWD+HfhpGddadxz7/j2Dz/5gUf9Qx87FrL3" + "XP/ynpnrPnhSu6Gv6hoIhofDP/xi5dOXPvvohR3oNIgHIAbGCsAsCC/3nZzj" + "mAtf3A+HmSzXA4ENP3QVJ2vaj2FnYyv0l4c1udlvze9vAzq+eR/YL98Def6f" + "td4RZOXztzDJjHZCijzcvlYKHv/br36nmKt7PzKfO7LWSXp88Ug0yAY7l/v9" + "bYcY6Ie6Duj+4YPib77/e+/4xRwAgOIlV5rwQlZSIAoAEwI1v+2Li7/75jc+" + "/PWdA9CcisFymEwdW10dCJnVQ2evISSY7aWH/IBo4gBny1BzYeC5vmYbtjJ1" + "9Ayl/3XuIfTT//ae81scOKBmH0avfPYBDutfSEJv/vIb/v2+fJhTaraaHers" + "kGwbIu84HLkWhso642P1lq/d+9tfUB4HwRYEuMje6HnMOrXVQS75C2Looav7" + "JzPsbx1T1XMTI3mfh/NyN1NPPhKUtxWz4v7oqKsc98YjOcol9b1f//4tw+9/" + "7plctuNJzlFktJXg4haMWfHiFRj+rpNxoalEFqArPdV53XnnqR+BEWUwogoi" + "XiSEIDitjuFoj/r6G/7+z//izjc+fR20Q0NnHV/RgJCZS0I3AV/QIwvEtVXw" + "C49sobC8ERTnc1Ghy4TPK+653FnQPRyhV3aWrHwgKx66HIJX63pC/ScMeT6X" + "MstAdrcZSD7TI9ewWT0rLuZNpax4zVaY6k8k95b27vzpNDDMK64eheksNzsM" + "ZHf/p+BM3/qP/3GZ8fP4e4WU5ER/GXnyQ/dQP//dvP9hIMx637e6fKECeexh" + "X+xj7g92Hjzz+R3oBhk6r+4lyUPFSbLwIoPEMNrPnEEifaz9eJK3zWguHgT6" + "F50MwkemPRmCDxdIcJ9RZ/dnT0TdWzMtvwRcD+yh4YGTQDoF5TedLZby8kJW" + "vGw/yN0UhH4MuNS1vTj3Y/A7Ba7/ya5suKxim7HcTu2lTS8+yJsCsHrfaOwF" + "gKx/4RC6OV6EZ8MLmxXS6hTg5Xpst7qbDzC+Mr/XZbcvB5E5yl8dQA/D9hQn" + "14oUA7931Av7PA7BqwQAzIWZU82aayf4kn5ivgBubz10G94Hafu7//m9X/n1" + "l3wTgIuDrk8zwwNMHfGtTpK9ybz9yfffe/Nj33p3vqgAZQ9/9Uf3PJKNqlxL" + "uqx4XVa8fl+sezKxpDxD45UobufrgK5lkl3bp8TQdsFyme6l6cijt39z/qFv" + "f3ybgp90oBPE+jsfe9ePd9/z2M6RF5+XXPbucbTP9uUnZ/qWPQ2H0APXmiXv" + "Qf/LJx/9zO8/+o4tV7cfT+Mb4C3143/931/Z/eC3vnSFvPG0A6zxUxs2Pic2" + "SxFb2//xqGyMyQHaGyHJcm41YanfLzQoqttoVVrlSTziB4zLUn4vZilVXg1U" + "nseqqdwjKjBRnKXTsMWtpLA/i3vCQuLgmBLLAWr6/ozShAWGCjNLQHpWIMDk" + "OFTaa1T2KoOBKi/g4iBOgfsQyJSoNgyHVqptGEmwYiomhq6rOFL2xqLY9CpG" + "n6fbhfkSpd3mjAwH9rgXhvPCmudmwXA9ZbGuBptGA5aJDjOKCT2lAqEltBxe" + "GiopT7uFUYVeLP1FH54Ebnvg9hfTkV4we2uC8wZ+ovgrsqfZZUG241G/4/To" + "oWOn3oJk2xQltzXWb48mi+7KYXR4yTHc3DDLaAMeVOym2rQIy5a5JGWSRgSv" + "CqJe6TnkOpSqTjRku9h62qECwPyq52+a9CRB5XlludSaQ3zUGcoWI8syF1ci" + "BaO0KcPjaL8LXmXheYFI+5vhkh6sx50G6o3rq5CtDgua3HUni75e1VFJ0UKl" + "75ZsuU9LpTXtBlTR5ckF3VOE5YISYmk5qoaVocLFWKAWmUkbFWhWFxiG8VZ9" + "jGODQMIC2JvppYncCuaxgKmM0jPcgBxKZd8poaXQL3oJ1hHXhVmn35SmmE3o" + "HUzumA2zMLZ9mlKai5aLyjRbaEhqhwmWmFgcDKne0J2SYhI5kjUbcbJeLzWn" + "Q1PGFZNzkD7Amcriliu7kutuvNU8XptVmujPF36hzvOC6g6GDU+eiUtrEqp1" + "ZtPqNjRX3zgs7o/8Vo8cMILHruLxsk1NOEwJ7LVTLk8W6Lrvs40i1aN7HFOq" + "YibsBMtCrdLrqvUO6cqjYk9C+YG1lkSpTaINe7npEpO55bdC257XRj13wqwN" + "q602gk2tYswFGSmiKAzDBTkOexOX1ayNGfmLaogzLufX+2QczAN/gDRqy74T" + "6QmaKIRmJ22Kron1To1nLBjxi/1huTg2hKXc7QtprY0x/ggdyL64RhZMpQFr" + "GO/EQytO/E6zxy9VsSipFSJs47qiAoXVqY06E+1JuyuL/HS10ONEnPcNqiwu" + "mg5rVTDfrY+ng5YQB12UCZKJvEC57qRvSN3WwneE1CnVy/NWdUPTfoUrdjdc" + "MNDk+toZ60OluSlWKJtrrMnWYsFohSFfiSpVdtoYGDiuWBwV4FydL9FObcVq" + "SHvN0YPiQunZQ7lg9TozRJGFKEh7XXplzaniQje7IxFl0Q4LZrHMYR28Aq/4" + "SXcSKjVcmPGc31gNpLQw2EyrYWrJVX0wjPsrilsouEFMODaR+hbOW3qtuzFR" + "yqyBZBOVxw2iqzqi5g49XTPc2VIY0XqFbGEzy+aWvN+LRpVGuEpITRJK00W/" + "m9jdQSlKO0txTOtqJ5hN6kYNIYURISPL6iJO0JBfdqh2NOa6Ws9iR8UCuei0" + "aXJp9Eh4MOtPB31egVOjzrXXrjCXZE7uOezK86TJskQOcH8WbzoCw9alcmPU" + "srgCZyr1DupKk5rPBjTlJSPJwwZuPBPXtY1Yb1Tx7hzu0D6uk4YmzuJCVYvS" + "WmeNs/NqDWkJlDRY1sU5XxD9/rKJjVCyTZmFKYLF0yKxLgslLTEjPrVnM7Kt" + "4v1Asjojs9s1Bu11FI0lExfFUJnNlISgXGoq6aRrsrPOsj/EFx0xYeuz1sCc" + "U1xxsOGVeaks2CV3MWwb6iYuyVNl3SE8k/YGAl8tcYAxuK8Lm1lr6UmFiIEL" + "YKEYiQ3aKDBIDCNEXEyjzbDalfr6HB8VGoScLI2ayrNu3Rl1wthJ2vacTmIj" + "qU7TTZhqaVFdxbRtjujhYlnXYqFGlUpdp76Jy4iMRP40hAmEldcbfEXVKa4k" + "m/Ou767aElxwUEqirVgaJ4ZZqw3VWjPmFpiykcD7+CiQGu1FTzUqPaRoO10E" + "0cd6Paq1h7q13AgJ0m5UZ0S5snQ7G7hYVpCOwS26s1pzgsoOzzkkkQAzWpjT" + "KlVtsUoVvDKCmMpobqxqRk1uJLJPrtxugW2ORbY8o5ZJ3XZCcjbheK4RiHAL" + "BCqcTvkCi6odj/VWEd1XeICbEOaLvTk66axDHcGZZrxkddGDlTVstNchNi5I" + "c7DONeTIcXsWHDtki47CkeSaCTybwEk0RRnBWPqrlUs3mDk/wcDS641kXMO0" + "Xj9Iq5Ytad4URNFexGsBHQ6Dbpe1pTK3iGrjBTegWu2SMq6iLbfNTbh+tzOm" + "JYkrrnRyVW2aEdssygOMqcOKPUTaSOyBxUo2yhs5wCnPLSPpVIqjwXA1xTrY" + "ejwJ23axtOCjriy0mRpfH2+mblOje50qPYT9QNXXBEZvOta6Wg/mqV8qhcjA" + "G08KI5c1xx5WtEkFdlkphbFS1Jz5sALjukAJCa410lCKdGrJ4u1iGV7KqCKo" + "BlKWPXO2bNHtmVNLN6uK0KyWPVmHe1VPgxuTREvWcK+hd4OQ12HGItqGhfqB" + "YeEAv4zbrWopbbZ6bkPoAxTS000wqE9tClbHBMbTPEk465LQVyfUbMOTpkC6" + "qFcTUH6mY4UaDKfLMTklCxg7HTbSLj0XGim69DYcU1xXG+Viqam0InHA6GuJ" + "MzkQxmN7NJ8s5ptpoSQQ/JhNPdmapJPRVO76VVJcDeZzOmKaI0EvrrARYhpd" + "m5mPSjGPT2KVNuKxnBbFVGb4OiIl9Lw/LQ+QWpIwDRjusMisYCSiMYxMeZ3a" + "icfAkq8FSuDN4FEpaOOxnjoAY6MVCodYKjoshtQXEe5JUQsp15vzCeKUal17" + "mVZdjwz7awInsLJbKbenfYy3mJjsckWyNUYkHZnJnUE6F0c0PO31Ga9oaERd" + "QOECBmOL3lIkJhjcXSEDtWzKiw4Rt7nNYlRYOuUSQZHajJ8wntvjZhPCrnW1" + "bntATGOtWx3zVRlppnUeJkaq0MCEpNiflDxJTSWgRlnpgjWdi0aEFZWE3igG" + "azzeRImISdTicFVY6aYNz0sdC9bHTmIWQ3Hc6zdHJr+xuo661oQ6vOFqNLpW" + "nbrmrRc0Okl4Ml1U12Go47EpIR7NAHbqbbEX4kVcbGElYtlvEU1URaapOk5q" + "VJug/QbD4qSDd9M6Tq0QVfCmZgd4aD+MW1GdHHOzWptsD6RC3zS7zV6zsIpm" + "RLVI+GTNZJp+fdXsj4txBNvwRm/hpIQCWJTlYTWtr+2i3W8sdVko0ii/GA5K" + "PUQ3ZsmqRAD8j3ABKyqDieWQ2sSbc3RnRSANfyxUixUBAXl4iAUhGdcSVhvI" + "s56jl6YYJ65qnc64VW86wlJChWRKzqurOboBKUwyoj2Jswm8tOxUSq3emBtg" + "BXlO8eyopiCT5XpB1AyOT50i5TeBwzJrcTivU/WaRWoeOVQ2ltkYy0a1ahmB" + "GhuK4YkxNo3VtjaleF9FCAQsL3il05kHM5FnxXWsplN5NoyTBShimyLISstX" + "qk0EdUS+Uuj2pg2rt6wMqDmut0jJmI0JlE6Esla0NriplPqOQxWHLUFoogjW" + "JiliJg26E73GeA5nD0HKa1ZWpaJCTtlUa5bhCBGcdgXk2yurJ2wqJaKtjakO" + "htJsY+AglV5YxivRCLHXDEPWfWsFli9/mGxEpKSSiw3DS6g0KDZEQm+jzooo" + "l1W4xpRLm0XUBOtheYFWrUJ3Gmwm8NDsdtK6J3OTTXNdtLwBYeKluihUm54R" + "G6u6hyfouszIlrRgkxatzau6sVLsjV1COrRjCON07QZa2Q3c0BrA9QrHtxet" + "sGgndDnckG3XkUrTjtiwVNEc4/hanZd7CcPMRcE1N32BAmqOErJGsNi4q9sO" + "QpaNKUuNaoKBYIWg0OCncWFGSyy9Rjh7U6vOhXooFRTSrQqlOTase+5GQ2dz" + "ZBE4nrDwVbuq49Z4yiIo8BRK7MvltDpXHbSC4biheoQfLt0FwTfIdlmqlWh6" + "KAZrYTzkC5qrJlI44tOkUHVnw0mk2ww+YsYTSitXm63+jDRrGDqbLuqYzI8d" + "yaHSKo/guIZEi5nJpaEtW1SPCVxESKuoO+uua1VdnhgmRcNLNbXDQQrDzZKj" + "g9SuaA/RQsyOnYEp1XE/LdZNKzGKm45nNKkJKo66LavZUsqasVjgOjobdvWO" + "LsyHIVOJQpJ2G6PekCYK4by9ccI6vDSG9qLaxtBSSo8GsoJvBAHhOCxWFuJg" + "LKBe3AAr6BrEgBg3iqkcOozWnixrJpHO1mqI2XKvNmki8qS1Gbe5dSMUlymZ" + "Gv5a5ZYmXKgi5GiqIXhnjHgVfTzXwRv0a7NX6/C57W7clm/aHJyg/hTbNasr" + "bZTmvzPQiVO3kxuldx/fHn3ZT7DPnR1AZTsb917tIDXf1fjwWx97QhM+gu7s" + "baO6MXRT7AevcvRUd07sij589R2cdn6OfLg1+YW3/us9/Z+33vgcjqXuP8Hn" + "ySE/2n7yS8xL1fftQNcdbFRedsJ9vNPF49uTZ0PwNhZ6/WOblPceWOKuTPEP" + "ggvfswR+jd3uy3Yoc9RssXKNXep3XaPt17LibTF0s6nH9NGdykN0vf25bGrn" + "FW89EO/2fXDV9sSr/ezF+8A12j6YFb8RQ7dk4uXo7OyZpnYo4Pv+DwLekVXe" + "C672noDtn42AO3uHs9mzdcTHnWxb1/GV+OD0Kd9YzT4S2a3FcWhPk1jXKAug" + "XI31kI31/Agvn+N3rqGoj2bF4zF0VtNDO9UzKOzP8MCz+v2hKp/4WahytKfK" + "0c9Uldnj7x7bdD0eUHrKMo9Sl9Q/637r6cc3n3xyu6c6VSI9huCrfTl0+cdL" + "2Wn0Q9c4UT/8puQHzKuf+s4/DV+/HwdvPtDFw5nor7qWLvatc8vh0Vxbyds+" + "k4/16WsY+3NZ8aljxs5q/uDQjn/4nA6yYuj5V/oSITtWvfuy75623+qon3ji" + "3I13PTH4m/ww/uB7mpt46EYjcZyj5ztH7s8EoW7YuQw3bU97gvzv8zH0wqui" + "NIZOG/sg/cst/RcBx1eij6HrQHmU8ssxdP4kJXDB/P8o3VeBNg/pYujM9uYo" + "ydNgdECS3X4tuMKZ4/ZAbHXqyAK45yO5SW5/NpMcdDl6qp/BL/9CbX+BS8Q9" + "lH/yCa7zpmcqH9l+VaA6ymaTjXIjD92w/cDhYJF84Kqj7Y91pvmKH936qZse" + "2gfyrVuGD/31CG/3X/kIv+EGcX7ovvnTu/74Nb/3xDfyg6H/BUhMCC46KAAA"); }
true
a47f3a4fc1c97fd462fae25660f777182ec25d5c
Java
Ruja159/Demo
/backend/donateblood/src/main/java/com/javaspring/donateblood/repository/BloodTypeRepository.java
UTF-8
304
1.851563
2
[]
no_license
package com.javaspring.donateblood.repository; import com.javaspring.donateblood.model.BloodType; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BloodTypeRepository extends JpaRepository<BloodType, Long> { }
true
3228fa023d9663e32183f1713108b85e85d4c177
Java
makelifeoutofdream/mobileapps
/wc/src/main/java/com/dream/wc/serviceimpl/AddressServiceImpl.java
UTF-8
819
2.046875
2
[]
no_license
package com.dream.wc.serviceimpl; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dream.wc.converter.AddressConverter; import com.dream.wc.dto.AddressDto; import com.dream.wc.repository.AddressRepository; import com.dream.wc.service.AddressService; @Service public class AddressServiceImpl implements AddressService{ @Autowired AddressRepository addressRepository; @Override @Transactional public List<AddressDto> getUserAddressList(Long userId) { return AddressConverter.addressListToAddressDtoList(addressRepository.findByUserId(userId)); } @Override @Transactional public void deleteAddress(Long addressId) { addressRepository.deleteById(addressId);; } }
true
e2292238e608734563743706f7d505b3836ac7d7
Java
vasanthvelusamy/DoeziPOC
/src/com/doezi/pages/GroupPagePost.java
UTF-8
625
2.15625
2
[]
no_license
package com.doezi.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class GroupPagePost { WebDriver driver; By newGroup = By.xpath("//div[@id='my_groups']/div/div[1]/a"); By newPost = By.id("advanced_activity_body"); By duzzButton = By.id("compose-submit"); public GroupPagePost(WebDriver driver){ this.driver = driver; } public void clickNewGroup(){ driver.findElement(newGroup).click(); } public void enterNewPost(){ driver.findElement(newPost).sendKeys("This is a test post"); } public void clickDuzzButton(){ driver.findElement(duzzButton).click(); } }
true
6ef4377c0125f5274aa4a95ad3c81e3d9edc8239
Java
1658544535/java
/src/com/tzmb2c/web/action/BrandDicAction.java
UTF-8
6,687
1.960938
2
[]
no_license
package com.tzmb2c.web.action; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import maowu.framework.utils.web.SuperAction; import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import com.tzmb2c.common.Pager; import com.tzmb2c.utils.FileUtil; import com.tzmb2c.utils.StringUtil; import com.tzmb2c.web.pojo.BrandDicPojo; import com.tzmb2c.web.service.BrandDicService; public class BrandDicAction extends SuperAction { @Autowired private BrandDicService brandDicService; private BrandDicPojo brandDicPojo; private List<BrandDicPojo> brandDicPojoList; private File upfile; private Integer option;// 用于判断操作类型 public List<BrandDicPojo> getBrandDicList() { return brandDicPojoList; } public void setBrandDicList(List<BrandDicPojo> brandDicPojoList) { this.brandDicPojoList = brandDicPojoList; } public BrandDicPojo getBrandDicPojo() { return brandDicPojo; } public void setBrandDicPojo(BrandDicPojo brandDicPojo) { this.brandDicPojo = brandDicPojo; } public File getUpfile() { return upfile; } public void setUpfile(File upfile) { this.upfile = upfile; } /** * 查询全部条数 */ public String brandDicListCount() throws Exception { try { if (page == null) { page = new Pager(); } Map<String, Object> map = new HashMap<String, Object>(); if (brandDicPojo != null) { map.put("brand", brandDicPojo.getBrand()); map.put("status", brandDicPojo.getStatus()); if (option != null) { map.put("option", option); } } int i = brandDicService.findBrandDicCount(map); page.setRowCount(i); } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } /** * 查询全部内容 */ public String brandDicListAll() throws Exception { try { Map<String, Object> map = new HashMap<String, Object>(); if (page == null) { page = new Pager(); } map.put("pageSize", 10); map.put("pageNo", (page.getPageNo() - 1) * page.getPageSize()); if (brandDicPojo != null) { map.put("brand", brandDicPojo.getBrand()); map.put("status", brandDicPojo.getStatus()); if (option != null) { map.put("option", option); } } brandDicPojoList = brandDicService.findBrandDicList(map); JSONArray json = JSONArray.fromObject(brandDicPojoList); page.setRowCount(brandDicPojoList.size()); page.setResult(json.toString()); } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } public Integer getOption() { return option; } public void setOption(Integer option) { this.option = option; } /** * 根据id删除 * * @return */ public String delBrandDic() throws Exception { try { brandDicService.delBrandDic(brandDicPojo); FileUtil.alertMessageBySkip("删除成功!", "brandDicList.do"); } catch (Exception e) { FileUtil.alertMessageBySkip("删除失败!", "brandDicList.do"); } return null; } /** * 编辑页面 * * @return * @throws Exception */ public String goUpdateBrandDic() throws Exception { if (brandDicPojo != null) { brandDicPojo = brandDicService.findBrandDicById(brandDicPojo.getId()); } return SUCCESS; } /** * 编辑百度用户浏览记录 * * @return * @throws Throwable */ public String updateBrandDic() throws Throwable { try { if (upfile != null) { String file_name = StringUtil.getCurrentDateStr() + ".jpg"; String uploadPath = ServletActionContext.getServletContext() .getRealPath("/upfiles/businessCenter/brandDic") + File.separator; FileUtil.uploadFile(file_name, uploadPath, "upfiles/businessCenter/brandDic", upfile); brandDicPojo.setLogo(file_name); } brandDicService.updateBrandDic(brandDicPojo); FileUtil.alertMessageBySkip("提交成功!", "brandDicList.do"); } catch (Exception e) { e.printStackTrace(); FileUtil.alertMessageBySkip("提交失败!", "brandDicList.do"); } return null; } /** * 提交编辑的用户积分 * * @return */ public String updateBrandDicOk() { try { brandDicService.updateBrandDic(brandDicPojo); FileUtil.alertMessageBySkip("修改成功!", "brandDicList.do"); } catch (Exception e) { e.printStackTrace(); FileUtil.alertMessageBySkip("修改失败!", "brandDicList.do"); } return null; } /** * 跳转新增页面 * * @return * @throws Exception */ public String addBrandDic() throws Exception { return SUCCESS; } /** * 新增提交 * * @return * @throws Throwable */ public String addBrandDicOK() throws Throwable { try { if (upfile != null) { String file_name = StringUtil.getCurrentDateStr() + ".jpg"; String uploadPath = ServletActionContext.getServletContext() .getRealPath("/upfiles/businessCenter/brandDic") + File.separator; FileUtil.uploadFile(file_name, uploadPath, "upfiles/businessCenter/brandDic", upfile); brandDicPojo.setLogo(file_name); } brandDicService.insertBrandDic(brandDicPojo); FileUtil.alertMessageBySkip("新增成功!", "brandDicList.do"); } catch (Exception e) { e.printStackTrace(); FileUtil.alertMessageBySkip("新增失败!", "brandDicList.do"); } return null; } /** * 根据id审核 * * @return */ public String checkBrandDic() throws Exception { try { brandDicService.checkBrandDic(brandDicPojo.getId()); FileUtil.alertMessageBySkip("审核成功!", "brandDicList.do"); } catch (Exception e) { FileUtil.alertMessageBySkip("审核失败!", "brandDicList.do"); } return null; } /** * 根据id取审 * * @return */ public String uncheckBrandDic() throws Exception { try { brandDicService.uncheckBrandDic(brandDicPojo.getId()); FileUtil.alertMessageBySkip("取审成功!", "brandDicList.do"); } catch (Exception e) { FileUtil.alertMessageBySkip("取审失败!", "brandDicList.do"); } return null; } }
true
86b8cab58ca96a99b42465337a7f8dd77a79c33c
Java
vinayak57/mobile-saas-medical-info-system
/MedicalInformationSystem/src/mis/resource/SocialHistoryResource.java
UTF-8
1,199
2.3125
2
[]
no_license
package mis.resource; import javax.ws.rs.Consumes; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import mis.dao.SocialHistoryDao; import mis.dao.SurgicalHistoryDao; import mis.model.SocialHistory; import mis.model.SurgicalHistory; @Path("/socialhistoryinfo") public class SocialHistoryResource { @PUT @Consumes(MediaType.APPLICATION_JSON) public Response putSocialHistory(SocialHistory patientMedInfo) { // return Response.status(201).entity(result).build(); //System.out.println(patient.getUsername()); return putAndGetResponse(patientMedInfo); } private Response putAndGetResponse(SocialHistory patientMedInfo) { Response res; // if (UserDao.instance.getAllUsers().containsKey(user.getUsername())) { // res = Response.noContent().build(); // } else { // res = Response.created(uriInfo.getAbsolutePath()).build(); // } if (SocialHistoryDao.instance.putSurgicalHistoryDetails(patientMedInfo) != 0) { String result = "prescription updated"; return Response.status(201).entity(result).build(); } else { return Response.noContent().build(); } } }
true
f39a20d2ae908f3a14a20c5b7db5587deffb1a9f
Java
gywnd6209/LAONIDE
/.svn/pristine/d5/d53d728d0b169345d98061a7ca5e1449eff235e3.svn-base
UTF-8
1,140
1.578125
2
[]
no_license
package kr.or.ddit.qaboard.service; import java.util.List; import java.util.Map; import org.springframework.web.multipart.MultipartFile; import kr.or.ddit.vo.QaboardVO; public interface IQaboardService { public QaboardVO qaboardInfo(Map<String, String> params) throws Exception; public List<QaboardVO> qaboardList(Map<String, String> params)throws Exception; // // public String insertFreeboardInfo(QaboardVO qaboardInfo, MultipartFile[] items) throws Exception; public String insertQaboardInfo(QaboardVO qaboardInfo) throws Exception; public void updateQaboardInfo(QaboardVO qaboardInfo) throws Exception; public void deleteQaboardInfo(Map<String, String> params) throws Exception; public void deleteQaboardReply(Map<String, String> params) throws Exception; // 댓글 public String insertQaboardReplyInfo(QaboardVO freeboardInfo) throws Exception; public QaboardVO qaboardReplyInfo(Map<String, String> params) throws Exception; // 페이지 public int totalCount(Map<String, String> params) throws Exception; // f5 방지 public void updateHit(Map<String, String> params) throws Exception; }
true
d348b8dd6686ebc11b061b1247615acffdc174d7
Java
baechuDeveloper/Coding-Test-Practice
/coding_test_subject_1/Dynamic_Programming_1/p8__LIS_false_problem.java
UHC
3,659
3.625
4
[]
no_license
package Dynamic_Programming_1; /** * ʿ LIS ڿ ݴ LIS * Ȥ * ʿ LIS ڿ ݴ LIS * 2 쿡 κ ´ٴ . * ġ LIS ݴ LIS ؼ ̸ ϴ° ´ ǥ̾. * * ϴµ ־ LB ſ ϰ Ҽ ְԵȴ. * */ import java.util.*; import java.io.*; // 11054 - κ public class p8__LIS_false_problem { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); int[] list = new int[N]; int[] reverse = new int[N]; for(int i=0; i<N; i++) { list[i] = Integer.parseInt(st.nextToken()); reverse[N-1-i] = list[i]; } int Lstart_max = 0, Rstart_max=0; int Lend = 0, Rend=0; int Lval = 0, Rval=0; //ʺ 빰 List<Integer> Lstart = new ArrayList<>(); List<Integer> Rstart = new ArrayList<>(); Lstart.add(list[0]); for(int i=1; i<N; i++) { int where = LB(Lstart, list[i]); if(Lstart.size() == where) { Lstart.add(list[i]); Lend = i; Lval=list[i]; } else { Lstart.set(where, list[i]); if(Lval == list[i]) Lend = i; } } for(int i=N-1; i>Lend; i--) { if(Rstart.size()==0) { for(int z=N-1; z>=0; z--) if(list[Lend]>list[z]) { Rstart.add(list[z]); i = z; break; } } else { int where = LB(Rstart, list[i]); if(list[Lend]<=list[i]) continue; if(Rstart.size() == where) { Rstart.add(list[i]); } else { Rstart.set(where, list[i]); } } } Lstart_max = Lstart.size() + Rstart.size(); //ʺ 빰 Lstart = new ArrayList<>(); Rstart = new ArrayList<>(); Rstart.add(reverse[0]); for(int i=1; i<N; i++) { int where = LB(Rstart, reverse[i]); if(Rstart.size() == where) { Rstart.add(reverse[i]); Rend = i; Rval = reverse[i]; } else { Rstart.set(where, reverse[i]); if(Rval == reverse[i]) Rend = i; } } for(int i=N-1; i>Rend; i--) { if(Lstart.size()==0) { for(int z=N-1; z>=0; z--) if(reverse[Rend]>reverse[z]) { Lstart.add(reverse[z]); i = z; break; } } else { int where = LB(Lstart, reverse[i]); if(reverse[Rend]<=reverse[i]) continue; if(Lstart.size() == where) { Lstart.add(reverse[i]); } else { Lstart.set(where, reverse[i]); } } } Rstart_max = Rstart.size() + Lstart.size(); System.out.println(Lstart_max+" "+ Rstart_max); System.out.println(Math.max(Lstart_max, Rstart_max)); }//===================================== // Lower_Bound ãϴ target ġ static int LB(List<Integer> list, int target) { int start = 0; int end = list.size(); int mid; while(start < end) { mid = (start + end)/2; if(list.get(mid) < target) // upper bound arr[mid] <= target ̸ ȴ. start = mid + 1; else end = mid; } return end; //ᱹ end 츮 ϴ ¸ . }//===================================== }
true
42d8aa7aa518d9a4bf81df790d697e4e42ffe661
Java
LiuwqGit/spring-boot-eureka
/messageContentEntity/src/main/java/com/yyit/marketOperation/message/entities/MessageRecordVO.java
UTF-8
2,009
2.109375
2
[]
no_license
package com.yyit.marketOperation.message.entities; import java.util.Date; public class MessageRecordVO { private String id; // ObjectId,可以作为记录id private String meetingId;//会议ID private String msgContent;// 消息内容 private int msgType;// 消息类型 private Date sendTime;// 消息发送时间 private String senderName;//发送消息的人员姓名 private String senderId;//发送消息的人员唯一Id private String senderImage;//发送消息人员图片 private Boolean onthewallStatus;//上墙状态 0 false 未上墙, 1 true 已上墙 private Boolean isDeleted;//删除状态 0 false 未删除, 1 true 已删除 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMeetingId() { return meetingId; } public void setMeetingId(String meetingId) { this.meetingId = meetingId; } public String getMsgContent() { return msgContent; } public void setMsgContent(String msgContent) { this.msgContent = msgContent; } public int getMsgType() { return msgType; } public void setMsgType(int msgType) { this.msgType = msgType; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } public String getSenderName() { return senderName; } public void setSenderName(String senderName) { this.senderName = senderName; } public String getSenderId() { return senderId; } public void setSenderId(String senderId) { this.senderId = senderId; } public String getSenderImage() { return senderImage; } public void setSenderImage(String senderImage) { this.senderImage = senderImage; } public Boolean getOnthewallStatus() { return onthewallStatus; } public void setOnthewallStatus(Boolean onthewallStatus) { this.onthewallStatus = onthewallStatus; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } }
true
993ab49588c8d09abe31d987439a23bcab493a61
Java
mkp1104/localEclipseWorkspaceJava
/object_part5/src/com/lara/Test.java
UTF-8
304
2.578125
3
[ "MIT" ]
permissive
package com.lara; class T { } public class Test { public static void main(String[] args) { T t1=new T(); String s1="12"; String s2="12"; String s3="abc"; String s4="t1.getClass()"; System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); } }
true
7d6377885ad336604ad7fe0bd36512d79246488f
Java
masterzz/springcloud-learn
/springcloud_sell/product/product-server/src/test/java/com/zhubr/product/service/ProductServiceTest.java
UTF-8
1,102
1.921875
2
[]
no_license
package com.zhubr.product.service; import com.zhubr.product.dto.CartDTO; import com.zhubr.product.ProductApplicationTests; import com.zhubr.product.dataobject.ProductInfo; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Component public class ProductServiceTest extends ProductApplicationTests { @Autowired ProductService productService; @Test public void findUpAll() throws Exception { List<ProductInfo> upAll = productService.findUpAll(); Assert.assertTrue(upAll.size() > 0); } @Test public void findList() throws Exception { List<ProductInfo> upAll = productService.findList(Arrays.asList("157875196366160022", "157875227953464068")); Assert.assertTrue(upAll.size() > 0); } @Test public void decreaseStock() throws Exception { CartDTO cartDTO = new CartDTO("157875196366160022",2); productService.decreaseStock(Arrays.asList(cartDTO)); } }
true
0562a82a6817f90032af8726d73b989dcf7a4eeb
Java
rucha-shah/demoproject
/src/main/java/com/training/demoproject/dto/DepartmentDTO.java
UTF-8
1,098
2.328125
2
[]
no_license
package com.training.demoproject.dto; public class DepartmentDTO { private int departmentId; private String name; private String departmentCode; private int parentDepartment; private int organizationId; public int getDepartmentId() { return departmentId; } public void setDepartmentId(int departmentId) { this.departmentId = departmentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartmentCode() { return departmentCode; } public void setDepartmentCode(String departmentCode) { this.departmentCode = departmentCode; } public int getParentDepartment() { return parentDepartment; } public void setParentDepartment(int parentDepartment) { this.parentDepartment = parentDepartment; } public int getOrganizationId() { return organizationId; } public void setOrganizationId(int organizationId) { this.organizationId = organizationId; } }
true