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
96f02cad89dbdbc33c99a7f1239d99e59b98ee1f
Java
nashi8128/global-input-services
/src/main/java/uk/co/globalinput/data/QRMessage.java
UTF-8
732
2.1875
2
[ "Apache-2.0" ]
permissive
package uk.co.globalinput.data; import com.fasterxml.jackson.core.JsonProcessingException; import uk.co.globalinput.util.GlobalInputUtil; public class QRMessage { private String se; private String cl; private String dt; public String getDt() { return dt; } public void setDt(String dt) { this.dt = dt; } public String getSe() { return se; } public void setSe(String se) { this.se = se; } public String getCl() { return cl; } public void setCl(String cl) { this.cl = cl; } public String toJsonString() throws JsonProcessingException{ com.fasterxml.jackson.databind.ObjectMapper objectMapper=GlobalInputUtil.createObjectMapper(); String content=objectMapper.writeValueAsString(this); return content; } }
true
59dce9bfd4331bdaaab122658d88760418790c63
Java
lostinthee/SimpleMybatis
/src/main/java/com/inthee/bean/Cust.java
UTF-8
974
2.296875
2
[]
no_license
/** *  中科金财 * Copyright (c) 2015-2018 zkjc,Inc.All Rights Reserved. */ package com.inthee.bean; import java.math.BigDecimal; /** * * @author dingyi * @version $Id: Cust.java, v 0.1 2018年03月25日 下午17:31 dingyi Exp $ */ public class Cust { private String id; private BigDecimal money; private String mobile; public String getId() { return id; } public void setId(String id) { this.id = id; } public BigDecimal getMoney() { return money; } public void setMoney(BigDecimal money) { this.money = money; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Override public String toString() { return "Cust{" + "id='" + id + '\'' + ", money=" + money + ", mobile='" + mobile + '\'' + '}'; } }
true
282c453a6f11d8a42a1cbe78013208e59913abea
Java
gupta19chirag/Projects
/Java/addTwoNumbers.java
UTF-8
1,596
3.265625
3
[]
no_license
package demo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class addTwoNumbers { public static void main(String[] args) { add obj = new add(); } } class add extends JFrame implements ActionListener{ JTextField num1, num2; JButton button; JLabel l; public add() { // JPanel panel = new JPanel(); setLayout(null); // add(panel); JLabel firstNum = new JLabel("First Number :"); firstNum.setBounds(10, 20, 80, 25); add(firstNum); num1 = new JTextField(5); num1.setBounds(120, 20, 50, 25); add(num1); JLabel secondNumber = new JLabel("Second Number:"); secondNumber.setBounds(10, 50, 100, 25); add(secondNumber); num2 = new JTextField(5); num2.setBounds(120, 50, 50, 25); add(num2); button = new JButton("ADD"); button.addActionListener(this); button.setBounds(10, 80, 80, 25); add(button); l = new JLabel("Result: "); l.setBounds(10, 110, 90, 25); add(l); setVisible(true); setSize(250, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { int n1 = Integer.parseInt(num1.getText()); int n2 = Integer.parseInt(num2.getText()); // If we want to use two button simeltaneously then use code:- /*if(e.getSource() == b1) * * else */ int sum; sum = n1 + n2; l.setText("Result : "+sum +""); } }
true
da41529c712f44e6e60f873cad3c0d813b8eba67
Java
yuehengyu/Leetcode
/src/com/yhy/leetcode/Leetcode204_CountPrimes.java
UTF-8
1,115
3.5
4
[]
no_license
package com.yhy.leetcode; public class Leetcode204_CountPrimes { public int countPrimes1(int n) { if (n <= 1) return 0; boolean[] notPrime = new boolean[n]; notPrime[0] = true; notPrime[1] = true; for (int i = 2; i < Math.sqrt(n); i++) { if (!notPrime[i]) { for (int j = i; i * j < n; j++) {//注意这里的索引值,答案都是从2开始 我个人认为从i开始就可以了 2*3 = 3*2 notPrime[j * i] = true; } } } int res = 0; for (boolean noPrime : notPrime) { if (!noPrime) res++; } return res; } public int countPrimes2(int n) { int res = 0; boolean[] notPrime = new boolean[n]; for (int i = 2; i < n; i++) {//注意这里的索引 不能从0开始 if (!notPrime[i]) { res++; for (int j = 2; i * j < n; j++) { notPrime[j * i] = true; } } } return res; } }
true
308ff2b47be83c7947acb1ea94f6c9728aed6d2a
Java
digid0c/design_patterns
/src/memento/AddStepCommand.java
UTF-8
379
2.375
2
[]
no_license
package memento; public class AddStepCommand extends AbstractWorkflowCommand { private String step; public AddStepCommand(WorkflowDesigner receiver, String step) { super(receiver); this.step = step; } @Override public void execute() { this.workflowSnapshot = receiver.getWorkflowSnapshot(); receiver.addStep(step); } }
true
535af4e32c029a21433495e44f11749a0b195a50
Java
abdirahmanali1997/Calculus
/calculus/source/ParametricAreaGraph.java
UTF-8
1,076
2.8125
3
[]
no_license
import java.awt.*; import java.awt.geom.*; import java.awt.event.*; public class ParametricAreaGraph extends ParametricGraph{ public ParametricAreaGraph( CalculusApplet applet, String f, String g, double a, double b, int n ){ super(); this.applet = applet; this.a = a; this.b = b; this.n = n; F.parseExpression( f ); G.parseExpression( g ); } public void draw( Graphics2D g ){ double delta = (b-a)/n; F.addVariable( "t", a ); double x0 = F.getValue(); double x1; double y; Rectangle2D rect; double[] P; if ( newStat ) stat = 0.0; g.setColor( red ); for ( int i=0; i<n; i++ ){ F.addVariable( "t", a + (i+1)*delta ); x1 = F.getValue(); G.addVariable( "t", a + (i+0.5)*delta ); y = G.getValue(); if ( newStat ) stat += y*(x1-x0); y *= scale; P = toScreenPoint( Math.min(x0,x1), 0 ); rect = new Rectangle2D.Double( P[0], P[1]-(y>0?y:0), Math.abs(x1-x0)*scale, Math.abs(y) ); g.fill( rect ); x0 = x1; } newStat = false; if ( n == 0 ) stat = 0.0; applet.setStat( "Area \u2248 ", stat, Color.red ); } }
true
d826bab39c2188623b3c5f9a15144fd869c5fbe9
Java
emovie/DesignPattern
/DesingPattern/src/factoryMethod/framework/ItemCreate.java
UTF-8
777
3.03125
3
[]
no_license
package factoryMethod.framework; public abstract class ItemCreate { // 팩토리 메서드 -> 템플릿 메서드 public Item create() { // 템플릿 메서드 패턴으 이용 -> 단계가 있음 (?) Item item; requestItemInformation(); item = createItem(); createItemLog(); System.out.println("main test commit"); return item; } // 아이템을 생성하기 전에 DB에서 아이템 정보를 요청 abstract protected void requestItemInformation(); // 아이템을 생성 후 아이템 복제 등의 불법을 방지하기 위해 DB에 아이템 생성 정보를 남김 abstract protected void createItemLog(); // 아이템을 생성하는 알고리즘 abstract protected Item createItem(); }
true
7e5547c12da383703df5885cd83526b653149051
Java
daiyirui/BlogBackStore
/src/com/back/dao/impl/AdminDaoImpl.java
UTF-8
3,496
2.484375
2
[]
no_license
package com.back.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.back.common.JDBCUtil; import com.back.dao.IAdminDao; import com.back.po.Admins; import com.back.po.Permissions; public class AdminDaoImpl implements IAdminDao { @Override public List<Admins> AdminsList() { List<Admins> lstAdmin = new ArrayList<Admins>(); PreparedStatement statement = null; Connection connection = null; ResultSet rs=null; try { connection = JDBCUtil.getConn(); String sql="SELECT * FROM admins"; statement = connection.prepareStatement(sql); rs=statement.executeQuery(); while(rs.next()){ Admins admin=new Admins(); admin.setAid(rs.getInt("aid")); admin.setA_pid(rs.getInt("a_pid")); admin.setAname(rs.getString("aname")); admin.setApwd(rs.getString("apwd")); admin.setAdate(rs.getDate("adate")); admin.setArealname(rs.getString("arealname")); admin.setAsex(rs.getString("asex")); admin.setAremarks(rs.getString("aremarks")); Permissions permission=new Permissions(); String sql1="SELECT * FROM permissions where pid=?"; statement = connection.prepareStatement(sql1); statement.setInt(1, rs.getInt("a_pid")); ResultSet re=statement.executeQuery(); if(re.next()){ permission.setPid(re.getInt("pid")); permission.setPname(re.getString("pname")); permission.setPcontent(re.getString("pcontent")); permission.setPremarks(re.getString("premarks")); admin.setPermission(permission); } lstAdmin.add(admin); } } catch (SQLException e) { e.printStackTrace(); return null; }finally{ JDBCUtil.closeDB(connection, statement, rs); } return lstAdmin; } @Override public Admins LoginBackStrone(String aname, String apwd) { PreparedStatement statement = null; Connection connection = null; ResultSet rs=null; try { connection = JDBCUtil.getConn(); String sql="SELECT * FROM admins where aname=? and apwd=?"; statement = connection.prepareStatement(sql); statement.setString(1, aname); statement.setString(2, apwd); rs=statement.executeQuery(); Admins admin=null; if(rs.next()){ admin=new Admins(); admin.setAid(rs.getInt("aid")); admin.setA_pid(rs.getInt("a_pid")); admin.setAname(rs.getString("aname")); admin.setApwd(rs.getString("apwd")); admin.setAdate(rs.getDate("adate")); admin.setArealname(rs.getString("arealname")); admin.setAsex(rs.getString("asex")); admin.setAremarks(rs.getString("aremarks")); Permissions permission=new Permissions(); String sql1="SELECT * FROM permissions where pid=?"; statement = connection.prepareStatement(sql1); statement.setInt(1, rs.getInt("a_pid")); ResultSet re=statement.executeQuery(); if(re.next()){ permission.setPid(re.getInt("pid")); permission.setPname(re.getString("pname")); permission.setPcontent(re.getString("pcontent")); permission.setPremarks(re.getString("premarks")); admin.setPermission(permission); } return admin; }else{ return null; } } catch (SQLException e) { e.printStackTrace(); return null; }finally{ JDBCUtil.closeDB(connection, statement, rs); } } }
true
9c53b1ab618a47ee97c0d7c3a9f74418c0132fd5
Java
vibha14-dotcom/vibha14-dotcom
/src/seleniumPractice/ImplicitIsDisplayed.java
UTF-8
1,044
2.34375
2
[]
no_license
package seleniumPractice; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ImplicitIsDisplayed { public static void main (String[]args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver" ,"E:\\Software Testing\\Selenium S_W\\Chrome Documentation\\chromedriver_win32\\chromedriver.exe"); WebDriver d = new ChromeDriver(); d.manage().window().maximize(); d.navigate().to("https://www.facebook.com/reg/"); d.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // below code is for IsEnabled WebElement fblogo = d.findElement(By.xpath("//img[@class='fb_logo _registrationPage__fbLogo img']")); boolean res = fblogo.isDisplayed(); if(res==true){ System.out.println("test senario is passed"); } else{ System.out.println("test senario is failed"); } Thread.sleep(3000); d.quit(); } }
true
3589afb116e773cd233e2e6b9cb5dadb2e7c9411
Java
oharaandrew314/3303Bomberman
/src/server/controllers/CLAParser.java
UTF-8
2,324
2.796875
3
[]
no_license
package server.controllers; import common.models.Grid; import java.awt.Dimension; import server.content.CreateGridException; import server.content.GridGenerator; import server.content.GridLoader; public class CLAParser { public static Grid parse(String[] args) { Grid grid = null; boolean showHelp = false; if (args.length > 0) { switch (args[0]) { case "load": if (args.length == 2) { try { grid = GridLoader.loadGrid(args[1]); } catch(CreateGridException e) { System.out.println(e.getMessage()); showHelp = true; } } else { showHelp = true; } break; case "random": if (args.length == 3 || args.length == 4) { try { Dimension dimension = new Dimension(Integer.parseInt(args[1]), Integer.parseInt(args[2])); if (args.length == 3) { grid = GridGenerator.createRandomGrid(dimension); } else { grid = GridGenerator.createRandomGrid(dimension, Integer.parseInt(args[3])); } } catch(NumberFormatException e) { showHelp = true; } } else { showHelp = true; } break; case "help": showHelp = true; break; } } else { showHelp = true; } if (showHelp) { System.out.println("Usage: server <command>"); System.out.println("Available commands:"); System.out.println(" load <gridName> Load a predefined json grid"); System.out.println(" random <width> <height> [<seed>] Generate a random grid"); System.out.println(" help Show this help file"); System.exit(0); } return grid; } }
true
b60ab94727a0e7e41d1edeba1b4f1d366cd0abeb
Java
Conchobhar/coursera-algorithms-part1
/src/wk2/Sorter.java
UTF-8
3,226
4.3125
4
[]
no_license
package wk2; public class Sorter { private Sorter() { } // Selection sort // For each element in the array, find the smallest element after it and replace it if found. // 1/2 N**2 public static void selectionSort(Comparable[] a) { int n = a.length; int im; for (int i = 0; i < n; i++) { im = i; for (int j = im; j < n; j++) { // Find the min if (less(a[j], a[im])) im = j; if (i != im) exch(a, i, im); } } } // Insertion sort // 1/4 N **2, but near linear for partially sorted arrays // For each element along the array, we move it backwards until it is no longer // greater than the element behind it. // This means the left wing of the array behind our initial iterator is kept sorted. public static void insertionSort(Comparable[] a) { for (int i = 1; i < a.length; i++) { for (int j = i; j > 0; j--) { if (less(a[j], a[j-1])) exch(a, j, j-1); else break; } } } // Shell sort (invented by Shell 1959) // Move entries more than one position at a time by h-sorting the array // i.e. we perform several insertion sorts but with decreasing strides // until the stride == 1, and the full insertion sort is performed over a partially sorted array. // with 3x+1 O(n**(3/2)) public static void shellSort(Comparable[] a) { int n = a.length; int h = 1; // Iteratively increase the stride h until the stride will at most sort 2 elements. while (h < n/3) h = 3*h + 1; while (h >= 1) { for (int i = 1; i < n; i += h) { for (int j = i; j > 0; j--) { if (less(a[j], a[j-1])) exch(a, j, j-1); else break; } } h /= 3; } } private static int randInt(int min, int max) { return (int) ((Math.random() * (max - min)) + min); } // Knuth Shuffle // Uniformly shuffle an array. // i.e. all n! (factorial) permutations should be possible, with equal probability. // As we increment i, we only exchange i with elements up to and including i. public static void knuthShuffle(Comparable[] a) { int r, n = a.length; for (int i = 1; i < n; i++) { r = randInt(0, i); exch(a, i, r); } } // Compare if first arg is less than second. private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; } // Exchange values at two indices private static void exch(Comparable[] a, int i, int j) { Comparable swap = a[i]; a[i] = a[j]; a[j] = swap; } public static void main(String[] args) { Integer[] array = {7, 3, 8, 5, 2}; System.out.println("Current array:"); for (int i : array) { System.out.print(String.valueOf(i) + ' '); } Sorter.shellSort(array); System.out.println("\nSorted array:"); for (int i : array) { System.out.print(String.valueOf(i) + ' '); } } }
true
e517cd6467146a2ad1639116ed56c69b662893d4
Java
LionKe22/CULTERAPP
/CULTERAP2/Objects/src/com/testdb/b4xlisttemplate.java
UTF-8
13,206
1.804688
2
[]
no_license
package com.testdb; import anywheresoftware.b4a.BA; import anywheresoftware.b4a.B4AClass; import anywheresoftware.b4a.BALayout; import anywheresoftware.b4a.debug.*; public class b4xlisttemplate extends B4AClass.ImplB4AClass implements BA.SubDelegator{ private static java.util.HashMap<String, java.lang.reflect.Method> htSubs; private void innerInitialize(BA _ba) throws Exception { if (ba == null) { ba = new BA(_ba, this, htSubs, "com.testdb.b4xlisttemplate"); if (htSubs == null) { ba.loadHtSubs(this.getClass()); htSubs = ba.htSubs; } } if (BA.isShellModeRuntimeCheck(ba)) this.getClass().getMethod("_class_globals", com.testdb.b4xlisttemplate.class).invoke(this, new Object[] {null}); else ba.raiseEvent2(null, true, "class_globals", false); } public anywheresoftware.b4a.keywords.Common __c = null; public anywheresoftware.b4a.objects.B4XViewWrapper.XUI _vvvvvvvvvvvvv2 = null; public anywheresoftware.b4a.objects.B4XViewWrapper _vvvvvvvvvvvvv1 = null; public b4a.example3.customlistview _customlistview1 = null; public anywheresoftware.b4a.objects.collections.List _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv3 = null; public String _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv4 = ""; public com.testdb.b4xdialog _vvvvvvvvvvvvvvvvvvvvvv3 = null; public boolean _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv5 = false; public int _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv6 = 0; public anywheresoftware.b4a.objects.collections.List _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7 = null; public int _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv0 = 0; public b4a.example.dateutils _vvvvvvv5 = null; public com.testdb.main _vvvvvvv6 = null; public com.testdb.starter _vvvvvvv7 = null; public com.testdb.httputils2service _vvvvvvv0 = null; public com.testdb.b4xcollections _vvvvvvvv1 = null; public String _class_globals() throws Exception{ //BA.debugLineNum = 1;BA.debugLine="Sub Class_Globals"; //BA.debugLineNum = 2;BA.debugLine="Private xui As XUI"; _vvvvvvvvvvvvv2 = new anywheresoftware.b4a.objects.B4XViewWrapper.XUI(); //BA.debugLineNum = 3;BA.debugLine="Public mBase As B4XView"; _vvvvvvvvvvvvv1 = new anywheresoftware.b4a.objects.B4XViewWrapper(); //BA.debugLineNum = 4;BA.debugLine="Public CustomListView1 As CustomListView"; _customlistview1 = new b4a.example3.customlistview(); //BA.debugLineNum = 5;BA.debugLine="Public Options As List"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv3 = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 6;BA.debugLine="Public SelectedItem As String"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv4 = ""; //BA.debugLineNum = 7;BA.debugLine="Private xDialog As B4XDialog"; _vvvvvvvvvvvvvvvvvvvvvv3 = new com.testdb.b4xdialog(); //BA.debugLineNum = 8;BA.debugLine="Public AllowMultiSelection As Boolean"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv5 = false; //BA.debugLineNum = 9;BA.debugLine="Public SelectionColor As Int = 0xAA0086FF"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv6 = (int) (0xaa0086ff); //BA.debugLineNum = 10;BA.debugLine="Public SelectedItems As List"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7 = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 11;BA.debugLine="Public MultiSelectionMinimum As Int = 0"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv0 = (int) (0); //BA.debugLineNum = 12;BA.debugLine="End Sub"; return ""; } public String _customlistview1_itemclick(int _index,Object _value) throws Exception{ b4a.example3.customlistview._clvitem _item = null; //BA.debugLineNum = 76;BA.debugLine="Private Sub CustomListView1_ItemClick (Index As In"; //BA.debugLineNum = 77;BA.debugLine="If Value = \"\" Then Return"; if ((_value).equals((Object)(""))) { if (true) return "";}; //BA.debugLineNum = 78;BA.debugLine="If AllowMultiSelection Then"; if (_vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv5) { //BA.debugLineNum = 79;BA.debugLine="Dim Item As CLVItem = CustomListView1.GetRawList"; _item = _customlistview1._getrawlistitem(_index); //BA.debugLineNum = 80;BA.debugLine="SelectItem (Item, True)"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv2(_item,__c.True); }else { //BA.debugLineNum = 82;BA.debugLine="SelectedItem = Value"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv4 = BA.ObjectToString(_value); //BA.debugLineNum = 83;BA.debugLine="SelectedItems.Clear"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.Clear(); //BA.debugLineNum = 84;BA.debugLine="SelectedItems.Add(Value)"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.Add(_value); //BA.debugLineNum = 85;BA.debugLine="xDialog.Close(xui.DialogResponse_Positive)"; _vvvvvvvvvvvvvvvvvvvvvv3._vvvvvvvvvvvvvvvvvvvvvvvvvvv7 /*boolean*/ (_vvvvvvvvvvvvv2.DialogResponse_Positive); }; //BA.debugLineNum = 87;BA.debugLine="End Sub"; return ""; } public String _dialogclosed(int _result) throws Exception{ //BA.debugLineNum = 89;BA.debugLine="Private Sub DialogClosed(Result As Int) 'ignore"; //BA.debugLineNum = 91;BA.debugLine="End Sub"; return ""; } public anywheresoftware.b4a.objects.B4XViewWrapper _getpanel(com.testdb.b4xdialog _dialog) throws Exception{ //BA.debugLineNum = 37;BA.debugLine="Public Sub GetPanel (Dialog As B4XDialog) As B4XVi"; //BA.debugLineNum = 38;BA.debugLine="Return mBase"; if (true) return _vvvvvvvvvvvvv1; //BA.debugLineNum = 39;BA.debugLine="End Sub"; return null; } public String _initialize(anywheresoftware.b4a.BA _ba) throws Exception{ innerInitialize(_ba); //BA.debugLineNum = 14;BA.debugLine="Public Sub Initialize"; //BA.debugLineNum = 15;BA.debugLine="mBase = xui.CreatePanel(\"mBase\")"; _vvvvvvvvvvvvv1 = _vvvvvvvvvvvvv2.CreatePanel(ba,"mBase"); //BA.debugLineNum = 16;BA.debugLine="mBase.SetLayoutAnimated(0, 0, 0, 300dip, 300dip)"; _vvvvvvvvvvvvv1.SetLayoutAnimated((int) (0),(int) (0),(int) (0),__c.DipToCurrent((int) (300)),__c.DipToCurrent((int) (300))); //BA.debugLineNum = 17;BA.debugLine="mBase.LoadLayout(\"ListTemplate\")"; _vvvvvvvvvvvvv1.LoadLayout("ListTemplate",ba); //BA.debugLineNum = 18;BA.debugLine="mBase.SetColorAndBorder(xui.Color_Transparent, 0,"; _vvvvvvvvvvvvv1.SetColorAndBorder(_vvvvvvvvvvvvv2.Color_Transparent,(int) (0),(int) (0),(int) (0)); //BA.debugLineNum = 19;BA.debugLine="CustomListView1.sv.SetColorAndBorder(xui.Color_Tr"; _customlistview1._sv.SetColorAndBorder(_vvvvvvvvvvvvv2.Color_Transparent,(int) (0),(int) (0),(int) (0)); //BA.debugLineNum = 20;BA.debugLine="CustomListView1.DefaultTextBackgroundColor = 0xFF"; _customlistview1._defaulttextbackgroundcolor = (int) (0xff555555); //BA.debugLineNum = 21;BA.debugLine="CustomListView1.DefaultTextColor = xui.Color_Whit"; _customlistview1._defaulttextcolor = _vvvvvvvvvvvvv2.Color_White; //BA.debugLineNum = 26;BA.debugLine="Options.Initialize"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv3.Initialize(); //BA.debugLineNum = 27;BA.debugLine="SelectedItems.Initialize"; _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.Initialize(); //BA.debugLineNum = 28;BA.debugLine="End Sub"; return ""; } public String _vvvvvvvvvvvvvvvvvvvvvvvvvvvv4(int _width,int _height) throws Exception{ //BA.debugLineNum = 31;BA.debugLine="Public Sub Resize(Width As Int, Height As Int)"; //BA.debugLineNum = 32;BA.debugLine="mBase.SetLayoutAnimated(0, 0, 0, Width, Height)"; _vvvvvvvvvvvvv1.SetLayoutAnimated((int) (0),(int) (0),(int) (0),_width,_height); //BA.debugLineNum = 33;BA.debugLine="CustomListView1.Base_Resize(Width, Height)"; _customlistview1._base_resize(_width,_height); //BA.debugLineNum = 34;BA.debugLine="End Sub"; return ""; } public String _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv2(b4a.example3.customlistview._clvitem _item,boolean _toggle) throws Exception{ int _index = 0; boolean _selected = false; //BA.debugLineNum = 59;BA.debugLine="Private Sub SelectItem (Item As CLVItem, Toggle As"; //BA.debugLineNum = 60;BA.debugLine="Dim index As Int = SelectedItems.IndexOf(Item.Val"; _index = _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.IndexOf(_item.Value); //BA.debugLineNum = 61;BA.debugLine="Dim Selected As Boolean = index > -1"; _selected = _index>-1; //BA.debugLineNum = 62;BA.debugLine="If Toggle Then Selected = Not(Selected)"; if (_toggle) { _selected = __c.Not(_selected);}; //BA.debugLineNum = 63;BA.debugLine="If Selected Then"; if (_selected) { //BA.debugLineNum = 64;BA.debugLine="If Not(Toggle) Then Item.Panel.Color = Selection"; if (__c.Not(_toggle)) { _item.Panel.setColor(_vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv6);}; //BA.debugLineNum = 65;BA.debugLine="Item.Color = CustomListView1.DefaultTextBackgrou"; _item.Color = _customlistview1._defaulttextbackgroundcolor; //BA.debugLineNum = 66;BA.debugLine="If index = -1 Then SelectedItems.Add(Item.Value)"; if (_index==-1) { _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.Add(_item.Value);}; }else { //BA.debugLineNum = 68;BA.debugLine="Item.Color = SelectionColor"; _item.Color = _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv6; //BA.debugLineNum = 69;BA.debugLine="If Not(Toggle) Then Item.Panel.Color = CustomLis"; if (__c.Not(_toggle)) { _item.Panel.setColor(_customlistview1._defaulttextbackgroundcolor);}; //BA.debugLineNum = 70;BA.debugLine="If index > -1 Then SelectedItems.RemoveAt(index)"; if (_index>-1) { _vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.RemoveAt(_index);}; }; //BA.debugLineNum = 72;BA.debugLine="xDialog.SetButtonState(xui.DialogResponse_Positiv"; _vvvvvvvvvvvvvvvvvvvvvv3._vvvvvvvvvvvvvvvvvvvvvvvvvvvv6 /*String*/ (_vvvvvvvvvvvvv2.DialogResponse_Positive,_vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7.getSize()>=_vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv0); //BA.debugLineNum = 73;BA.debugLine="End Sub"; return ""; } public void _show(com.testdb.b4xdialog _dialog) throws Exception{ ResumableSub_Show rsub = new ResumableSub_Show(this,_dialog); rsub.resume(ba, null); } public static class ResumableSub_Show extends BA.ResumableSub { public ResumableSub_Show(com.testdb.b4xlisttemplate parent,com.testdb.b4xdialog _dialog) { this.parent = parent; this._dialog = _dialog; } com.testdb.b4xlisttemplate parent; com.testdb.b4xdialog _dialog; Object _opt = null; int _i = 0; b4a.example3.customlistview._clvitem _item = null; anywheresoftware.b4a.BA.IterableList group3; int index3; int groupLen3; int step8; int limit8; @Override public void resume(BA ba, Object[] result) throws Exception{ while (true) { switch (state) { case -1: return; case 0: //C this.state = 1; //BA.debugLineNum = 42;BA.debugLine="xDialog = Dialog"; parent._vvvvvvvvvvvvvvvvvvvvvv3 = _dialog; //BA.debugLineNum = 43;BA.debugLine="CustomListView1.Clear"; parent._customlistview1._clear(); //BA.debugLineNum = 44;BA.debugLine="For Each opt As Object In Options"; if (true) break; case 1: //for this.state = 4; group3 = parent._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv3; index3 = 0; groupLen3 = group3.getSize(); this.state = 12; if (true) break; case 12: //C this.state = 4; if (index3 < groupLen3) { this.state = 3; _opt = group3.Get(index3);} if (true) break; case 13: //C this.state = 12; index3++; if (true) break; case 3: //C this.state = 13; //BA.debugLineNum = 45;BA.debugLine="CustomListView1.AddTextItem(opt, opt)"; parent._customlistview1._addtextitem(_opt,_opt); if (true) break; if (true) break; ; //BA.debugLineNum = 47;BA.debugLine="If AllowMultiSelection Then"; case 4: //if this.state = 11; if (parent._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv5) { this.state = 6; }if (true) break; case 6: //C this.state = 7; //BA.debugLineNum = 48;BA.debugLine="Sleep(20)"; parent.__c.Sleep(ba,this,(int) (20)); this.state = 14; return; case 14: //C this.state = 7; ; //BA.debugLineNum = 49;BA.debugLine="For i = 0 To CustomListView1.Size - 1"; if (true) break; case 7: //for this.state = 10; step8 = 1; limit8 = (int) (parent._customlistview1._getsize()-1); _i = (int) (0) ; this.state = 15; if (true) break; case 15: //C this.state = 10; if ((step8 > 0 && _i <= limit8) || (step8 < 0 && _i >= limit8)) this.state = 9; if (true) break; case 16: //C this.state = 15; _i = ((int)(0 + _i + step8)) ; if (true) break; case 9: //C this.state = 16; //BA.debugLineNum = 50;BA.debugLine="Dim item As CLVItem = CustomListView1.GetRawLis"; _item = parent._customlistview1._getrawlistitem(_i); //BA.debugLineNum = 51;BA.debugLine="SelectItem (item, False)"; parent._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv2(_item,parent.__c.False); if (true) break; if (true) break; case 10: //C this.state = 11; ; if (true) break; case 11: //C this.state = -1; ; //BA.debugLineNum = 54;BA.debugLine="Dialog.InternalAddStubToCLVIfNeeded(CustomListVie"; _dialog._vvvvvvvvvvvvvvvvvvvvvvvvvvvv2 /*String*/ (parent._customlistview1,parent._customlistview1._defaulttextbackgroundcolor); //BA.debugLineNum = 55;BA.debugLine="SelectedItem = \"\""; parent._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv4 = ""; //BA.debugLineNum = 57;BA.debugLine="End Sub"; if (true) break; } } } } public Object callSub(String sub, Object sender, Object[] args) throws Exception { BA.senderHolder.set(sender); if (BA.fastSubCompare(sub, "DIALOGCLOSED")) return _dialogclosed(((Number)args[0]).intValue()); if (BA.fastSubCompare(sub, "GETPANEL")) return _getpanel((com.testdb.b4xdialog) args[0]); return BA.SubDelegator.SubNotFound; } }
true
9f608c743d606a270b186d8ef2ecb99ad023dbd6
Java
liaochuanhai/MyCar
/src/com/cnlaunch/mycar/im/common/ImMsgIds.java
GB18030
1,754
1.796875
2
[]
no_license
package com.cnlaunch.mycar.im.common; public class ImMsgIds { //¼ public static final int ORDER_LOGIN = 0; public static final int REPLY_LOGIN = 1; //dz public static final int ORDER_LOGOUT = 2; public static final int REPLY_LOGOUT = 3; //б public static final int ORDER_UPDATE_ONLINE_LIST = 4; public static final int REPLY_ONLINE_LIST_UPDATED = 5; //б public static final int ORDER_UPDATE_FRIEND_LIST = 6; public static final int REPLY_FRIEND_LIST_UPDATED = 7; //б public static final int ORDER_UPDATE_FRIEND_ONLINE_LIST = 20; public static final int REPLY_FRIEND_ONLINE_LIST_UPDATED = 21; //Ϣ public static final int ORDER_SEND_CHAT_MESSAGE = 8; public static final int REPLY_SNED_CHAT_MESSAGE = 9; //ļ(˶ ORDER_UPLOAD_FILEĶ) public static final int ORDER_SNED_FILE = 10; public static final int REPLY_SNED_FILE = 11; //ļ public static final int ORDER_DOWNLOAD_FILE = 12; public static final int REPLY_DOWNLOAD_FILE = 13; //ϴļ public static final int ORDER_UPLOAD_FILE = 14; public static final int REPLY_UPLOAD_FILE = 15; //ܾļ public static final int ORDER_SEND_FILE_REFUSED = 16; public static final int REPLY_SEND_FILE_REFUSE = 17; //֪ͨļߣȥļ public static final int NOTICE_SEND_FILE_REQUEST_MESSAGE = 18; //֪ͨյϢ public static final int NOTICE_RECEIVE_CHAT_MESSAGE = 19; //Ӻ public static final int ORDER_ADD_FRIEND = 22; public static final int REPLY_ADD_FRIEND = 23; //ɾ public static final int ORDER_DEL_FRIEND = 24; public static final int REPLY_DEL_FRIEND = 25; }
true
3f42f868dab95fe45205d751da8cde493338230b
Java
rodmccutcheon/spring-cloud-contract-demo
/clock/target/generated-test-sources/contracts/com/rodmccutcheon/clock/ContractVerifierTest.java
UTF-8
2,138
1.851563
2
[]
no_license
package com.rodmccutcheon.clock; import com.rodmccutcheon.clock.BaseContractTestMessaging; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import javax.inject.Inject; import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper; import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage; import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging; import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat; import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*; import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson; import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers; import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes; @SuppressWarnings("rawtypes") public class ContractVerifierTest extends BaseContractTestMessaging { @Inject ContractVerifierMessaging contractVerifierMessaging; @Inject ContractVerifierObjectMapper contractVerifierObjectMapper; @Test public void validate_shouldProduceMessageToTriggerTimeoutApplier() throws Exception { // when: timeoutApplierClockSupplier(); // then: ContractVerifierMessage response = contractVerifierMessaging.receive("clock_timeout_applier"); assertThat(response).isNotNull(); // and: DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload())); assertThatJson(parsedJson).array().contains("['key']").isEqualTo("TIMEOUT_APPLIER"); assertThatJson(parsedJson).array().contains("['buildingId']").isEqualTo(1); assertThatJson(parsedJson).array().contains("['startTime']").isEqualTo("2020-12-03T05:43:07.824713Z"); assertThatJson(parsedJson).array().contains("['endTime']").isNull(); assertThatJson(parsedJson).array().contains("['buildingId']").isEqualTo(2); } }
true
7a4c6a78dd06520cf2f24dffb20b5e4b07c41d0b
Java
KleitonRufino/spring-statemachine
/demo-statemachine-persister-multipleDB/src/main/java/com/example/demo/config/IniciarDB.java
UTF-8
1,062
2.03125
2
[]
no_license
package com.example.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import com.example.demo.model.Ordem; import com.example.demo.model.Status; import com.example.demo.repository.OrdemRepository; @Configuration @EnableTransactionManagement public class IniciarDB implements CommandLineRunner{ @Autowired private OrdemRepository repository; @Override @Transactional("ordemTransactionManager") public void run(String... args) throws Exception { // TODO Auto-generated method stub repository.deleteAll(); Ordem ordem1 = new Ordem(); ordem1.setNome("ordem1"); ordem1.setStatus(Status.WAITING); repository.save(ordem1); Ordem ordem2 = new Ordem(); ordem2.setNome("ordem2"); ordem2.setStatus(Status.WAITING); repository.save(ordem2); } }
true
220d2bcf366eef66ff11ce4c54b588a370628072
Java
RussellRC/RussellTests
/algorithms/src/main/java/org/russell/algorithms/practice/unsorted/GetIntComplement.java
UTF-8
737
3.8125
4
[]
no_license
package org.russell.algorithms.practice.unsorted; /** * Get bitwise complement of a number * Example: Input: 10 (1010) Output: 5 (0101) */ public class GetIntComplement { public static void main(String[] args) { System.out.println(getIntComplement(10)); } private static int getIntComplement(int num) { final String binNum = Integer.toBinaryString(num); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < binNum.length(); i++) { if (binNum.charAt(i) == '0') { sb.append('1'); } else { sb.append('0'); } } return Integer.parseInt(sb.toString(), 2); } }
true
5d18e80caf195cfe937a764a72e062a9ec39ba22
Java
AntonKurbet/GeekBrains.Java2
/src/ru/geekbrains/java2/lesson3/PhoneBook.java
UTF-8
1,625
3.515625
4
[]
no_license
package ru.geekbrains.java2.lesson3; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; // 2. Написать простой класс ТелефонныйСправочник, который хранит в себе список фамилий и телефонных номеров. // В этот телефонный справочник с помощью метода add() можно добавлять записи. // С помощью метода get() искать номер телефона по фамилии. // Следует учесть, что под одной фамилией может быть несколько телефонов (в случае однофамильцев), // тогда при запросе такой фамилии должны выводиться все телефоны. public class PhoneBook { private HashMap<String,ArrayList<String>> book = new HashMap<>(); private HashMap<String,String> invertedBook = new HashMap<>(); public void add(String personName, String phoneNumber) { ArrayList<String> list = book.get(personName); if (list == null) list = new ArrayList<>(); list.add(phoneNumber); book.put(personName,list); invertedBook.put(phoneNumber,personName); } public ArrayList<String> get (String personName) { ArrayList<String> phones = book.get(personName); if (phones == null) phones = new ArrayList<>(); return phones; } public String getName (String phoneNumber) { return invertedBook.get(phoneNumber); } }
true
c5214b465c73ea5bd59f062f8e3b59d54b5a8bdb
Java
jasonbrianhall/Jaspersoft-Studio
/com.jaspersoft.studio/src/com/jaspersoft/studio/preferences/editor/sorttable/TableFieldEditor.java
UTF-8
7,608
2.015625
2
[]
no_license
/******************************************************************************* * Copyright (C) 2010 - 2016. TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. ******************************************************************************/ package com.jaspersoft.studio.preferences.editor.sorttable; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import com.jaspersoft.studio.preferences.editor.sorttable.model.ITableContentProvider; import com.jaspersoft.studio.preferences.editor.sorttable.model.TableViewerSorter; import com.jaspersoft.studio.preferences.editor.sorttable.model.TableViewerSorterHandler; public class TableFieldEditor extends FieldEditor { private Table table; private TableViewer viewer; private IStructuredContentProvider contentProvider; private ITableLabelProvider labelProvider; private Object input; private String[] columnHeaders; private TableViewerSorter sorter; private TableViewerSorterHandler sorterHandler; private int selectionColumn; private Object oldValue; public TableFieldEditor(String name, String labelText, Composite parent, IStructuredContentProvider contentProvider, ITableLabelProvider labelProvider, String[] columnHeaders, Object input) { this.contentProvider = contentProvider; this.labelProvider = labelProvider; this.columnHeaders = columnHeaders; this.input = input; this.init(name, labelText); this.createControl(parent); } public int getNumberOfControls() { return (1); } public void setSelectionColumn(int columnIndex) { this.selectionColumn = columnIndex; } public int getSelectionColumn() { return (this.selectionColumn); } public String getSelection() { IStructuredSelection selection = (IStructuredSelection) this.viewer.getSelection(); if (selection.isEmpty()) { return (""); } else if (this.selectionColumn == -1) { return (selection.getFirstElement().toString()); } else { return (this.labelProvider.getColumnText(selection.getFirstElement(), this.selectionColumn)); } } public void setSortingEnabled(boolean enabled) { if (this.contentProvider instanceof ITableContentProvider) { if (enabled) { this.sorter = new TableViewerSorter(this.viewer, (ITableContentProvider) this.contentProvider); this.sorterHandler = new TableViewerSorterHandler(this.table, this.sorter); this.viewer.setSorter(sorter); } else { this.sorter = null; this.sorterHandler = null; this.viewer.setSorter(null); } } } public boolean isSortingEnabled() { return (this.sorterHandler != null); } public void sort(int columnIndex, boolean ascending) { if (this.isSortingEnabled()) { this.sorterHandler.sort(columnIndex, ascending); } } public int getSortingColumn() { if (this.isSortingEnabled()) { return (this.sorter.getSortingColumn()); } else { return (-1); } } public boolean isSortAscending() { if (this.isSortingEnabled()) { return (this.sorter.isAscending()); } else { return (false); } } public void setColumnWidth(int columnIndex, int width) { if (columnIndex >= 0 && columnIndex < this.columnHeaders.length) { TableColumn column = this.table.getColumn(columnIndex); column.setWidth(width); } } public int getColumnWidth(int columnIndex) { if (columnIndex >= 0 && columnIndex < this.columnHeaders.length) { TableColumn column = this.table.getColumn(columnIndex); return (column.getWidth()); } else { return (0); } } protected void adjustForNumColumns(int numColumns) { GridData gd = (GridData) this.table.getLayoutData(); gd.horizontalSpan = numColumns - 1; gd.grabExcessHorizontalSpace = gd.horizontalSpan <= 1; } protected void doFillIntoGrid(Composite parent, int numColumns) { this.getLabelControl(parent); this.table = new Table(parent, SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); this.table.setHeaderVisible(true); this.table.setLinesVisible(false); this.table.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { valueChanged(); } public void widgetSelected(SelectionEvent e) { valueChanged(); } }); this.initializeColumns(); this.initializeViewer(); GridData gd = new GridData(); gd.horizontalSpan = numColumns - 1; gd.horizontalAlignment = GridData.FILL; gd.verticalAlignment = GridData.FILL; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; this.table.setLayoutData(gd); } protected void doLoad() { String value = this.getPreferenceStore().getString(this.getPreferenceName()); this.setSelection(value); this.oldValue = value; } protected void doLoadDefault() { String defaultValue = this.getPreferenceStore().getDefaultString(this.getPreferenceName()); this.setSelection(defaultValue); this.valueChanged(); } protected void doStore() { this.getPreferenceStore().setValue(this.getPreferenceName(), this.getSelection()); } protected void valueChanged() { this.setPresentsDefaultValue(false); IStructuredSelection selection = (IStructuredSelection) this.viewer.getSelection(); String newValue; if (selection.isEmpty()) { newValue = ""; } else if (this.selectionColumn == -1) { newValue = selection.getFirstElement().toString(); } else { newValue = this.labelProvider.getColumnText(selection.getFirstElement(), this.selectionColumn); } if (newValue.equals(oldValue)) { this.fireValueChanged(VALUE, oldValue, newValue); oldValue = newValue; } } private void initializeViewer() { this.viewer = new TableViewer(this.table); this.viewer.setContentProvider(this.contentProvider); this.viewer.setLabelProvider(this.labelProvider); this.viewer.setColumnProperties(this.columnHeaders); this.viewer.setInput(this.input); TableColumn column; for (int i = 0; i < this.columnHeaders.length; i++) { column = this.table.getColumn(i); column.pack(); } } private void initializeColumns() { TableColumn column; for (int i = 0; i < this.columnHeaders.length; i++) { column = new TableColumn(this.table, SWT.LEFT); column.setText(this.columnHeaders[i]); column.setToolTipText(this.columnHeaders[i]); } } private void setSelection(String selectionStr) { if (this.viewer != null) { Object[] items = this.contentProvider.getElements(this.viewer.getInput()); boolean selected = false; if (this.selectionColumn == -1) { for (int i = 0; i < items.length && !selected; i++) { if (selectionStr.equals(items[i].toString())) { StructuredSelection selection = new StructuredSelection(items[i]); this.viewer.setSelection(selection); selected = true; } } } else { for (int i = 0; i < items.length && !selected; i++) { if (selectionStr.equals(this.labelProvider.getColumnText(items[i], this.selectionColumn))) { StructuredSelection selection = new StructuredSelection(items[i]); this.viewer.setSelection(selection); selected = true; } } } } } }
true
b1541b3637f43701146c2253465fb2e5d5325a0e
Java
memorex386/infinite-scroll-viewpager-w-tabs
/app/src/main/java/com/memorex386/infiniteviewpagerandtabs/CircleTabIndicator.java
UTF-8
988
2.265625
2
[ "Apache-2.0" ]
permissive
package com.memorex386.infiniteviewpagerandtabs; import android.content.Context; import android.support.design.widget.TabLayout; import android.util.AttributeSet; import android.widget.FrameLayout; /** * Created by bradley.thome on 6/15/17. */ public class CircleTabIndicator extends FrameLayout implements InfiniteScroll.CustomTab { private TabLayout tabLayout; public CircleTabIndicator(Context context) { super(context); init(); } public CircleTabIndicator(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CircleTabIndicator(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void init() { inflate(getContext(), R.layout.view_circle_tab_indicator, this); tabLayout = (TabLayout) findViewById(R.id.tab_layout); } public TabLayout getTabLayout() { return tabLayout; } }
true
324f887b4c10cfbcb6c8618a259d25718deab82b
Java
08raj-prince97/car-system-rental
/src/com/car/rental/system/Contact.java
UTF-8
1,857
2.3125
2
[]
no_license
package com.car.rental.system; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Contact */ @WebServlet("/Contact") public class Contact extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session= request.getSession(); String name=request.getParameter("name"); System.out.println("name"+name); double mobile=Double.parseDouble(request.getParameter("mobile")); String email=request.getParameter("email"); String subject= request.getParameter("subject"); String message= request.getParameter("message"); String to = "pk250061@gmail.com"; Mailer.send(to, subject, message); PrintWriter out=response.getWriter(); String url ="jdbc:mysql://localhost:3306/car_rental_system"; String u ="root"; String p =""; String sql ="INSERT INTO contactreport SET name=?,mobile=?,email=?,subject=?,message=?"; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection) DriverManager.getConnection(url,u,p); PreparedStatement st = con.prepareStatement(sql); st.setString(1, name); st.setDouble(2, mobile); st.setString(3, email); st.setString(4, subject); st.setString(5, message); st.execute(); con.close(); response.sendRedirect("index.jsp"); }catch(Exception e) { e.printStackTrace(); } } }
true
41f964729bf40bc6fad463902009b4985aa8d0b2
Java
Adilbek97/ProjectTwitter
/app/src/main/java/com/example/ashirov/project_twitter_login/NavigationActivity.java
UTF-8
5,367
1.726563
2
[]
no_license
package com.example.ashirov.project_twitter_login; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.twitter.sdk.android.tweetcomposer.TweetComposer; import com.twitter.sdk.android.tweetui.SearchTimeline; import com.twitter.sdk.android.tweetui.TweetTimelineRecyclerViewAdapter; public class NavigationActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { TextView mUsername,mUserEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_navigation); //----------------------------- final RecyclerView recyclerView = findViewById(R.id.recyclerView1); recyclerView.setLayoutManager(new LinearLayoutManager(this)); final SearchTimeline searchTimeline = new SearchTimeline.Builder() .query("#hiking") .maxItemsPerRequest(50) .build(); final TweetTimelineRecyclerViewAdapter adapter = new TweetTimelineRecyclerViewAdapter.Builder(this) .setTimeline(searchTimeline) .setViewStyle(R.style.tw__TweetLightWithActionsStyle) .build(); recyclerView.setAdapter(adapter); //--------------------------------- // mUsername=findViewById(R.id.username); //mUserEmail=findViewById(R.id.userEmail1); // mUsername.setText(MainActivity.userName); // mUserEmail.setText(MainActivity.mUserEmail); // String name=getIntent().getStringExtra("name"); Toast.makeText(NavigationActivity.this,MainActivity.userName,Toast.LENGTH_SHORT).show(); // // mUserEmail.setText(mIntent.getStringExtra("email")); //-------------------------- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //eger chalishmassa resimi silmek lasim /* Uri imageUri = FileProvider.getUriForFile(NavigationActivity.this, BuildConfig.APPLICATION_ID + "com.example.myapp.fileprovider", new File("drawable/ic_launcher_backdround.png"));*/ TweetComposer.Builder builder = new TweetComposer.Builder(NavigationActivity.this) .text(" ..."); // .image(imageUri); builder.show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.navigation, menu); return true; } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { Intent intent=new Intent(NavigationActivity.this,UserTweet.class); startActivity(intent); // Handle the camera action } else if (id == R.id.nav_gallery) { Intent intent=new Intent(NavigationActivity.this,ExampleTweet.class); startActivity(intent); } else if (id == R.id.nav_slideshow) { Intent intent=new Intent(NavigationActivity.this,UserTime.class); startActivity(intent); }else if(id==R.id.nav_search){ Intent intent=new Intent(NavigationActivity.this,SearchActivity.class); startActivity(intent); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
true
c29d457846ae5fe4f11cbb515329ddd07da037ee
Java
azhangge/gateway
/src/main/java/com/huajie/educomponent/course/bo/CourseApproveHisBo.java
UTF-8
489
1.71875
2
[]
no_license
package com.huajie.educomponent.course.bo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; /** * Created by zgz on 2017/8/18. */ @Data public class CourseApproveHisBo { private String courseId; private String courseName; private String approverId; private int courseApproveStatus; private String reason; @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") private Date date; }
true
76bf0a4cd71f47d86754583ed75d04a6b5a95ba0
Java
play-project/play-governance
/governance-user-service/src/main/java/org/ow2/play/governance/user/ws/UserServiceImpl.java
UTF-8
1,320
2.109375
2
[]
no_license
/** * */ package org.ow2.play.governance.user.ws; import javax.jws.WebMethod; import org.ow2.play.governance.user.api.UserException; import org.ow2.play.governance.user.api.bean.User; import org.ow2.play.governance.user.api.ws.UserService; /** * @author chamerling * */ public class UserServiceImpl implements UserService { private org.ow2.play.governance.user.api.UserService userService; @Override @WebMethod public User getUser(String login) throws UserException { return userService.getUser(login); } @Override @WebMethod public User getUserFromProvider(String provider, String login) throws UserException { return userService.getUserFromProvider(provider, login); } @Override @WebMethod public User getUserFromToken(String token) throws UserException { return userService.getUserFromToken(token); } @Override @WebMethod public User update(User user) throws UserException { return userService.update(user); } @Override @WebMethod public User register(User user) throws UserException { return userService.register(user); } @Override @WebMethod public void delete(User user) throws UserException { userService.delete(user); } public void setUserService( org.ow2.play.governance.user.api.UserService userService) { this.userService = userService; } }
true
b8f17e4e2987cf27e7633ed8982c8e380d3a47e9
Java
debueb/pro-padel
/src/main/java/de/appsolve/padelcampus/db/dao/ModuleDAO.java
UTF-8
1,716
2.390625
2
[]
no_license
package de.appsolve.padelcampus.db.dao; import de.appsolve.padelcampus.constants.ModuleType; import de.appsolve.padelcampus.db.dao.generic.SortedGenericDAO; import de.appsolve.padelcampus.db.model.Module; import org.hibernate.Session; import org.springframework.stereotype.Component; import java.util.*; /** * @author dominik */ @Component public class ModuleDAO extends SortedGenericDAO<Module> implements ModuleDAOI { @Override public Module saveOrUpdate(Module entity) { if (entity.getSubModules() != null) { for (Module subModule : entity.getSubModules()) { subModule.setCustomer(getCustomer()); } } setCustomer(entity); Session session = entityManager.unwrap(Session.class); session.merge((entity)); return entity; } @Override public Module findByUrlTitle(String title) { title = title.replace("-", " "); return findByAttribute("urlTitle", title); } @Override public List<Module> findByModuleType(ModuleType moduleType) { Map<String, Object> attributeMap = new HashMap<>(); attributeMap.put("moduleType", moduleType); return findByAttributes(attributeMap); } @Override public List<Module> findAllRootModules() { //only get top level modules (e.g. remove all submodules) List<Module> modules = findAll(); Set<Module> modulesToRemove = new HashSet<>(); for (Module module : modules) { if (module.getSubModules() != null) { modulesToRemove.addAll(module.getSubModules()); } } modules.removeAll(modulesToRemove); return modules; } }
true
ee6b338e1245f80dcbc194367315bd611d832987
Java
ShikhaShrivastava/Java-Daily-Task
/Day6/ExceptionHandlingTask.java
UTF-8
603
3.484375
3
[]
no_license
package com.techment.Day6; import java.util.InputMismatchException; import java.util.Scanner; public class ExceptionHandlingTask { public static void main(String[] args) { try { System.out.println("Enter 1st number"); Scanner scanner= new Scanner(System.in); int a=scanner.nextInt(); System.out.println("Enter 2nd number"); int b=scanner.nextInt(); int c=a/b; System.out.println(c); } catch(ArithmeticException ae) { System.out.println("Dont give zero"); } catch(InputMismatchException ime) { System.out.println("Dont enter any character"); } } }
true
0e980709579d60b18bae9e67707d557f50bf7daa
Java
codelovers2g/MindMe
/app/src/main/java/com/mindmesolo/mindme/ContactAndLists/InterestCat.java
UTF-8
4,996
2.265625
2
[]
no_license
package com.mindmesolo.mindme.ContactAndLists; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; import com.mindmesolo.mindme.R; import com.mindmesolo.mindme.helper.Contacts; import com.mindmesolo.mindme.helper.SqliteDataBaseHelper; import org.json.JSONArray; import java.util.ArrayList; /** * Created by eNest on 6/8/2016. */ public class InterestCat extends Fragment { ListView InterestsList; String id; MyCustomAdapter dataAdapter = null; String contactCode; SqliteDataBaseHelper mydbhelper; ArrayList<Contacts> newarray = new ArrayList<Contacts>(); View view; String listname, Listid; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.organize_contact_lists, container, false); mydbhelper = new SqliteDataBaseHelper(getContext()); ArrayList<Contacts> countryList = new ArrayList<Contacts>(); ArrayList name = mydbhelper.getAllInterestNames(); ArrayList lid = mydbhelper.getAllInterestId(); for (int i = 0; i < name.size(); i++) { listname = String.valueOf(name.get(i)); Listid = String.valueOf(lid.get(i)); Contacts country = new Contacts(Listid, listname, id, "demo", false); countryList.add(country); } dataAdapter = new MyCustomAdapter(getContext(), R.layout.layout_contact_row, countryList); ListView listView = (ListView) view.findViewById(R.id.orgnize_list_view); listView.setAdapter(dataAdapter); return view; } //-------------- GET SELECTED ITEMS ROM LIST VIEW -------AND RETURAN A JSON ARRAY OF SELECTED ITEMS-------// public JSONArray getselecteditems() { super.onPause();// Always call the superclass method first String idsss = null; ArrayList idss; ArrayList<String> arraylist = new ArrayList<String>(); JSONArray jsonArray = new JSONArray(); ArrayList<Contacts> countryList = dataAdapter.contactsList; for (int i = 0; i < countryList.size(); i++) { Contacts country = countryList.get(i); if (country.isSelected()) { String data = country.getCode().toString(); jsonArray.put(data); } } return jsonArray; } //-------------------ADDAPTER FOR GENRATING THE LIST VIEW FOR TAGS------// private class MyCustomAdapter extends ArrayAdapter<Contacts> { private ArrayList<Contacts> contactsList; public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<Contacts> countryList) { super(context, textViewResourceId, countryList); this.contactsList = new ArrayList<Contacts>(); this.contactsList.addAll(countryList); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.orgnize_contact_row, null); holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.listview_item_title); holder.id = (CheckBox) convertView.findViewById(R.id.CheckBox01); convertView.setTag(holder); holder.id.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox) v; Contacts contacts = (Contacts) cb.getTag(); contacts.setSelected(cb.isChecked()); JSONArray arrayList = getselecteditems(); SharedPreferences pref = getContext().getSharedPreferences("Importcontact", Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString("InterestsArray", arrayList.toString()); editor.commit(); } }); } else { holder = (ViewHolder) convertView.getTag(); } Contacts contact = contactsList.get(position); holder.name.setText(contact.getName()); holder.id.setChecked(contact.isSelected()); holder.id.setTag(contact); return convertView; } private class ViewHolder { TextView name; CheckBox id; } } }
true
03c180cf1365caad1c35a00776ff869fd93cc47d
Java
07sahilg/MobileDeviceManagement
/app/src/main/java/com/example/myapplication/MainActivity.java
UTF-8
10,056
1.8125
2
[]
no_license
package com.example.myapplication; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.SetOptions; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { String email,pwd; EditText emailid; EditText password; Button signin; Button signup; FirebaseAuth mAuth; static Uri profile; FirebaseFirestore db = FirebaseFirestore.getInstance(); static Map<String,Object> userInfo = new HashMap<>(); EditText username; Map<String,Object> userI = new HashMap<>(); Map<String,Object> name = new HashMap<>(); ImageView googleAcc; private GoogleSignInClient mGoogle; private int RC_SIGN_IN = 1; static String e; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); /* if(user!=null){ Intent intent = new Intent(MainActivity.this,LoginActivity.class); startActivity(intent); }*/ name.put("name","sahil"); mAuth = FirebaseAuth.getInstance(); emailid = (EditText) findViewById(R.id.email); password = (EditText) findViewById(R.id.password); username = findViewById(R.id.username); // db.collection("l").add(name); signin = (Button) findViewById(R.id.login); signup = (Button) findViewById(R.id.signup); signin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { email = emailid.getText().toString(); pwd = password.getText().toString(); if(email.isEmpty()){ emailid.setError("Please enter emaill id"); } else if(pwd.isEmpty()){ password.setError("Please enter password"); } else if(email.isEmpty() && pwd.isEmpty()){ Toast.makeText(MainActivity.this, "Please fill the entries", Toast.LENGTH_SHORT).show(); } else if(!(email.isEmpty() && pwd.isEmpty())){ mAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(!(task.isSuccessful())){ Toast.makeText(MainActivity.this, "Entries Not Valid \n Try Sign Up", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(MainActivity.this, "Sign In Successful", Toast.LENGTH_SHORT).show(); FirebaseUser user = mAuth.getCurrentUser(); if(user != null){ email = user.getEmail(); userI.put("email",email); userI.put("name",username.getText().toString()); Log.i("user", String.valueOf(userI)); } db.collection("user").document(email).set(userI, SetOptions.merge()); Intent intent = new Intent(MainActivity.this, LoginActivity.class); intent.putExtra("email",user.getEmail()); e = user.getEmail(); startActivity(intent); } } }); } } }); signup.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,SignUpActivity.class); startActivity(intent); } }); googleAcc = findViewById(R.id.googleAcc); googleAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogle = GoogleSignIn.getClient(MainActivity.this, gso); googleAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { signIn(); } }); } }); /* signup.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { email = emailid.getText().toString(); pwd = password.getText().toString(); mAuth.createUserWithEmailAndPassword(email, pwd) .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser user = mAuth.getCurrentUser(); Toast.makeText(MainActivity.this, "Authentication Successful.", Toast.LENGTH_SHORT).show(); if(user.getDisplayName() == null) { userInfo.put("email",user.getEmail()); //db.collection("user").add(userInfo); Intent intent = new Intent(MainActivity.this, UserNameActivity.class); startActivity(intent); } } else { Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); } } }); } });*/ } private void signIn(){ Intent intent = mGoogle.getSignInIntent(); startActivityForResult(intent,RC_SIGN_IN); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == RC_SIGN_IN){ Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignResult(task); } } private void handleSignResult(Task<GoogleSignInAccount> completedTask){ try { GoogleSignInAccount acc = completedTask.getResult(ApiException.class); e = acc.getEmail(); userI.put("name",acc.getDisplayName()); userI.put("email",acc.getEmail()); db.collection("user").document(acc.getEmail()).set(userI); FirebaseGoogleAuth(acc); } catch (ApiException e) { Toast.makeText(this, "Sign In Failed", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } private void FirebaseGoogleAuth(final GoogleSignInAccount acct){ AuthCredential authCredential = GoogleAuthProvider.getCredential(acct.getIdToken(),null); mAuth.signInWithCredential(authCredential).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ FirebaseUser user = mAuth.getCurrentUser(); firebaseUpdate(user); } else{ Toast.makeText(MainActivity.this, "Sign In Failed", Toast.LENGTH_SHORT).show(); } } }); } void firebaseUpdate(FirebaseUser fuser){ GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if(account != null){ Toast.makeText(MainActivity.this, "Sign In Successful", Toast.LENGTH_SHORT).show(); userI.put("name",account.getDisplayName()); userI.put("email",account.getEmail()); db.collection("user").document(account.getEmail()).set(userI); Intent intent = new Intent(MainActivity.this,LoginActivity.class); intent.putExtra("email",account.getEmail()); startActivity(intent); } } }
true
228d05b8719bb45cfcce47a3084e9ea55fd7b767
Java
MasterCram/MasterMMORPG
/event/SkillsEvent.java
ISO-8859-1
1,694
2.375
2
[]
no_license
package Master_Cram.Master_Mod.event; import Master_Cram.Master_Mod.References; import Master_Cram.Master_Mod.item.NewSword; import Master_Cram.Master_Mod.player.ExtendedPlayer; import Master_Cram.Master_Mod.util.NBTHelper; import Master_Cram.Master_Mod.world.arcana.TeleporterArcana; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.world.BlockEvent; public class SkillsEvent { @SubscribeEvent public void onEventBreakBlock(BlockEvent.BreakEvent event) { //TODO: Faire en sorte que le joueur ne gagne pas d'xp en cratif if(event.block != null) { ExtendedPlayer.get(event.getPlayer()).skills.mining.addXpFromBlock(event.getPlayer(), event.block); ExtendedPlayer.get(event.getPlayer()).skills.woodcutting.addXpFromBlock(event.getPlayer(), event.block); ExtendedPlayer.get(event.getPlayer()).skills.digging.addXpFromBlock(event.getPlayer(), event.block); } } @SubscribeEvent public void onEntityDamage(LivingHurtEvent event) { if(event.source.getSourceOfDamage() instanceof EntityPlayer) { ExtendedPlayer player = ExtendedPlayer.get((EntityPlayer) event.source.getSourceOfDamage()); System.out.println(player.player.getDisplayName()); if(event.entityLiving.getHealth() > event.ammount) { player.skills.combat.addExperience(event.ammount); } else { player.skills.combat.addExperience(event.entityLiving.getHealth()); } } } }
true
7ac98a96112e57a79ddb0b9262d27ed0bb9ac49a
Java
constseche/Sacchon-2
/BackEnd/src/main/java/model/ChiefDoctor.java
UTF-8
402
2.0625
2
[]
no_license
package model; import lombok.*; import lombok.experimental.SuperBuilder; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Data @Entity public class ChiefDoctor extends User{ @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private long id; private String role="chiefDoctor"; }
true
071a1be0829e047f57c88e691b8a81cd30eabcd0
Java
tik5213/myWorldBox
/app/src/main/java/io/netty/handler/codec/AsciiHeadersEncoder.java
UTF-8
3,603
2.875
3
[]
no_license
package io.netty.handler.codec; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.util.AsciiString; import java.util.Map.Entry; public final class AsciiHeadersEncoder { private final ByteBuf buf; private final NewlineType newlineType; private final SeparatorType separatorType; public enum NewlineType { LF, CRLF } public enum SeparatorType { COLON, COLON_SPACE } public AsciiHeadersEncoder(ByteBuf buf) { this(buf, SeparatorType.COLON_SPACE, NewlineType.CRLF); } public AsciiHeadersEncoder(ByteBuf buf, SeparatorType separatorType, NewlineType newlineType) { if (buf == null) { throw new NullPointerException("buf"); } else if (separatorType == null) { throw new NullPointerException("separatorType"); } else if (newlineType == null) { throw new NullPointerException("newlineType"); } else { this.buf = buf; this.separatorType = separatorType; this.newlineType = newlineType; } } public void encode(Entry<CharSequence, CharSequence> entry) { int offset; CharSequence name = (CharSequence) entry.getKey(); CharSequence value = (CharSequence) entry.getValue(); ByteBuf buf = this.buf; int nameLen = name.length(); int valueLen = value.length(); int entryLen = (nameLen + valueLen) + 4; int offset2 = buf.writerIndex(); buf.ensureWritable(entryLen); writeAscii(buf, offset2, name, nameLen); offset2 += nameLen; switch (this.separatorType) { case COLON: offset = offset2 + 1; buf.setByte(offset2, 58); offset2 = offset; break; case COLON_SPACE: offset = offset2 + 1; buf.setByte(offset2, 58); offset2 = offset + 1; buf.setByte(offset, 32); break; default: throw new Error(); } writeAscii(buf, offset2, value, valueLen); offset2 += valueLen; switch (this.newlineType) { case LF: offset = offset2 + 1; buf.setByte(offset2, 10); offset2 = offset; break; case CRLF: offset = offset2 + 1; buf.setByte(offset2, 13); offset2 = offset + 1; buf.setByte(offset, 10); break; default: throw new Error(); } buf.writerIndex(offset2); } private static void writeAscii(ByteBuf buf, int offset, CharSequence value, int valueLen) { if (value instanceof AsciiString) { writeAsciiString(buf, offset, (AsciiString) value, valueLen); } else { writeCharSequence(buf, offset, value, valueLen); } } private static void writeAsciiString(ByteBuf buf, int offset, AsciiString value, int valueLen) { ByteBufUtil.copy(value, 0, buf, offset, valueLen); } private static void writeCharSequence(ByteBuf buf, int offset, CharSequence value, int valueLen) { int i = 0; int offset2 = offset; while (i < valueLen) { offset = offset2 + 1; buf.setByte(offset2, c2b(value.charAt(i))); i++; offset2 = offset; } } private static int c2b(char ch) { return ch < 'Ā' ? (byte) ch : 63; } }
true
ae4b182e3d37533b5bbf6182c257e64241ae2a22
Java
Ivan-kitty/CoolSQL
/src/main/java/com/cattsoft/coolsql/pub/component/selectabletree/SelectableTree.java
UTF-8
3,332
2.453125
2
[]
no_license
/** * */ package com.cattsoft.coolsql.pub.component.selectabletree; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Hashtable; import java.util.Vector; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import com.cattsoft.coolsql.pub.component.BaseTree; import com.cattsoft.coolsql.system.lookandfeel.SystemLookAndFeel; /** * @author ����(kenny liu) * * 2008-3-16 create */ public class SelectableTree extends BaseTree { private static final long serialVersionUID = 1L; private MouseListener selectionTreeListener; public SelectableTree() { super(); } public SelectableTree(Object[] value) { super(value); } public SelectableTree(Vector<?> value) { super(value); } public SelectableTree(Hashtable<?,?> value) { super(value); } public SelectableTree(TreeNode root) { super(root); } public SelectableTree(TreeNode root, boolean asksAllowsChildren) { super(root,asksAllowsChildren); } public SelectableTree(TreeModel newModel) { super(newModel); } @Override protected void initTree() { super.initTree(); if(!SystemLookAndFeel.getInstance().isMetalLookAndFeel()) setRowHeight(getRowHeight()+3); selectionTreeListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if(e.getButton()!=MouseEvent.BUTTON1) return; int x = e.getX(); int y = e.getY(); int row = getRowForLocation(x, y); if(row == -1) return; TreePath path = getPathForRow(row); Rectangle rowRect = getPathBounds(path); if (!isInCheckBox(rowRect, e.getPoint())) { return; } if (path != null) { SelectableTreeNode node = (SelectableTreeNode) path .getLastPathComponent(); if (node.getOrderable()) { return; } setNodeSelected(node, !node.getSelected()); } } }; getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); putClientProperty("JTree.lineStyle", "Angled"); setShowsRootHandles(true); setCellRenderer(new SelectableTreeNodeRenderer()); addMouseListener(selectionTreeListener); } private boolean isInCheckBox(Rectangle rowRect, Point p) { TreeCellRenderer render = getCellRenderer(); if (!(render instanceof SelectableTreeNodeRenderer)) { return false; } SelectableTreeNodeRenderer stRender = (SelectableTreeNodeRenderer) render; Insets renderInsets = stRender.getInsets(); return p.x < (rowRect.x + renderInsets.left + stRender.getCheckBoxWith()); } /** * Select or deselect a node, update selectionTree and orderingTree * 1. update selectionTree * * @param node * the node to be selected or deselected * @param selected */ protected void setNodeSelected(SelectableTreeNode node, boolean selected) { // update selection tree node.setSelected(selected); DefaultTreeModel model = ((DefaultTreeModel)getModel()); SelectableTreeNode updated = node; while (updated != null) { model.nodeChanged(updated); updated = (SelectableTreeNode) updated.getParent(); } } }
true
8fe065ebe710dd98715adf21eb7b705a9d4c61c9
Java
aritrac/SolidJava
/SerializationInJava/src/test/serialization/ExternalizableTest.java
UTF-8
1,191
3.046875
3
[]
no_license
package test.serialization; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ExternalizableTest { public static void main(String[] args) { String fileName = "person.ser"; NewExternalizedPerson person = new NewExternalizedPerson(); person.setId(1); person.setName("Aritra"); person.setGender("Male"); try { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(person); oos.close(); } catch (IOException e) { e.printStackTrace(); } FileInputStream fis; try { fis = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(fis); NewExternalizedPerson p = (NewExternalizedPerson) ois.readObject(); ois.close(); System.out.println("Person Object Read="+p); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
true
7888d213cac734d1f4b2337de18804d2318e917d
Java
Ektasahu0027/Fermi-master_app
/app/src/main/java/com/example/fermi/fermi/adapter/MessageModel.java
UTF-8
486
2.078125
2
[]
no_license
package com.example.fermi.fermi.adapter; /** * Created by Parsania Hardik on 11-May-17. */ public class MessageModel { private String message,position; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } }
true
e38e450bd8b5d7c8c7529de95e605d43166afcb2
Java
Adn1217/Ciclo2
/clase01/src/App.java
UTF-8
527
3.59375
4
[]
no_license
import java.util.Scanner; public class App { public static void main(String[] args) throws Exception { System.out.println("Hello, World!!!"); var Scanner = new Scanner(System.in); System.out.println("Ingrese un número entero"); var numero = Scanner.nextInt(); var respuesta = validarNumero(numero); System.out.println(respuesta); } public static String validarNumero(int numero){ return(numero % 2 == 0 ? numero +" es par": numero + " es impar"); } }
true
c586f9fd450f4a72d670a3cb3bed5939bcf4dc2e
Java
helloingob/Ultimaster
/Ultimaster-API/src/test/java/de/fhl/ultimaster/api/v1/connection/history/print_jobs/HistoryPrintJobsGetTest.java
UTF-8
447
1.65625
2
[ "Apache-2.0" ]
permissive
package de.fhl.ultimaster.api.v1.connection.history.print_jobs; import org.junit.Assert; import org.junit.Test; import de.fhl.ultimaster.api.v1.history.print_jobs.HistoryPrintJobsGet; import de.fhl.ultimaster.api.v1.utils.TestPrinter; public class HistoryPrintJobsGetTest { @Test public void testHistoryPrintJobsGet() { Assert.assertNotNull(HistoryPrintJobsGet.get(TestPrinter.getInstance().getPrinter(), null, null)); } }
true
582880e3ceb73b6ee6ddd36329979dd803992f00
Java
keibai/keibai-android
/app/src/main/java/io/github/keibai/SaveSharedPreference.java
UTF-8
2,798
2.125
2
[ "Apache-2.0" ]
permissive
package io.github.keibai; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.google.gson.Gson; import io.github.keibai.gson.BetterGson; import io.github.keibai.models.Auction; import io.github.keibai.models.Event; public class SaveSharedPreference { static final String PREF_USER_ID = "user_id"; static final String PREF_COOKIES = "cookies"; static final String PREF_CURRENT_EVENT = "current_event"; static final String PREF_CURRENT_AUCTION = "current_auction"; static final String PREF_AUTOFILL_EMAIL = "autofill_email"; static SharedPreferences getSharedPreferences(Context ctx) { return PreferenceManager.getDefaultSharedPreferences(ctx); } public static void setUserId(Context ctx, long userId) { Editor editor = getSharedPreferences(ctx).edit(); editor.putLong(PREF_USER_ID, userId); editor.apply(); } public static long getUserId(Context ctx) { return getSharedPreferences(ctx).getLong(PREF_USER_ID, -1); } public static void setCookies(Context ctx, String cookies) { Editor editor = getSharedPreferences(ctx).edit(); editor.putString(PREF_COOKIES, cookies); editor.apply(); } public static String getCookies(Context ctx) { return getSharedPreferences(ctx).getString(PREF_COOKIES, ""); } public static void setCurrentEvent(Context ctx, Event event) { Editor editor = getSharedPreferences(ctx).edit(); editor.putString(PREF_CURRENT_EVENT, new BetterGson().newInstance().toJson(event)); editor.apply(); } public static Event getCurrentEvent(Context ctx) { String jsonEvent = getSharedPreferences(ctx).getString(PREF_CURRENT_EVENT, "{}"); return new BetterGson().newInstance().fromJson(jsonEvent, Event.class); } public static void setCurrentAuction(Context ctx, Auction auction) { Editor editor = getSharedPreferences(ctx).edit(); editor.putString(PREF_CURRENT_AUCTION, new BetterGson().newInstance().toJson(auction)); editor.apply(); } public static Auction getCurrentAuction(Context ctx) { String jsonEvent = getSharedPreferences(ctx).getString(PREF_CURRENT_AUCTION, "{}"); return new BetterGson().newInstance().fromJson(jsonEvent, Auction.class); } public static void setAutofillEmail(Context ctx, String email) { Editor editor = getSharedPreferences(ctx).edit(); editor.putString(PREF_AUTOFILL_EMAIL, email); editor.apply(); } public static String getAutofillEmail(Context ctx) { return getSharedPreferences(ctx).getString(PREF_AUTOFILL_EMAIL, ""); } }
true
a971e292754d84e44fdf3df25f68c51812654265
Java
phucnb/CST8288_Assignment1
/src/java/dao/ScoreDAO.java
UTF-8
1,675
2.390625
2
[]
no_license
package dao; import entity.Score; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author baphucnguyen */ public class ScoreDAO extends GenericDAO<Score>{ public ScoreDAO(){ super(Score.class); } public List<Score> findAll(){ return findResults( "Score.findAll", null); } public List<Score> findByID( int id){ Map<String, Object> map = new HashMap<>(); map.put("id", id); return findResults( "Score.findById", map); } public List<Score> findByScore( int score){ Map<String, Object> map = new HashMap<>(); map.put("score", score); return findResults( "Score.findByScore", map); } public List<Score> findBySubmission( Date submission){ Map<String, Object> map = new HashMap<>(); map.put("submission", submission); return findResults( "Score.findBySubmission", map); } public List<Score> findBySubmissionBeforeDate( Date submission){ Map<String, Object> map = new HashMap<>(); map.put("submission", submission); return findResults( "Score.findBySubmissionBeforeDate", map); } public List<Score> findBySubmissionAfterDate( Date submission){ Map<String, Object> map = new HashMap<>(); map.put("submission", submission); return findResults( "Score.findBySubmissionAfterDate", map); } public List<Score> findByPlayerID( int playerID){ Map<String, Object> map = new HashMap<>(); map.put("playerid", playerID); return findResults( "Score.findByPlayerId", map); } }
true
1c46181bb4db06fb3f1d92cb54f5d3b2dd4f8f23
Java
527088995/dian
/rito-admin/src/test/java/com/stylefeng/guns/flowable/FlowableTest.java
UTF-8
8,394
2.1875
2
[ "Apache-2.0" ]
permissive
package com.stylefeng.guns.flowable; import com.alibaba.fastjson.JSON; import org.flowable.engine.*; import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.task.api.Task; import org.flowable.task.api.TaskQuery; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * 工作流的业务测试 * * @author ... * @date 2017-12-02 20:37 */ public class FlowableTest { ProcessEngine processEngine; @Before public void init() { ProcessEngineConfiguration cfg = new StandaloneProcessEngineConfiguration() .setJdbcUrl("jdbc:mysql://127.0.0.1:3306/guns_flowable?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull") .setJdbcUsername("root") .setJdbcPassword("root") .setJdbcDriver("com.mysql.jdbc.Driver") .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); processEngine = cfg.buildProcessEngine(); } /** * 发布流程 */ @Test public void deploy() { RepositoryService repositoryService = processEngine.getRepositoryService(); Deployment deployment = repositoryService.createDeployment() .addClasspathResource("ExpenseProcess.bpmn20.xml") .deploy(); ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery() .deploymentId(deployment.getId()) .singleResult(); System.out.println("Found process definition : " + processDefinition.getName()); } /** * 查看发布 */ @Test public void findDeploy() { RepositoryService repositoryService = processEngine.getRepositoryService(); List<Deployment> list = repositoryService.createDeploymentQuery().list(); for (Deployment deployment : list) { System.out.println(deployment.getCategory()); System.out.println(deployment.getName()); System.out.println("deploy = " + deployment.getId()); System.out.println("key = " + deployment.getKey()); } } /** * 启动流程 */ @Test public void start() { HashMap<String, Object> map = new HashMap<>(); map.put("taskUser", "fsn"); ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceByKey("Expense", map); System.out.println("pid = " + processInstance.getId()); System.out.println("activityId = " + processInstance.getActivityId()); System.out.println("getProcessDefinitionId = " + processInstance.getProcessDefinitionId()); } /** * 查看流程定义 */ @Test public void queryProcess() { List<ProcessInstance> list1 = processEngine.getRuntimeService().createProcessInstanceQuery().list(); for (ProcessInstance processDefinition : list1) { System.out.println("id = " + processDefinition.getId()); System.out.println("getDeploymentId = " + processDefinition.getDeploymentId()); System.out.println("getTenantId = " + processDefinition.getTenantId()); System.out.println("name = " + processDefinition.getName()); } System.err.println("---------------------------------"); List<ProcessDefinition> list = processEngine.getRepositoryService() .createProcessDefinitionQuery() .list(); for (ProcessDefinition processDefinition : list) { System.out.println("id = " + processDefinition.getId()); System.out.println("getDeploymentId = " + processDefinition.getDeploymentId()); System.out.println("getTenantId = " + processDefinition.getTenantId()); System.out.println("name = " + processDefinition.getName()); System.out.println("key = " + processDefinition.getKey()); System.out.println("version = " + processDefinition.getVersion()); System.out.println("resourceName = " + processDefinition.getResourceName()); } } /** * 删除流程定义 */ @Test public void delProcess() { processEngine.getRuntimeService().deleteProcessInstance("67501","abcd"); //processEngine.getRepositoryService().deleteDeployment("25001", true); System.out.println("删除成功"); } /** * 查看任务 */ @Test public void queryMyTask() { String name = "张三"; TaskQuery taskQuery = processEngine.getTaskService().createTaskQuery().taskAssignee(name); List<Task> list = taskQuery.list(); for (Task task : list) { System.out.println("name = " + task.getName()); System.out.println(JSON.toJSON(task.getTaskLocalVariables())); } System.out.println("查询完毕!"); } /** * 完成任务 */ @Test public void complete() { HashMap<String, Object> map = new HashMap<>(); map.put("money", 600); TaskService taskService = processEngine.getTaskService(); taskService.complete("47513", map); } public static void main(String[] args) { ProcessEngineConfiguration cfg = new StandaloneProcessEngineConfiguration() .setJdbcUrl("jdbc:mysql://127.0.0.1:3306/flowable?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull") .setJdbcUsername("root") .setJdbcPassword("root") .setJdbcDriver("com.mysql.jdbc.Driver") .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); ProcessEngine processEngine = cfg.buildProcessEngine(); RepositoryService repositoryService = processEngine.getRepositoryService(); Deployment deployment = repositoryService.createDeployment() .addClasspathResource("holiday-request.bpmn20.xml") .deploy(); ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery() .deploymentId(deployment.getId()) .singleResult(); System.out.println("Found process definition : " + processDefinition.getName()); Scanner scanner = new Scanner(System.in); System.out.println("Who are you?"); String employee = scanner.nextLine(); System.out.println("How many holidays do you want to request?"); Integer nrOfHolidays = Integer.valueOf(scanner.nextLine()); System.out.println("Why do you need them?"); String description = scanner.nextLine(); RuntimeService runtimeService = processEngine.getRuntimeService(); Map<String, Object> variables = new HashMap<String, Object>(); variables.put("employee", employee); variables.put("nrOfHolidays", nrOfHolidays); variables.put("description", description); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("holidayRequest", variables); TaskService taskService = processEngine.getTaskService(); List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers").list(); System.out.println("You have " + tasks.size() + " tasks:"); for (int i = 0; i < tasks.size(); i++) { System.out.println((i + 1) + ") " + tasks.get(i).getName()); } System.out.println("Which task would you like to complete?"); int taskIndex = Integer.valueOf(scanner.nextLine()); Task task = tasks.get(taskIndex - 1); Map<String, Object> processVariables = taskService.getVariables(task.getId()); System.out.println(processVariables.get("employee") + " wants " + processVariables.get("nrOfHolidays") + " of holidays. Do you approve this?"); boolean approved = scanner.nextLine().toLowerCase().equals("y"); variables = new HashMap<String, Object>(); variables.put("approved", approved); taskService.complete(task.getId(), variables); } }
true
2324bdcde01026d38d1cb40bb036c608fdb25cb3
Java
ren90/BIMforBA
/BIMfoBA.src/jsdai/SIfc4/CIfcparameterizedprofiledef.java
UTF-8
6,403
1.851563
2
[]
no_license
/* Generated by JSDAI Express Compiler, version 4.3.2, build 500, 2011-12-13 */ // Java class implementing entity IfcParameterizedProfileDef package jsdai.SIfc4; import jsdai.lang.*; public class CIfcparameterizedprofiledef extends CIfcprofiledef implements EIfcparameterizedprofiledef { public static final jsdai.dictionary.CEntity_definition definition = initEntityDefinition(CIfcparameterizedprofiledef.class, SIfc4.ss); /*----------------------------- Attributes -----------*/ /* // ProfileType: protected int a0; ProfileType - java inheritance - ENUMERATION IfcProfileTypeEnum // ProfileName: protected String a1; ProfileName - java inheritance - STRING // HasExternalReference: protected Object - inverse - java inheritance - ENTITY IfcExternalReferenceRelationship // HasProperties: protected Object - inverse - java inheritance - ENTITY IfcProfileProperties protected Object a2; // Position - current entity - ENTITY IfcAxis2Placement2D protected static final jsdai.dictionary.CExplicit_attribute a2$ = CEntity.initExplicitAttribute(definition, 2); */ /*----------------------------- Attributes (new version) -----------*/ // ProfileType - explicit - java inheritance // protected static final jsdai.dictionary.CExplicit_attribute a0$ = CEntity.initExplicitAttribute(definition, 0); // protected int a0; // ProfileName - explicit - java inheritance // protected static final jsdai.dictionary.CExplicit_attribute a1$ = CEntity.initExplicitAttribute(definition, 1); // protected String a1; // HasExternalReference - inverse - java inheritance // protected static final jsdai.dictionary.CInverse_attribute i0$ = CEntity.initInverseAttribute(definition, 0); // HasProperties - inverse - java inheritance // protected static final jsdai.dictionary.CInverse_attribute i1$ = CEntity.initInverseAttribute(definition, 1); // Position - explicit - current entity protected static final jsdai.dictionary.CExplicit_attribute a2$ = CEntity.initExplicitAttribute(definition, 2); protected Object a2; public jsdai.dictionary.EEntity_definition getInstanceType() { return definition; } /* *** old implementation *** protected void changeReferences(InverseEntity old, InverseEntity newer) throws SdaiException { super.changeReferences(old, newer); if (a2 == old) { a2 = newer; } } */ protected void changeReferences(InverseEntity old, InverseEntity newer) throws SdaiException { super.changeReferences(old, newer); if (a2 == old) { a2 = newer; } } /*----------- Methods for attribute access -----------*/ /*----------- Methods for attribute access (new)-----------*/ //going through all the attributes: #5070=EXPLICIT_ATTRIBUTE('ProfileType',#5068,0,#2963,$,.F.); //<01> generating methods for consolidated attribute: ProfileType //<01-1> supertype, java inheritance //<01-1-0> explicit - generateExplicitSupertypeJavaInheritedMethodsX() //going through all the attributes: #5071=EXPLICIT_ATTRIBUTE('ProfileName',#5068,1,#2539,$,.T.); //<01> generating methods for consolidated attribute: ProfileName //<01-1> supertype, java inheritance //<01-1-0> explicit - generateExplicitSupertypeJavaInheritedMethodsX() //going through all the attributes: #5072=INVERSE_ATTRIBUTE('HasExternalReference',#5068,0,#4231,$,#4234,#8892,$,.F.); //<01> generating methods for consolidated attribute: HasExternalReference //<01-1> supertype, java inheritance //<01-1-2> inverse - generateInverseSupertypeJavaInheritedMethodsX() //going through all the attributes: #5073=INVERSE_ATTRIBUTE('HasProperties',#5068,1,#5074,$,#5076,#8894,$,.F.); //<01> generating methods for consolidated attribute: HasProperties //<01-1> supertype, java inheritance //<01-1-2> inverse - generateInverseSupertypeJavaInheritedMethodsX() //going through all the attributes: #4870=EXPLICIT_ATTRIBUTE('Position',#4868,0,#3378,$,.T.); //<01> generating methods for consolidated attribute: Position //<01-0> current entity //<01-0-0> explicit attribute - generateExplicitCurrentEntityMethodsX() // attribute (current explicit or supertype explicit) : Position, base type: entity IfcAxis2Placement2D public static int usedinPosition(EIfcparameterizedprofiledef type, EIfcaxis2placement2d instance, ASdaiModel domain, AEntity result) throws SdaiException { return ((CEntity)instance).makeUsedin(definition, a2$, domain, result); } public boolean testPosition(EIfcparameterizedprofiledef type) throws SdaiException { return test_instance(a2); } public EIfcaxis2placement2d getPosition(EIfcparameterizedprofiledef type) throws SdaiException { return (EIfcaxis2placement2d)get_instance(a2); } public void setPosition(EIfcparameterizedprofiledef type, EIfcaxis2placement2d value) throws SdaiException { a2 = set_instance(a2, value); } public void unsetPosition(EIfcparameterizedprofiledef type) throws SdaiException { a2 = unset_instance(a2); } public static jsdai.dictionary.EAttribute attributePosition(EIfcparameterizedprofiledef type) throws SdaiException { return a2$; } /*---------------------- setAll() --------------------*/ /* *** old implementation *** protected void setAll(ComplexEntityValue av) throws SdaiException { if (av == null) { a2 = unset_instance(a2); a0 = 0; a1 = null; return; } a2 = av.entityValues[0].getInstance(0, this, a2$); a0 = av.entityValues[1].getEnumeration(0, a0$); a1 = av.entityValues[1].getString(1); } */ protected void setAll(ComplexEntityValue av) throws SdaiException { if (av == null) { a2 = unset_instance(a2); a0 = 0; a1 = null; return; } a2 = av.entityValues[0].getInstance(0, this, a2$); a0 = av.entityValues[1].getEnumeration(0, a0$); a1 = av.entityValues[1].getString(1); } /*---------------------- getAll() --------------------*/ /* *** old implementation *** protected void getAll(ComplexEntityValue av) throws SdaiException { // partial entity: IfcParameterizedProfileDef av.entityValues[0].setInstance(0, a2); // partial entity: IfcProfileDef av.entityValues[1].setEnumeration(0, a0, a0$); av.entityValues[1].setString(1, a1); } */ protected void getAll(ComplexEntityValue av) throws SdaiException { // partial entity: IfcParameterizedProfileDef av.entityValues[0].setInstance(0, a2); // partial entity: IfcProfileDef av.entityValues[1].setEnumeration(0, a0, a0$); av.entityValues[1].setString(1, a1); } }
true
da0207715237fdc62f372e9b5b78f658df3deb18
Java
freedomx04/ncgyy2
/src/main/java/com/hongmeng/gcgyy/entity/monitor/ScoreEntity.java
UTF-8
1,167
2.0625
2
[]
no_license
package com.hongmeng.gcgyy.entity.monitor; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import com.hongmeng.gcgyy.entity.BaseEntity; import com.hongmeng.gcgyy.entity.authority.BaseEnterpriseEntity; @Entity @Table(name = "monitor_score", indexes = { @Index(name = "index_score_score", columnList = "score") }) public class ScoreEntity extends BaseEntity { @OneToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "enterprise_id") private BaseEnterpriseEntity enterprise; // 企业 private Integer score; public ScoreEntity() { // TODO Auto-generated constructor stub } public ScoreEntity(BaseEnterpriseEntity enterprise, Integer score) { this.enterprise = enterprise; this.score = score; } public BaseEnterpriseEntity getEnterprise() { return enterprise; } public void setEnterprise(BaseEnterpriseEntity enterprise) { this.enterprise = enterprise; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } }
true
40204ca840c75e0f82778728805a65a0ba09e0ef
Java
aashishshrestha5532/SSA-
/SSA/app/src/main/java/com/alchemist/ssa/StartingStuffs/WelcomeActivity.java
UTF-8
3,601
2.34375
2
[]
no_license
package com.alchemist.ssa.StartingStuffs; import android.content.Intent; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.alchemist.ssa.R; import com.alchemist.ssa.ScheduleStuffs.Schedule; public class WelcomeActivity extends AppCompatActivity { private ViewPager viewPager; private IntroPageAdapter introPageAdapter; private Button skipBtn,nextBtn; private int slideLayouts[]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); slideLayouts=new int[]{R.layout.intro_slide1,R.layout.intro_slide2}; skipBtn=findViewById(R.id.skipSlide); nextBtn=findViewById(R.id.nextSlide); viewPager=findViewById(R.id.introViewPager); introPageAdapter=new IntroPageAdapter(); viewPager.setAdapter(introPageAdapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if(position==(slideLayouts.length-1)){ nextBtn.setText("Got it"); } } @Override public void onPageScrollStateChanged(int state) { } }); nextBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(getCurrentSlide()<slideLayouts.length){ //if the slide is still present if(getCurrentSlide()==(slideLayouts.length-1)){ //if the slide is last one nextBtn.setText("Got it"); } viewPager.setCurrentItem(getCurrentSlide()); } else{ startActivity(new Intent(getApplicationContext(),PostSplash.class)); } } }); skipBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(),PostSplash.class)); } }); } private int getCurrentSlide() { return viewPager.getCurrentItem()+1; } public class IntroPageAdapter extends PagerAdapter { @Override public int getCount() { return slideLayouts.length; } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } //Inner adapter class for the viewpager public IntroPageAdapter() { } @Override public Object instantiateItem(ViewGroup container, int position) { View view = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(slideLayouts[position], container, false); container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } }
true
d4c78c5c612960d71dd614df66680d85f4fc542b
Java
ExceptionHandler/TestRepo
/DataStructures/src/com/dc/ads/LinkedList.java
UTF-8
746
3.28125
3
[]
no_license
package com.dc.ads; public class LinkedList { public static LLNode root; public static void addNode(int data) { LLNode node = new LLNode(data); LLNode temp = null; if(root == null) { root = node; } else { temp = root; while(temp.getNext() != null) { temp = temp.getNext(); } temp.setNext(node); } } public static class LLNode { private int data; private LLNode next; public LLNode(int data) { this.data = data; next = null; } public int getData() { return this.data; } public void setData(int data) { this.data = data; } public LLNode getNext() { return next; } public void setNext(LLNode next) { this.next = next; } } }
true
970d5448252c7aafc74d240a21adb38cefcca770
Java
graphhopper/gtfs-lib
/src/main/java/com/conveyal/gtfs/validator/OverlappingTripsValidator.java
UTF-8
5,481
2.3125
2
[ "BSD-2-Clause" ]
permissive
package com.conveyal.gtfs.validator; import com.conveyal.gtfs.GTFSFeed; import com.conveyal.gtfs.error.OverlappingTripsInBlockError; import com.conveyal.gtfs.model.CalendarDate; import com.conveyal.gtfs.model.Service; import com.conveyal.gtfs.model.StopTime; import com.conveyal.gtfs.model.Trip; import com.conveyal.gtfs.validator.model.InvalidValue; import com.conveyal.gtfs.validator.model.Priority; import com.conveyal.gtfs.validator.model.ValidationResult; import com.google.common.collect.Iterables; import org.mapdb.Fun; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by landon on 5/2/16. */ public class OverlappingTripsValidator extends GTFSValidator { private static Double distanceMultiplier = 1.0; public boolean validate(GTFSFeed feed, boolean repair, Double distanceMultiplier) { this.distanceMultiplier = distanceMultiplier; return validate(feed, repair); } @Override public boolean validate(GTFSFeed feed, boolean repair) { ValidationResult result = new ValidationResult(); // check for overlapping trips within block HashMap<String, ArrayList<BlockInterval>> blockIntervals = new HashMap<String, ArrayList<BlockInterval>>(); feed.trips.values().stream().iterator().forEachRemaining(trip -> { // store trip intervals by block id if (trip.block_id != null) { Iterable<StopTime> stopTimes = feed.getOrderedStopTimesForTrip(trip.trip_id); BlockInterval blockInterval = new BlockInterval(); blockInterval.trip = trip; StopTime firstStopTime = Iterables.get(stopTimes, 0); blockInterval.startTime = firstStopTime.departure_time; blockInterval.firstStop = firstStopTime; blockInterval.lastStop = Iterables.getLast(stopTimes); if(!blockIntervals.containsKey(trip.block_id)) blockIntervals.put(trip.block_id, new ArrayList<BlockInterval>()); blockIntervals.get(trip.block_id).add(blockInterval); } }); for(String blockId : blockIntervals.keySet()) { ArrayList<BlockInterval> intervals = blockIntervals.get(blockId); Collections.sort(intervals, new BlockIntervalComparator()); int iOffset = 0; for(BlockInterval i1 : intervals) { for(BlockInterval i2 : intervals.subList(iOffset, intervals.size() - 1)) { String tripId1 = i1.trip.trip_id; String tripId2 = i2.trip.trip_id; if(!tripId1.equals(tripId2)) { // if trips don't overlap, skip if(i1.lastStop.departure_time <= i2.firstStop.arrival_time || i2.lastStop.departure_time <= i1.firstStop.arrival_time) continue; // if trips have same service id they overlap if(i1.trip.service_id.equals(i2.trip.service_id)) { String[] tripIds = {tripId1, tripId2}; try { feed.errors.add(new OverlappingTripsInBlockError(0, "block_id", blockId, feed.routes.get(i1.trip.route_id), tripIds, Priority.HIGH)); } catch (Exception e) { } } else { Service s1 = feed.services.get(i1.trip.service_id); Service s2 = feed.services.get(i2.trip.service_id); boolean overlap = Service.checkOverlap(s1, s2); // if trips don't share service id check to see if service dates fall on the same days/day of week for(Map.Entry<LocalDate, CalendarDate> d1 : s1.calendar_dates.entrySet()) { LocalDate date = d1.getKey(); boolean activeOnDate = s1.activeOn(date) && s2.activeOn(date); if (activeOnDate || overlap) { String[] tripIds = {tripId1, tripId2}; try { feed.errors.add(new OverlappingTripsInBlockError(0, "block_id", blockId, feed.routes.get(i1.trip.route_id), tripIds, Priority.HIGH)); } catch (Exception e) { } break; } } } } } } } return false; } private class BlockInterval implements Comparable<BlockInterval> { Trip trip; Integer startTime; StopTime firstStop; StopTime lastStop; public int compareTo(BlockInterval o) { return new Integer(this.firstStop.arrival_time).compareTo(new Integer(o.firstStop.arrival_time)); } } private class BlockIntervalComparator implements Comparator<BlockInterval> { public int compare(BlockInterval a, BlockInterval b) { return new Integer(a.startTime).compareTo(new Integer(b.startTime)); } } }
true
f7f58e4235b5eda966e84c90ef1be435805e387c
Java
huangruqi88/DesighModeSample
/app/src/main/java/com/example/huangruqi/pattern/template_method/ConcreteClassA.java
UTF-8
416
2.828125
3
[]
no_license
package com.example.huangruqi.pattern.template_method; /** * @data: 2019/2/16 11:24 * @author: 黄汝琪 * @Email: * @Description: */ public class ConcreteClassA extends AbstractClass { @Override void primitiveOperation1() { System.out.println("具体类A 方法1 实现"); } @Override void primitiveOperation2() { System.out.println("具体类A 方法2 实现"); } }
true
3354cb67c726ce31eeb288f1d1b09cc448495165
Java
transitive-bullshit/Artifice
/gfx/App.java
UTF-8
2,603
3.328125
3
[]
no_license
package gfx; /* * The only purpose of this class is so that you have something to test your * shape with. It's use is 100% optional. When you run cs015_runDemo gfx, this * is what you see. Instructions for its use are below. */ public class App { public App(String s) { super(); /* * Pass in one of your Shape subclasses here. You might be wondering * where your shapes will get their container from. For a container, * cs015.prj.Shape.ViewerFrame has a protected drawing panel. It is * named _dp. Since this class is a subclass of * cs015.prj.Shape.ViewerFrame, you have access to the _dp instance * variable from within this class. Thus, to use the ViewerFrame to test * your Shape, all you need is this: * * gfx.Ellipse ellipse = new gfx.Ellipse(_dp); * * Where Ellipse is one of your Shape subclasses. * * Then you need to call: * * this.setShape(ellipse); * * and you should be all set! Just compile everything and run as: * * java gfx.App * */ // instantiate an instance of your Shape subclass here /* Rectangle */ // gfx.Ellipse e = new gfx.Ellipse(_dp); // gfx.Rectangle e = new gfx.Rectangle(_dp); // gfx.ImageShape e = new ImageShape(_dp, "witch01.gif"); // this.setShape(e); // this.setShape(new Rectangle(_dp)); /** Gradient Paint Example */ // e.setPaint(new // java.awt.GradientPaint(0F,0F,java.awt.Color.black,(float)e.getWidth(),0F,java.awt.Color.white)); // this.setShape(new gfx.TextShape(_dp, "This is a test", 50, 50)); /** Texture Paint Example */ // e.setPaint(ImageUtils.getTexturePaint(_dp, "witch01.gif")); // e.setPaint(new java.awt.TexturePaint(ImageUtils.getBufferedImage(_dp, // "witch01.gif"), // new java.awt.geom.Rectangle2D.Double(0, 0, e.getWidth(), // e.getHeight()))); // BufferedImage = // e.setPaint(new java.awt.TexturePaint(new BufferedImage("test.jpg", // _dp), /* Ellipse */ // this.setShape(new Ellipse(_dp)); /* Arc */ // this.setShape(new Arc(_dp)); // uncomment this line and pass in your shape // this.setShape(<your shape subclass here>); } // Still don't need to worry about this yet. It just starts the App. public static void main(String[] argv) { App a = new App("Shape Viewer"); } }
true
c2e418c86937e474b6e835b47c5c98cdb92d70a2
Java
wpilibsuite/desktop-common
/src/main/java/edu/wpi/first/desktop/plugin/PluginManager.java
UTF-8
2,920
2.734375
3
[]
no_license
package edu.wpi.first.desktop.plugin; import java.util.LinkedHashSet; import java.util.stream.Collectors; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; /** * Manages loading and unloading plugins from a single, shared target object. * * @param <T> the type of the target managed plugins apply to */ public class PluginManager<T> { private final T target; private final ObservableSet<Plugin<T>> knownPlugins = FXCollections.observableSet(new LinkedHashSet<>()); private final ObservableSet<Plugin<T>> loadedPlugins = FXCollections.observableSet(new LinkedHashSet<>()); /** * Creates a new plugin manager for the given target object. */ public PluginManager(T target) { this.target = target; } /** * Loads a plugin and applies it to the target. Has no effect if the plugin cannot be loaded. * * @param plugin the plugin to load * * @see #canLoad(Plugin) * @see #unload(Plugin) */ public void load(Plugin<T> plugin) { if (canLoad(plugin)) { plugin.applyTo(target); loadedPlugins.add(plugin); } knownPlugins.add(plugin); } /** * Checks if a plugin is currently loaded. * * @param plugin the plugin to check * * @return true if the plugin is loaded, false if it is not loaded */ public boolean isLoaded(Plugin<T> plugin) { return loadedPlugins.contains(plugin); } /** * Unloads a plugin and removes it from the target. Any loaded plugins that depend on it will also be unloaded. * * @param plugin the plugin to unload */ public void unload(Plugin<T> plugin) { plugin.removeFrom(target); unloadDependents(plugin); loadedPlugins.remove(plugin); } private void unloadDependents(Plugin<T> dependency) { loadedPlugins.stream() .filter(p -> p.dependsOn(dependency)) .collect(Collectors.toList()) .forEach(this::unload); } /** * Checks if a plugin can be loaded. A plugin can be loaded only if it meets all of the following conditions: * <ul> * <li>All of its requirements are currently loaded; and</li> * <li>No known plugin shares its name and group ID</li> * </ul> * * @param plugin the plugin to check * * @return true if the plugin can be loaded, false if not */ public boolean canLoad(Plugin<T> plugin) { return knownPlugins.stream() .noneMatch(p -> p.descriptor().idString().equals(plugin.descriptor().idString())) && plugin.requirements().stream() .allMatch(r -> loadedPlugins.stream().anyMatch(p -> r.matches(p.descriptor()))); } /** * Gets the set of plugins that have ever been attempted to be loaded. */ public ObservableSet<Plugin<T>> getKnownPlugins() { return knownPlugins; } /** * Gets the set of currently loaded plugins. */ public ObservableSet<Plugin<T>> getLoadedPlugins() { return loadedPlugins; } }
true
17c34f0ddc7fcaa20ba45e5b9ecf53a015e3c93a
Java
ChiHam-Lee/GUI_CHAT
/hello.java
UTF-8
9,073
2.875
3
[]
no_license
package hello; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import java.awt.Panel; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; /* class Receive extends Thread { public void run() { try { DatagramSocket socket = new DatagramSocket(9999); DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); while (true) { socket.receive(packet); String ip = packet.getAddress().getHostAddress(); byte[] arr = packet.getData(); int len = packet.getLength(); System.out.println("IP:" + ip + " " + new String(arr, 0, len)); } } catch (IOException e) { e.printStackTrace(); } } } class Send extends Thread { public void run() { try { Scanner sc = new Scanner(System.in); DatagramSocket socket = new DatagramSocket(); while (true) { String line = sc.nextLine(); if ("exit".equals(line)) { break; } DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 9999); socket.send(packet); } socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } */ class GUI extends Frame { private DatagramSocket socket; private TextField iptext; private Button send; private Button record; private Button clear; private Button shake; private TextArea chattext; private TextArea sendtext; private BufferedWriter writer; public GUI() { window(); downpanel(); middlepanel(); even(); } private class receive extends Thread { public void run() { try { DatagramSocket socket = new DatagramSocket(9999); DatagramPacket packet = new DatagramPacket(new byte[8192], 8192); while (true) { socket.receive(packet); byte[] arr = packet.getData(); int len = packet.getLength(); if (arr[0] == -1 && len == 1) { shake(); } else { String messenger = new String(arr, 0, len); String time = getTime(); String ip = packet.getAddress().getHostAddress(); String string = time + "\t" + ip + "说:\n" + messenger + "\n\n"; chattext.append(string); writer.write(string); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String getTime() { // TODO Auto-generated method stub Date d = new Date(); SimpleDateFormat sd = new SimpleDateFormat("yyyy年mm月dd日hh:mm:ss"); return sd.format(d); } } public void even() { this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { try { socket.close(); writer.close(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.exit(0); } }); // --------------------------------------------------Send---------------------------------------------------------------------- send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { send(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); sendtext.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub if (e.getKeyCode() == KeyEvent.VK_ENTER) { sendtext.append("\r"); } else if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isShiftDown()) { try { send(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); // --------------------------------------------------Record---------------------------------------------------------------------- record.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { recordFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); // --------------------------------------------------Clear---------------------------------------------------------------------- clear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub chattext.setText(""); } }); // --------------------------------------------------Shake---------------------------------------------------------------------- shake.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { send(new byte[] { -1 }, iptext.getText()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); } // ------------------SendMethod------------------------------------------------------------ public void send(byte[] arr, String ip) throws IOException { DatagramPacket packet = new DatagramPacket(arr, arr.length, InetAddress.getByName(ip), 9999); socket.send(packet); } private void send() throws IOException { // TODO Auto-generated method stub String messenger = sendtext.getText();// 获取发送框内容 String ip = iptext.getText();// 获取ip地址内容 ip = ip.trim().length() == 0?"255.255.255.255":ip;//如果ip地址为空,默认向所有人广播 send(messenger.getBytes(), ip); String time = getTime(); String string = time + "\t对" + (ip.equals("255.255.255.255")?"所有人":ip )+ "说:\n" + messenger + "\n\n"; chattext.append(string); writer.write(string);// 将信息写到文件中 sendtext.setText("");// 发送后清空发送区 } private String getTime() { // TODO Auto-generated method stub Date d = new Date(); SimpleDateFormat sd = new SimpleDateFormat("yyyy年mm月dd日HH:mm:ss"); return sd.format(d); } // ------------------ShakeMethod------------------------------------------------------------ private void shake() throws InterruptedException { int x = this.getLocation().x;// 获取x坐标 int y = this.getLocation().y;// 获取y坐标 for (int i = 0; i <= 10; i++) { this.setLocation(x + 50 * (int) Math.pow(-1, i), y + 50 * (int) Math.pow(-1, i));// 用40+(-1)的i次幂来实现转换窗口坐标 Thread.sleep(10); } this.setLocation(x, y); } // ------------------RecordMethod------------------------------------------------------------ private void recordFile() throws IOException { writer.flush(); FileInputStream input = new FileInputStream("info.txt"); ByteArrayOutputStream output = new ByteArrayOutputStream(); int i; byte[] arr = new byte[8192]; while ((i = input.read(arr)) != -1) { output.write(arr, 0, i); } String str = output.toString(); chattext.setText(str); input.close(); } public void middlepanel() { Panel middle = new Panel(); chattext = new TextArea();// 聊天文本区 chattext.setEditable(false);// 设置浏览文本区不可编辑 chattext.setBackground(Color.white);// 设置背景为白,不设置则为灰 sendtext = new TextArea();// 发送文本区 middle.setLayout(new BorderLayout()); middle.add(chattext, BorderLayout.CENTER); middle.add(sendtext, BorderLayout.SOUTH); this.add(middle, BorderLayout.CENTER); } public void downpanel() { Panel down = new Panel(); iptext = new TextField(30); iptext.setText("127.0.0.1"); send = new Button("Send"); clear = new Button("Clear"); record = new Button("Record"); shake = new Button("Shake"); down.add(iptext); down.add(send); down.add(clear); down.add(record); down.add(shake); this.add(down, BorderLayout.SOUTH); } public void window() { this.setLocation(500, 500); this.setSize(600, 700); try { socket = new DatagramSocket();// 新建socket对象 writer = new BufferedWriter(new FileWriter("info.txt", true));// 新建bufferedwriter对象,绑定info.txt文件储存信息,并在尾部append不是覆盖 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } new receive().start(); this.setVisible(true); } } class hello { public static void main(String[] args) throws IOException, InterruptedException { new GUI(); } }
true
b577f25b0312a5fffc02f316d883017f6f637c03
Java
krishnadontaraju/Day_16_StackAndQueue
/Queue.java
UTF-8
428
3.1875
3
[]
no_license
public class Queue<K> { CustomLinkedList customQueue = new CustomLinkedList(); public void enqueue(ParentNode parameterNode) { customQueue.append(parameterNode); } public void dequeue() { customQueue.popLast(); } public ParentNode showLatestNodeOfQueue() { return customQueue.head; } public ParentNode showFirstNodeOfQueue() { return customQueue.tail; } }
true
0963bdf289a03bc803ce63edc8c7577cc2efebf1
Java
KostyaSvirski/epam.test-web-1
/src/by/svirski/testweb/dao/DaoFactory.java
UTF-8
1,259
2.109375
2
[]
no_license
package by.svirski.testweb.dao; import by.svirski.testweb.dao.abstracts.realisation.CarDAO; import by.svirski.testweb.dao.abstracts.realisation.CommentDAO; import by.svirski.testweb.dao.abstracts.realisation.OrderDAO; import by.svirski.testweb.dao.abstracts.realisation.PenaltyDAO; import by.svirski.testweb.dao.abstracts.realisation.SystemDAOImpl; import by.svirski.testweb.dao.abstracts.realisation.UserDAO; public class DaoFactory { private final static DaoFactory instance = new DaoFactory(); private final UserDAO userDao = new UserDAO(); private final SystemDAOImpl siteDao = new SystemDAOImpl(); private final CarDAO carDao = new CarDAO(); private final OrderDAO orderDao = new OrderDAO(); private final PenaltyDAO penaltyDao = new PenaltyDAO(); private final CommentDAO commentDao = new CommentDAO(); private DaoFactory() { } public CarDAO getCarDao() { return carDao; } public static DaoFactory getInstance() { return instance; } public UserDAO getUserDao() { return userDao; } public SystemDAOImpl getSiteDao() { return siteDao; } public OrderDAO getOrderDao() { return orderDao; } public PenaltyDAO getPenaltyDao() { return penaltyDao; } public CommentDAO getCommentDao() { return commentDao; } }
true
3396fb14ef633a167e215e9f805754df80de9cca
Java
pasatigiy/HomeWork_21
/src/main/java/by/tms/service/CalcService.java
UTF-8
1,302
2.734375
3
[]
no_license
package by.tms.service; import by.tms.entity.Operation; import by.tms.entity.User; import by.tms.storage.OperationStorage; import java.util.List; public class CalcService { private final OperationStorage operationStorage = new OperationStorage(); public Operation calc (double a, double b, String operation, User user ){ switch (operation){ case "sum": Operation operation1 = new Operation(a, b, operation, a + b, user); operationStorage.save(operation1); return operation1; case "sub": Operation operation2 = new Operation(a, b, operation, a - b, user); operationStorage.save(operation2); return operation2; case "mul": Operation operation3 = new Operation(a, b, operation, a * b, user); operationStorage.save(operation3); return operation3; case "div": Operation operation4 = new Operation(a, b, operation, a / b, user); operationStorage.save(operation4); return operation4; } return null; } public List<Operation> findAll(){ return operationStorage.getAll(); } }
true
de1d0c5de5eac4033fd0c188474d33657a35c478
Java
Nebulous03/NebulousGameEngineV3
/src/com/nebulous/nebulousEngine/physics/boxes/SphereBoundBox.java
UTF-8
985
3.09375
3
[]
no_license
package com.nebulous.nebulousEngine.physics.boxes; import com.nebulous.nebulousEngine.core.logic.math.Vector3f; import com.nebulous.nebulousEngine.physics.Intersection; public class SphereBoundBox { private Vector3f center; private float radius; public SphereBoundBox(Vector3f center, float radius) { this.center = center; this.radius = radius; } public Intersection intersecting(SphereBoundBox other){ float radiusDistance = radius + other.getRadius(); float centerDistance = (other.getCenter().sub(center)).length(); float distance = other.getCenter().sub(center).length(); if(centerDistance < radiusDistance){ return new Intersection(true, distance); } else { return new Intersection(false, distance); } } public Vector3f getCenter() { return center; } public void setCenter(Vector3f center) { this.center = center; } public float getRadius() { return radius; } public void setRadius(float radius) { this.radius = radius; } }
true
3853cd3d5e95a29c565ae2493d1fa80d6d91662f
Java
tushar27rajput/UbuntuEcllipseSeleniumWebdriver
/MindQSystemAssignment/src/com/dataEncapsulation/Test1.java
UTF-8
791
3.3125
3
[]
no_license
package com.dataEncapsulation; public class Test1 { private int empSSNumber; private String empName; private int empAge; public static void main(String[] args) { Test1 obj = new Test1(); obj.setEmpSSNumber(1001); obj.setEmpName("Tushar Rajput"); obj.setEmpAge(28); System.out.println(obj.getEmpSSNumber()); System.out.println(obj.getEmpName()); System.out.println(obj.getEmpAge()); } public int getEmpSSNumber() { return empSSNumber; } public void setEmpSSNumber(int empSSNumber) { this.empSSNumber = empSSNumber; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpAge() { return empAge; } public void setEmpAge(int empAge) { this.empAge = empAge; } }
true
51fea0aaae82f7ec5b34317f7cba122575083743
Java
lehjr/MachineMusePowersuits
/src/recipecreator/java/lehjr/mpsrecipecreator/block/RecipeWorkbench.java
UTF-8
2,294
1.992188
2
[ "BSD-2-Clause" ]
permissive
package lehjr.mpsrecipecreator.block; import lehjr.mpsrecipecreator.container.MPSRCMenu; import lehjr.numina.client.sound.SoundDictionary; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; import net.minecraftforge.network.NetworkHooks; /** * @author lehjr */ public class RecipeWorkbench extends Block { public RecipeWorkbench() { super(Block.Properties.of(Material.WOOD) .strength(1.5F, 1000.0F) .sound(SoundType.METAL) .dynamicShape() .lightLevel((state) -> 15)); registerDefaultState(this.stateDefinition.any()); } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { player.playSound(SoundDictionary.SOUND_EVENT_GUI_SELECT.get(), 1.0F, 1.0F); if (worldIn.isClientSide) { return InteractionResult.SUCCESS; } else { NetworkHooks.openScreen((ServerPlayer) player, new SimpleMenuProvider((windowID, inventory, playerEntity) -> new MPSRCMenu(windowID, inventory), title), buf -> buf.writeBlockPos(pos)); return InteractionResult.SUCCESS; } } private static final Component title = Component.translatable("container.crafting"); @Override public MenuProvider getMenuProvider(BlockState state, Level level, BlockPos pos) { return new SimpleMenuProvider((id, inventory, player) -> new MPSRCMenu(id, inventory, ContainerLevelAccess.create(level, pos)), title); } }
true
3180ed01eeed115b459e4410bf8a3845b895ed29
Java
LeafKnow/XRings
/lib_common/src/main/java/com/yj/njh/common/flux/ActionMethodHolder.java
UTF-8
3,443
2.8125
3
[ "MIT" ]
permissive
package com.yj.njh.common.flux; import com.yj.njh.common.flux.annotation.BindAction; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * Created by oceanzhang on 16/2/17. */ public class ActionMethodHolder { private WeakReference<?> mObjectHolder; private Method mMethod; private Class<?> mParameterClass; private String mActionName; /** * 私有构造方法 * @param object * @param method * @param parameterClass * @param mActionName */ private ActionMethodHolder(Object object, Method method, Class<?> parameterClass, String mActionName) { this.mObjectHolder = new WeakReference<Object>(object); this.mMethod = method; this.mParameterClass = parameterClass; this.mActionName = mActionName; } /** * 传入一个obj,获取所有注解中的actionName,参数类型,并保存起来 * @param object * @return */ public static ActionMethodHolder[] findAllFluxActionMethods(Object object) { List<ActionMethodHolder> result = new ArrayList<>(); try { Class<?> clazz = object.getClass(); Method[] methods = clazz.getMethods(); for (Method m : methods) { // Annotation[] ann = m.getAnnotations(); Annotation annotation = null; if ( (annotation = hasActionAnnotation(m)) == null) { continue; } String actionName = ((BindAction)annotation).value(); Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length != 1) { continue; } Class<?> param = paramTypes[0]; result.add(new ActionMethodHolder(object, m, param,actionName)); } } catch (Throwable e) { e.printStackTrace(); } return result.toArray(new ActionMethodHolder[0]); } /** * 判断是否有BindAction的注解在方法上 * return true when the method has @Flux annotation * @param method * @return */ private static Annotation hasActionAnnotation(Method method) { Annotation[] ann = method.getAnnotations(); if (ann == null || ann.length == 0) { return null; } for (Annotation a : ann) { if (a instanceof BindAction) { return a; } } return null; } /** * 调用注解标注的方法 * call holding method. * If the object will be released, do nothing in this method. * @param parameter * @return */ public boolean call(Object parameter) { Object receiver = this.mObjectHolder.get(); if (receiver == null) { return false; } try { this.mMethod.invoke(receiver, parameter); return true; } catch (Throwable e) { System.out.println("ErrorHappened:" + e); e.printStackTrace(); return false; } } //accessor public Object getReceiver() { return this.mObjectHolder.get(); } public Class<?> getParameterClass() { return mParameterClass; } public String getmActionName() { return mActionName; } }
true
604ea346ff8067d6dc08630ec4515724f3378057
Java
feiger184/WoodPersons
/app/src/main/java/com/jywy/woodpersons/network/entity/UnSoldMarketKind.java
UTF-8
711
1.914063
2
[]
no_license
package com.jywy.woodpersons.network.entity; import com.google.gson.annotations.SerializedName; /** * Created by 高 on 2017/3/27. */ public class UnSoldMarketKind { /** * kindid : 1 * kindname : 原木 * kind_bj : 0 * portid : 1 * kindname_en-us : 0 */ @SerializedName("kindid") private String kindId; @SerializedName("kindname") private String kindName; public String getKindId() { return kindId; } public void setKindId(String kindId) { this.kindId = kindId; } public String getKindName() { return kindName; } public void setKindName(String kindName) { this.kindName = kindName; } }
true
44cd2843063addee809d2f66fa2f15b5d25f350d
Java
mdasrafhamid/grocery
/GroceryProject/src/com/grocery/Item.java
UTF-8
831
3.21875
3
[]
no_license
package com.grocery; import java.util.*; public class Item { private String name; private int qty; private float price; private static List<Item> itemList = new ArrayList<>(); Item(String n, int quantity, float p){ name = n; qty= quantity; price = p; } public static void addToList(Item item) { itemList.add(item); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public String toString() { return "this is a "+name; } public static List<Item> getList() { return itemList; } }
true
bb995920cce6c5e2bf90d357887e6b6876757ef4
Java
WinterPan2017/Android-Malware-Detection
/getAndroidAPI/src/android/view/animation/GridLayoutAnimationController.java
UTF-8
2,832
1.867188
2
[]
no_license
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: GridLayoutAnimationController.java package android.view.animation; import android.content.Context; import android.util.AttributeSet; import android.view.View; // Referenced classes of package android.view.animation: // LayoutAnimationController, Animation public class GridLayoutAnimationController extends LayoutAnimationController { public static class AnimationParameters extends LayoutAnimationController.AnimationParameters { public int column; public int columnsCount; public int row; public int rowsCount; public AnimationParameters() { throw new RuntimeException("Stub!"); } } public GridLayoutAnimationController(Context context, AttributeSet attrs) { super((Animation)null); throw new RuntimeException("Stub!"); } public GridLayoutAnimationController(Animation animation) { super((Animation)null); throw new RuntimeException("Stub!"); } public GridLayoutAnimationController(Animation animation, float columnDelay, float rowDelay) { super((Animation)null); throw new RuntimeException("Stub!"); } public float getColumnDelay() { throw new RuntimeException("Stub!"); } public void setColumnDelay(float columnDelay) { throw new RuntimeException("Stub!"); } public float getRowDelay() { throw new RuntimeException("Stub!"); } public void setRowDelay(float rowDelay) { throw new RuntimeException("Stub!"); } public int getDirection() { throw new RuntimeException("Stub!"); } public void setDirection(int direction) { throw new RuntimeException("Stub!"); } public int getDirectionPriority() { throw new RuntimeException("Stub!"); } public void setDirectionPriority(int directionPriority) { throw new RuntimeException("Stub!"); } public boolean willOverlap() { throw new RuntimeException("Stub!"); } protected long getDelayForView(View view) { throw new RuntimeException("Stub!"); } public static final int DIRECTION_BOTTOM_TO_TOP = 2; public static final int DIRECTION_HORIZONTAL_MASK = 1; public static final int DIRECTION_LEFT_TO_RIGHT = 0; public static final int DIRECTION_RIGHT_TO_LEFT = 1; public static final int DIRECTION_TOP_TO_BOTTOM = 0; public static final int DIRECTION_VERTICAL_MASK = 2; public static final int PRIORITY_COLUMN = 1; public static final int PRIORITY_NONE = 0; public static final int PRIORITY_ROW = 2; }
true
b49006822d9af8538f8dfe3e0108fd43b1931233
Java
KitKatCake/Guava
/src/main/java/Gek/PredicateDemo.java
UTF-8
716
3.40625
3
[]
no_license
package Gek; import java.util.function.Predicate; public class PredicateDemo { public static void main(String[] args) { // // Creating predicate // Predicate<Integer> lessthan = i ->(i<18); // // // Calling Predicate method // System.out.println(lessthan.test(10)); // Creating predicate Predicate<Integer> greaterThanTen = (i)->i>10; Predicate<Integer> lowerThanTwenty = (i)->i<20; boolean result = greaterThanTen.and(lowerThanTwenty).test(15); System.out.println(result); // Calling Predicate method boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15); System.out.println(result2); } }
true
d1e83ce59c0fec5a8f31ce140a760fa9b0f226e0
Java
ESSE-xiaogui/kom_manager_new
/source/kom-manager-api/src/main/java/com/transsion/store/dto/TaskGoalModelDto.java
UTF-8
3,213
2.171875
2
[]
no_license
package com.transsion.store.dto; import java.io.Serializable; import java.util.Map; public class TaskGoalModelDto implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public static final String HEADER_COMPANY_CODE = "事业部"; public static final String HEADER_GOAL_MONTH = "年/月"; public static final String HEADER_USER_CODE = "用户名"; public static final String HEADER_SHOP_CODE = "门店编码"; public static final String HEADER_MODEL_CODE = "重点机型"; public static final String HEADER_SALE_TARGET = "销量目标"; public static String[] IMPORT_HEADERS= {HEADER_COMPANY_CODE,HEADER_GOAL_MONTH,HEADER_USER_CODE,HEADER_SHOP_CODE,HEADER_MODEL_CODE,HEADER_SALE_TARGET}; //Excel中字段 private String companyCode; private String goalMonth; private String userCode; private String shopCode; private String modelCode; private String saleTarget; //额外字段 private Long companyId; private Long modelId; private Long shopId; //task表 private String context; public void copyFormMap(Map<String, Object> importMap) { companyCode = (String) importMap.get(HEADER_COMPANY_CODE); goalMonth = (String) importMap.get(HEADER_GOAL_MONTH); userCode = (String) importMap.get(HEADER_USER_CODE); shopCode = (String) importMap.get(HEADER_SHOP_CODE); modelCode = (String) importMap.get(HEADER_MODEL_CODE); saleTarget = (String)importMap.get(HEADER_SALE_TARGET); } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public String getGoalMonth() { return goalMonth; } public void setGoalMonth(String goalMonth) { this.goalMonth = goalMonth; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getShopCode() { return shopCode; } public void setShopCode(String shopCode) { this.shopCode = shopCode; } public String getModelCode() { return modelCode; } public void setModelCode(String modelCode) { this.modelCode = modelCode; } public String getSaleTarget() { return saleTarget; } public void setSaleTarget(String saleTarget) { this.saleTarget = saleTarget; } public Long getCompanyId() { return companyId; } public void setCompanyId(Long companyId) { this.companyId = companyId; } public Long getModelId() { return modelId; } public void setModelId(Long modelId) { this.modelId = modelId; } public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public void setContext(String context) { this.context = context; } public String getContext(){ context = HEADER_COMPANY_CODE +":" +companyCode + "\r" + HEADER_GOAL_MONTH+":" + goalMonth + "\r" + HEADER_USER_CODE+":" + userCode + "\r" + HEADER_SHOP_CODE+":"+ shopCode+ "\r" +HEADER_MODEL_CODE+":"+modelCode+"\r"+ HEADER_SALE_TARGET+":"+saleTarget; return context; } }
true
79c2e24b396a65cc5a696f4e263d570865634a21
Java
xuhengfei/slovef-sdk
/src/com/slovef/android/filesystem/FileCache.java
WINDOWS-1252
676
2.65625
3
[]
no_license
package com.slovef.android.filesystem; import java.util.concurrent.atomic.AtomicBoolean; public class FileCache { private static String ROOT; private static AtomicBoolean initd=new AtomicBoolean(false); public static void init(String root){ if(initd.get()){ return; } if(!root.endsWith("/")){ root=root+"/"; } ROOT=root; initd.set(true); } public static String getCacheFolder(){ if(!initd.get()){ throw new RuntimeException("Please call init() first"); } return ROOT; } /** * */ public static void clearCache(){ if(!initd.get()){ throw new RuntimeException("Please call init() first"); } //TODO } }
true
d0254cc05dcf29a64158c4e5025bb1eeb05a292a
Java
ntmanh/ktnb4
/ktnb_web/JavaSource/cmc/com/ktnb/web/kntc/xac_minh/tien_hanh/BaoCaoForm.java
UTF-8
3,465
2.0625
2
[]
no_license
package cmc.com.ktnb.web.kntc.xac_minh.tien_hanh; import cmc.com.ktnb.pl.hb.entity.KntcBaoCao; import cmc.com.ktnb.util.Formater; import cmc.com.ktnb.web.BaseActionForm; /** * Báo cáo form * @author Ntthu * Created on 03/03/2011 */ public class BaoCaoForm extends BaseActionForm { // Thong tin Ho so private String maPhieu; private String maHoSo; private String kntcQdinhXm; private String diaDiem; private String ngayLap; private String doanXm; private String ngayPhieuYcgt; private String nguoiLapBc; private String nguoiLapBcChucVu; private String nguoiLapBcDvCt; private String noiDungGt,lanTd; public KntcBaoCao toEntity() throws Exception { KntcBaoCao pYc = new KntcBaoCao(); pYc.setMaHs(this.maHoSo); pYc.setDiaDiem(this.diaDiem); pYc.setThoiDiem(Formater.str2date(this.ngayLap)); pYc.setNguoiLap(this.nguoiLapBc); pYc.setNguoiLapCvu(this.nguoiLapBcChucVu); pYc.setNguoiLapDvi(this.nguoiLapBcDvCt); pYc.setNgayYc(Formater.str2date(this.ngayPhieuYcgt)); pYc.setNoiDung(this.noiDungGt); pYc.setTenDoan(this.doanXm); if(!Formater.isNull(this.lanTd)) pYc.setLanTd(new Long(this.lanTd)); else pYc.setLanTd(new Long("0")); return pYc; } /** * @return */ public String getDiaDiem() { return diaDiem; } /** * @return */ public String getDoanXm() { return doanXm; } /** * @return */ public String getKntcQdinhXm() { return kntcQdinhXm; } /** * @return */ public String getMaHoSo() { return maHoSo; } /** * @return */ public String getMaPhieu() { return maPhieu; } /** * @return */ public String getNgayLap() { return ngayLap; } /** * @return */ public String getNgayPhieuYcgt() { return ngayPhieuYcgt; } /** * @return */ public String getNguoiLapBc() { return nguoiLapBc; } /** * @return */ public String getNguoiLapBcChucVu() { return nguoiLapBcChucVu; } /** * @return */ public String getNguoiLapBcDvCt() { return nguoiLapBcDvCt; } /** * @return */ public String getNoiDungGt() { return noiDungGt; } /** * @param string */ public void setDiaDiem(String string) { diaDiem = string; } /** * @param string */ public void setDoanXm(String string) { doanXm = string; } /** * @param string */ public void setKntcQdinhXm(String string) { kntcQdinhXm = string; } /** * @param string */ public void setMaHoSo(String string) { maHoSo = string; } /** * @param string */ public void setMaPhieu(String string) { maPhieu = string; } /** * @param string */ public void setNgayLap(String string) { ngayLap = string; } /** * @param string */ public void setNgayPhieuYcgt(String string) { ngayPhieuYcgt = string; } /** * @param string */ public void setNguoiLapBc(String string) { nguoiLapBc = string; } /** * @param string */ public void setNguoiLapBcChucVu(String string) { nguoiLapBcChucVu = string; } /** * @param string */ public void setNguoiLapBcDvCt(String string) { nguoiLapBcDvCt = string; } /** * @param string */ public void setNoiDungGt(String string) { noiDungGt = string; } public String getLanTd() { return lanTd; } public void setLanTd(String lanTd) { this.lanTd = lanTd; } }
true
c09905b175e8f252e6664238b3682b068cc996bd
Java
SurbhiRautji23/Resonance
/src/main/java/edu/sjsu/models/SongDao.java
UTF-8
403
1.992188
2
[]
no_license
package edu.sjsu.models; import java.util.ArrayList; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; /** * Created by harkirat singh on 3/9/2016. */ public interface SongDao extends CrudRepository<Song, Long> { @Query(value="SELECT * FROM songs Order By date DESC LIMIT 0, 10",nativeQuery = true) ArrayList<Song> getLatestSongs(); }
true
2c99a92371b81d41fa4ee5212b7ef0566a008f0d
Java
alldatacenter/alldata
/studio/micro-services/SREWorks/paas/appmanager/tesla-appmanager-server/src/main/java/com/alibaba/tesla/appmanager/server/repository/ComponentHistoryRepository.java
UTF-8
906
1.8125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "EPL-1.0", "LGPL-2.0-or-later", "BSD-3-Clause", "MIT", "MPL-2.0", "GPL-2.0-only", "JSON", "EPL-2.0" ]
permissive
package com.alibaba.tesla.appmanager.server.repository; import com.alibaba.tesla.appmanager.server.repository.condition.ComponentHistoryQueryCondition; import com.alibaba.tesla.appmanager.server.repository.domain.ComponentHistoryDO; import java.util.List; public interface ComponentHistoryRepository { long countByCondition(ComponentHistoryQueryCondition condition); int deleteByCondition(ComponentHistoryQueryCondition condition); int insert(ComponentHistoryDO record); List<ComponentHistoryDO> selectByConditionWithBLOBs(ComponentHistoryQueryCondition condition); List<ComponentHistoryDO> selectByCondition(ComponentHistoryQueryCondition condition); int updateByConditionWithBLOBs(ComponentHistoryDO record, ComponentHistoryQueryCondition condition); int updateByCondition(ComponentHistoryDO record, ComponentHistoryQueryCondition condition); }
true
8b63e7d35e36ed75a43d0c458e92bcd3f0a5c2a1
Java
gtg124x/iRP
/app/src/main/java/team1/gatech/edu/irp/model/AccountStateENUM.java
UTF-8
156
1.71875
2
[]
no_license
package team1.gatech.edu.irp.model; /** Account States Enum * * @author Mitchell_Alvarado */ public enum AccountStateENUM { LOCKED, UNLOCKED }
true
cfc8c8cb15fdd7267de6a70989caa7519e6368be
Java
igortimbalenco/tekwill-homework
/src/com/itimbalenco/homework/forloop31032021/CumulativeSum.java
UTF-8
709
3.640625
4
[]
no_license
package com.itimbalenco.homework.forloop31032021; import java.util.Scanner; public class CumulativeSum { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number, sum; System.out.print("Enter your number please: "); sum = number = scanner.nextInt(); System.out.println("The sum of all entered numbers is: " + sum); for (int i = 0; number != 0;i++){ System.out.print("Enter your number please: "); number = scanner.nextInt(); sum += number; System.out.println("The sum of all entered numbers is: " + sum); } System.out.println("Loop terminated"); } }
true
e0daff34284d6c5338d1729f3c8fe568180e5ba9
Java
OnelongX/demos
/HadoopHello/src/main/java/com/ways2u/SparkDemo.java
UTF-8
18,575
2.34375
2
[ "MIT" ]
permissive
package com.ways2u; import java.io.FileWriter; import java.io.IOException; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.hadoop.io.RawComparator; import org.apache.log4j.net.SyslogAppender; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.*; import org.apache.spark.mllib.tree.configuration.Strategy; import scala.Tuple2; public class SparkDemo { private static final String USER = "huanglong"; static class MyComparator implements Comparator<Tuple2<String, Integer>>,Serializable { @Override public int compare(Tuple2<String, Integer> o1, Tuple2<String, Integer> o2) { return o1._2.compareTo(o2._2); } } static class MyComparator1 implements Comparator<String>,Serializable { @Override public int compare(String o1, String o2) { return Integer.valueOf(o1).compareTo(Integer.valueOf(o2)); } } public static void main(String[] args) throws Exception { System.setProperty("user.name", USER); // 设置访问Spark使用的用户名 System.setProperty("HADOOP_USER_NAME", USER); // 设置访问Hadoop使用的用户名 Map<String, String> envs = new HashMap<String, String>(); envs.put("HADOOP_USER_NAME", USER); // 为Spark环境中服务于本App的各个Executor程序设置访问Hadoop使用的用户名 System.setProperty("spark.executor.memory", "512m"); // 为Spark环境中服务于本App的各个Executor程序设置使用内存量的上限 // 以下构造sc对象的构造方法各参数意义依次为: // Spark Master的地址; // App的名称; // Spark Worker的部署位置; // 需要提供给本App的各个Executor程序下载的jar包的路径列表,这些jar包将出现在Executor程序的类路径中; // 传递给本App的各个Executor程序的环境信息。 SparkConf conf =new SparkConf().setAppName("Spark Log").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); //其底层就是scala的sparkcontext //JavaSparkContext sc = new JavaSparkContext("local[4]", "Spark Log", "/user/huanglong/spark", new String[0], envs); long start = System.currentTimeMillis(); String file = "file:///Users/huanglong/Desktop/HadoopHello/src/main/java/com/ways2u/access_05_30.log"; JavaRDD<String> data = sc.textFile(file, 4); //日志格式 //String log = "27.19.74.143 - - [30/May/2013:17:38:20 +0800] \"GET /static/image/common/faq.gif HTTP/1.1\" 200 1127"; final Pattern pattern = Pattern.compile("^(\\S+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(\\S+) (\\S+) (\\S+)\" (\\d{3}) (\\S+)"); /* Matcher m = pattern.matcher(log); if (m.matches()){ System.out.println(m.group(1));//ip System.out.println(m.group(2));//- System.out.println(m.group(3));//- System.out.println(m.group(4));//time System.out.println(m.group(5));//methom System.out.println(m.group(6));//url System.out.println(m.group(7));//version System.out.println(m.group(8));//state System.out.println(m.group(9));//size } */ //"^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] \"(\S+) (\S+) (\S+)\" (\d{3}) (\d+)"; JavaRDD<String> filter = data.filter(new org.apache.spark.api.java.function.Function<String, Boolean>() { @Override public Boolean call(String s) throws Exception { //过滤合法和非静态的资源的日志 return (s.contains("POST")||s.contains("GET"))&& !s.contains("/static/"); } }); final SimpleDateFormat tf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH); //只有一天的记录,不需要年月日了,时间精度到分钟 final SimpleDateFormat tf1 = new SimpleDateFormat("HH:mm"); JavaRDD<Map<String,String>> lines = filter.flatMap(new FlatMapFunction<String,Map<String,String>>(){ @Override public Iterator<Map<String,String>> call(String s) throws Exception { List<Map<String,String>> list = new ArrayList<Map<String,String>>(1); Map<String,String> map = new HashMap<String, String>(); Matcher m = pattern.matcher(s); if (m.matches()){ list.add(map); map.put("ip",m.group(1)); //System.out.println(m.group(1));//ip //System.out.println(m.group(2));//- //System.out.println(m.group(3));//- Date date = tf.parse(m.group(4)); map.put("time",tf1.format(date)); //System.out.println(m.group(4));//time //System.out.println(m.group(5));//methom String url = m.group(6); if(url!=null&&url.indexOf("?")!=-1) { map.put("url",url.substring(0,url.indexOf("?"))); }else { map.put("url",url); } //System.out.println(m.group(6));//url map.put("version",m.group(7)); //System.out.println(m.group(7));//version map.put("state", m.group(8)); //System.out.println(m.group(8));//state //System.out.println(m.group(9));//size }else { //System.out.println(s); } //非正则表达式方式,正则相对快一点点 /* String ip = s.substring(0,s.indexOf(" - - ")); map.put("ip",ip); String t = s.substring(s.indexOf("[")+1,s.indexOf("]")); Date date = tf.parse(t); map.put("time",tf1.format(date)); String http = s.substring(s.indexOf("\"")+1,s.indexOf("\" ")); String[] h= http.split(" "); if(h.length>1){ if(h[1]!=null&&h[1].indexOf("?")!=-1) { map.put("url",h[1].substring(0,h[1].indexOf("?"))); }else { map.put("url",h[1]); } } if(h.length>2) { map.put("version",h[2]); } if(map.get("version")!=null&&map.get("version").contains("1.1")) { String state = s.substring(s.indexOf("1.1\" ")+5,s.length()); String[] strings = state.split(" "); if(strings.length>0) { map.put("state", strings[0]); } }else if(map.get("version")!=null&&map.get("version").contains("1.0")) { String state = s.substring(s.indexOf("1.0\" ")+5,s.length()); String[] strings = state.split(" "); if(strings.length>0) { map.put("state", strings[0]); } }else { //System.out.println(s); } */ return list.iterator(); } }).cache(); /** *cache ,如果某个RDD反复的被使用,可以考虑将其进行cache */ System.out.println("总记录数:"+lines.count()); // 统计ip ipsHandle(lines); System.out.println("--------------------------------------------------"); // 统计分时页面访问量 timeHandle(lines); System.out.println("--------------------------------------------------"); // 统计分时ip访问量 timeHandle3(lines); System.out.println("--------------------------------------------------"); // 统计状态 400,300 200 各有多少,计算失败率 stateHandle(lines); System.out.println("--------------------------------------------------"); // 统计http版本 1.1、1.0 versionHandle(lines); // 页面热度 System.out.println("--------------------------------------------------"); // pageHandle(lines); System.out.println("--------------------------------------------------"); System.out.println(System.currentTimeMillis() - start); System.out.println("--------------------------------------------------"); sc.close(); } private static void pageHandle(JavaRDD<Map<String, String>> lines) { JavaRDD<Map<String, String>> filterData = lines.filter(new Function<Map<String, String>, Boolean>() { @Override public Boolean call(Map<String, String> map) throws Exception { String url = map.get("url"); return "200".equals(map.get("state"))&&url.endsWith(".php"); } }); JavaPairRDD<String,Integer> versionPairs = filterData.mapToPair(new PairFunction<Map<String,String>, String,Integer>() { @Override public Tuple2<String,Integer> call(Map<String, String> stringStringMap) throws Exception { return new Tuple2<String, Integer>(stringStringMap.get("url"),1); } }); JavaPairRDD<String,Integer> versionCount = versionPairs.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) throws Exception { return v1+v2; } }); versionCount.foreach(new VoidFunction<Tuple2<String,Integer>>() { @Override public void call(Tuple2<String, Integer> pairs) throws Exception { System.out.println("URL->PV:"+pairs._1+" : " +pairs._2); } }); } private static void versionHandle(JavaRDD<Map<String, String>> lines) { JavaPairRDD<String,Integer> versionPairs = lines.mapToPair(new PairFunction<Map<String,String>, String,Integer>() { @Override public Tuple2<String,Integer> call(Map<String, String> stringStringMap) throws Exception { return new Tuple2<String, Integer>(stringStringMap.get("version"),1); } }); JavaPairRDD<String,Integer> versionCount = versionPairs.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) throws Exception { return v1+v2; } }); versionCount.foreach(new VoidFunction<Tuple2<String,Integer>>() { @Override public void call(Tuple2<String, Integer> pairs) throws Exception { System.out.println("VERSION->PV:"+pairs._1+" : " +pairs._2); } }); } private static void stateHandle(JavaRDD<Map<String, String>> lines) { JavaPairRDD<String,Integer> statePairs = lines.mapToPair(new PairFunction<Map<String,String>, String,Integer>() { @Override public Tuple2<String,Integer> call(Map<String, String> stringStringMap) throws Exception { return new Tuple2<String, Integer>(stringStringMap.get("state"),1); } }); JavaPairRDD<String,Integer> stateCount = statePairs.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) throws Exception { return v1+v2; } // }).sortByKey(); /* JavaPairRDD<SecondarySortKey,Integer> srdd= stateCount.mapToPair(new PairFunction<Tuple2<String,Integer>, SecondarySortKey, Integer>() { @Override public Tuple2<SecondarySortKey, Integer> call(Tuple2<String, Integer> t) throws Exception { SecondarySortKey s = new SecondarySortKey(); s.key = t._1; s.count = t._2; return new Tuple2<SecondarySortKey, Integer>(s,t._2); } }).sortByKey(false); */ /* List<Tuple2<String, Integer>> srdd = stateCount.top(10,new MyComparator()); for (Tuple2<String, Integer> pairs:srdd) { System.out.println("STATE->PV:"+pairs._1+" : " +pairs._2); } */ stateCount.foreach(new VoidFunction<Tuple2<String,Integer>>() { @Override public void call(Tuple2<String, Integer> pairs) throws Exception { System.out.println("STATE->PV:"+pairs._1+" : " +pairs._2); } }); } private static void ipsHandle(JavaRDD<Map<String, String>> lines) { JavaPairRDD<String,Integer> ipPairs = lines.mapToPair(new PairFunction<Map<String,String>, String,Integer>() { @Override public Tuple2<String,Integer> call(Map<String, String> stringStringMap) throws Exception { return new Tuple2<String, Integer>(stringStringMap.get("ip"),1); } }); JavaPairRDD<String,Integer> ipCount = ipPairs.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) throws Exception { return v1+v2; } }); System.out.println("总ip数:"+ipCount.count()); /* ipCount.foreach(new VoidFunction<Tuple2<String,Integer>>() { @Override public void call(Tuple2<String, Integer> pairs) throws Exception { System.out.println("IP->PV:"+pairs._1+" : " +pairs._2); } }); */ List<Tuple2<String, Integer>> top10 = ipCount.top(10, new MyComparator()); for (Tuple2<String, Integer> pairs:top10) { System.out.println("IP->PV:"+pairs._1+" : " +pairs._2); } } private static void timeHandle3(JavaRDD<Map<String, String>> lines) { JavaPairRDD<String,String> timePairs = lines.mapToPair(new PairFunction<Map<String,String>, String,String>() { @Override public Tuple2<String,String> call(Map<String, String> stringStringMap) throws Exception { return new Tuple2<String, String>(stringStringMap.get("time"),stringStringMap.get("ip")); } }); JavaPairRDD<String, Integer> pairs = timePairs.groupBy(new Function<Tuple2<String,String>, String>() { @Override public String call(Tuple2<String, String> t) throws Exception { return t._1; } }).mapToPair(new PairFunction<Tuple2<String,Iterable<Tuple2<String,String>>>, String, Integer>() { @Override public Tuple2<String, Integer> call(Tuple2<String, Iterable<Tuple2<String, String>>> t) throws Exception { Collection c = (Collection)t._2; return new Tuple2<String, Integer>(t._1,c.size()); } }); List<Tuple2<String, Integer>> top10 = pairs.top(10, new MyComparator()); for (Tuple2<String, Integer> p:top10) { System.out.println("TIME->IP:"+p._1+" : " +p._2); } /* pairs.foreach(new VoidFunction<Tuple2<String, Integer>>() { @Override public void call(Tuple2<String, Integer> pairs) throws Exception { System.out.println("TIME->IP:"+pairs._1+" : " +pairs._2); } }); */ } private static void timeHandle2(JavaRDD<Map<String, String>> lines) { JavaPairRDD<String,Map<String,Boolean>> timePairs = lines.mapToPair(new PairFunction<Map<String,String>, String,Map<String,Boolean>>() { @Override public Tuple2<String,Map<String,Boolean>> call(Map<String, String> stringStringMap) throws Exception { Map<String,Boolean> m = new HashMap<String, Boolean>(); m.put(stringStringMap.get("ip"),Boolean.TRUE); return new Tuple2<String, Map<String,Boolean>>(stringStringMap.get("time"),m); } }); JavaPairRDD<String,Map<String,Boolean>> timeCount = timePairs.reduceByKey(new Function2<Map<String,Boolean>, Map<String,Boolean>, Map<String,Boolean>>() { @Override public Map<String,Boolean> call(Map<String,Boolean> v1, Map<String,Boolean> v2) throws Exception { HashMap<String, Boolean> m = new HashMap<String, Boolean>(); m.putAll(v1); m.putAll(v2); return m; } }); timeCount.foreach(new VoidFunction<Tuple2<String, Map<String,Boolean>>>() { @Override public void call(Tuple2<String, Map<String,Boolean>> pairs) throws Exception { System.out.println("TIME->IP:"+pairs._1+" : " +pairs._2.size()); } }); } private static void timeHandle(JavaRDD<Map<String, String>> lines) { JavaPairRDD<String,Integer> timePairs = lines.mapToPair(new PairFunction<Map<String,String>, String,Integer>() { @Override public Tuple2<String,Integer> call(Map<String, String> stringStringMap) throws Exception { return new Tuple2<String, Integer>(stringStringMap.get("time"),1); } }); JavaPairRDD<String,Integer> timeCount = timePairs.reduceByKey(new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) throws Exception { return v1+v2; } }); List<Tuple2<String, Integer>> top10 = timeCount.top(10, new MyComparator()); for (Tuple2<String, Integer> p:top10) { System.out.println("TIME->PV:"+p._1+" : " +p._2); } /* timeCount.foreach(new VoidFunction<Tuple2<String,Integer>>() { @Override public void call(Tuple2<String, Integer> pairs) throws Exception { System.out.println("TIME->PV:"+pairs._1+" : " +pairs._2); } }); */ } }
true
2973acc16454a02ca0d2699095d856b8b3362f8b
Java
itdanja/java_0616
/java1/src/Day10/Day10_1.java
UHC
3,277
4.09375
4
[]
no_license
package Day10; import java.util.Scanner; public class Day10_1 { // ó : ߻ ٸڵ ó // : ġ ߻ => Ŭ ش ϰ ó // : // 1. try{ ߻ ڵ } // catch(Ŭ ü){ ߻ üڵ } // finally{ Ǵ ڵ } // Ŭ : // 1. ܸ ˰ ִ° // 1. ArrayIndexOutOfBoundsException // 2. NullPointerException // 3. NumberFormatException // 2. ܸ 𸣴° // 1. Exception [ Ŭ ] // 3. ܴ // 1. throws Exception public static void main(String[] args) { //1 ) 迭/ ڸ Ұ => ߻ try { // try{ } ߻ÿ catch{} ̵ int[] 迭 = new int[3]; 迭[0] = 10; 迭[1] = 20; 迭[2] = 30; 迭[4] = 40; // ߻ => catch ̵ }catch( ArrayIndexOutOfBoundsException e ){ // [ܹ߻]Ŭ ü[] System.out.println(" ߻ : " + e); } //2) null ΰ ü½ => ߻ try { String data = null; System.out.println( data ); System.out.println( data.toString() ); // ü.toString() : ü ޼ҵ }catch (NullPointerException e) { System.out.println(" ߻ : " + e); } //3) => // => ȯ => ߻ try { String data1 = "100"; String data2 = "a100"; System.out.println( Integer.parseInt(data1) ); // Integer.parseInt(ڿ); ڿ => ڿ System.out.println( Integer.parseInt(data2) ); } catch (NumberFormatException e) { System.out.println(" ߻ : " + e); System.out.println("ڰ Ե ڴ ڷ ȯҼ ϴ"); } // 4) ܸ óִ Ŭ Exception try { // 1. int[] 迭 = new int[3]; 迭[0] = 10; 迭[1] = 20; 迭[2] = 30; 迭[4] = 40; // ߻ => catch ̵ // 2. String data = null; System.out.println( data ); System.out.println( data.toString() ); // ü.toString() : ü ޼ҵ // 3. String data1 = "100"; String data2 = "a100"; System.out.println( Integer.parseInt(data1) ); // Integer.parseInt(ڿ); ڿ => ڿ System.out.println( Integer.parseInt(data2) ); } catch (Exception e) { System.out.println("[[߻]] : " + e); } finally { // Ǵ ڵ [ ܹ߻ ] . System.out.println("[[ڵ ]]"); } //1 while(true) { Scanner scanner = new Scanner(System.in); // new : ޸ Ҵ [ Ӱ ޸ Ҵ ] try { System.out.print( "ȣ : "); int = scanner.nextInt(); } catch (Exception e) { System.out.println(" [] : ڸ Է մϴ "); }finally { System.out.println(" ó Ǿϴ "); } } } }
true
46b3a9dffcea9e072e54da9b67350f14e525dc57
Java
eduardoal86/psneon
/PSNeon/app/src/main/java/edualves/com/psneon/BaseApp.java
UTF-8
823
2.125
2
[]
no_license
package edualves.com.psneon; import android.app.Application; import edualves.com.psneon.components.AppComponent; import edualves.com.psneon.components.DaggerAppComponent; import edualves.com.psneon.modules.AppModule; import edualves.com.psneon.modules.PrefsModule; import edualves.com.psneon.modules.NetworkModule; /** * Created by edualves on 30/06/17. */ public class BaseApp extends Application { AppComponent appComponent; @Override public void onCreate() { super.onCreate(); appComponent = DaggerAppComponent.builder() .networkModule(new NetworkModule()) .prefsModule(new PrefsModule()) .appModule(new AppModule(this)) .build(); } public AppComponent getAppComponent() { return appComponent; } }
true
be5d61f2117e6281b47a531761638f445898a6bc
Java
BulkSecurityGeneratorProject/simple-service
/src/main/java/com/pure/service/service/impl/CustomerConsumerLogServiceImpl.java
UTF-8
2,474
2.515625
3
[]
no_license
package com.pure.service.service.impl; import com.pure.service.service.CustomerConsumerLogService; import com.pure.service.domain.CustomerConsumerLog; import com.pure.service.repository.CustomerConsumerLogRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing CustomerConsumerLog. */ @Service @Transactional public class CustomerConsumerLogServiceImpl implements CustomerConsumerLogService{ private final Logger log = LoggerFactory.getLogger(CustomerConsumerLogServiceImpl.class); private final CustomerConsumerLogRepository customerConsumerLogRepository; public CustomerConsumerLogServiceImpl(CustomerConsumerLogRepository customerConsumerLogRepository) { this.customerConsumerLogRepository = customerConsumerLogRepository; } /** * Save a customerConsumerLog. * * @param customerConsumerLog the entity to save * @return the persisted entity */ @Override public CustomerConsumerLog save(CustomerConsumerLog customerConsumerLog) { log.debug("Request to save CustomerConsumerLog : {}", customerConsumerLog); return customerConsumerLogRepository.save(customerConsumerLog); } /** * Get all the customerConsumerLogs. * * @param pageable the pagination information * @return the list of entities */ @Override @Transactional(readOnly = true) public Page<CustomerConsumerLog> findAll(Pageable pageable) { log.debug("Request to get all CustomerConsumerLogs"); return customerConsumerLogRepository.findAll(pageable); } /** * Get one customerConsumerLog by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public CustomerConsumerLog findOne(Long id) { log.debug("Request to get CustomerConsumerLog : {}", id); return customerConsumerLogRepository.findOne(id); } /** * Delete the customerConsumerLog by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete CustomerConsumerLog : {}", id); customerConsumerLogRepository.delete(id); } }
true
406c24d6fda5ca2fedb3f131d2ee4018333e8208
Java
kkolyan/training
/spring-mini/src/main/java/net/kkolyan/spring/altimpl/xml/traverse/BeanConfigurator.java
UTF-8
219
1.757813
2
[]
no_license
package net.kkolyan.spring.altimpl.xml.traverse; import net.kkolyan.spring.altimpl.Bean; /** * @author nplekhanov */ public interface BeanConfigurator { void configureBean(Bean bean) throws Exception; }
true
546e3de5d64c6829e4a7755636070008698f877f
Java
RileyCampbell73/TDChallenge
/TDChallenge/app/src/main/java/rileycampbell/example/com/tdchallenge/MainActivity.java
UTF-8
16,819
2.296875
2
[]
no_license
package rileycampbell.example.com.tdchallenge; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; public class MainActivity extends Activity { final String API_KEY = "AIzaSyDyQ-faomCpZDP_TIMqJm0OOBfZm12vvlw"; final String Google_Places_API_Key = "AIzaSyAsb8XP5659RBOaQSYK5e71Ta2Z0CQ_5Q4"; ArrayList<Place> arrayList = new ArrayList<Place>(); double latitude = 0.0; double longitude = 0.0; GetPlaces asyncTask; int devtappcounter = 0; String dev_range = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Remove title bar this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); Spinner spinner = (Spinner)findViewById(R.id.spinnerRange); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { dev_range = parent.getItemAtPosition(position).toString(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } public void CheckInButtonClick(View view) { GPSService mGPSService = new GPSService(getBaseContext()); mGPSService.getLocation(); if (!mGPSService.isLocationAvailable) { // Here you can ask the user to try again, using return; for that Toast.makeText(getBaseContext(), "Your location is not available, please try again.", Toast.LENGTH_SHORT).show(); return; } else { // Getting location co-ordinates latitude = mGPSService.getLatitude(); longitude = mGPSService.getLongitude(); Toast.makeText(getBaseContext(), "Latitude:" + latitude + " | Longitude: " + longitude, Toast.LENGTH_LONG).show(); // make sure you close the gps after using it. Save user's battery power mGPSService.closeGPS(); //Grabs all the places near user, and places them into an arraylist asyncTask = new GetPlaces(); asyncTask.execute(); } } public void TdLogoTap(View view) { if (devtappcounter < 2){ devtappcounter ++; } else if (devtappcounter >= 2){ //Show Slider TextView text = (TextView)findViewById(R.id.textViewRange); text.setVisibility(View.VISIBLE); Spinner SR = (Spinner)findViewById(R.id.spinnerRange); SR.setVisibility(View.VISIBLE); } } private class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>>{ private ProgressDialog dialog; private String getJSON(String theUrl) { StringBuilder content = new StringBuilder(); try { //making the request to google URL url = new URL(theUrl); URLConnection urlConnection = url.openConnection(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream()), 8); String line; while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); }catch (Exception e) { e.printStackTrace(); Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show(); } return content.toString(); } @Override protected void onPreExecute() { super.onPreExecute(); arrayList = new ArrayList<Place>(); //before the call to google, open a dialog that shows a loading message dialog = new ProgressDialog(MainActivity.this); dialog.setCancelable(false); dialog.setMessage("Loading.."); dialog.isIndeterminate(); dialog.show(); } @Override protected void onPostExecute(final ArrayList<Place> result) { //after the call to google //get rid of the loading dialog if (dialog.isShowing()) { dialog.dismiss(); } if (result.size() == 1){//ONLY 1 RESULT // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage("Are you currently at " + result.get(0).getName() + "? \n\nIf you select no the app will attempt to find the store your currently at again.") .setTitle("Are You Here?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked yes button Intent i = new Intent(MainActivity.this ,CouponActivity.class); i.putExtra("Place",new Gson().toJson(result.get(0))); i.putExtra("DevOptions", devtappcounter == 2); startActivity(i); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog asyncTask = new GetPlaces(); asyncTask.execute(); } }); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); dialog.show(); } else if (result.size() > 1){//MORE THEN 1 RESULT //make a string array of the names of the places recieved String[] PlaceNames = new String[result.size()]; int counter = 0; //populate the string array for (Place s : result){ PlaceNames[counter] = s.getName(); counter ++; } // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 2. Chain together various setter methods to set the dialog characteristics builder.setTitle("Are you at any of these locations?"); builder.setPositiveButton("Yes", null); builder.setSingleChoiceItems(PlaceNames, -1, null); // 3. Get the AlertDialog from create() final AlertDialog d = builder.create(); //set on click listener d.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button b = d.getButton(AlertDialog.BUTTON_POSITIVE); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ListView lw = ((AlertDialog)d).getListView(); if (lw.getCheckedItemPosition() != -1){ String checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition()).toString(); Toast.makeText(getBaseContext(), checkedItem, Toast.LENGTH_SHORT).show(); //Dismiss once everything is OK. //LAUNCH NEW ACTIVITY WITH PLACE INFO Intent i = new Intent(MainActivity.this ,CouponActivity.class); //get the place based on the name of the place they picked for (Place p : result){ if (p.getName().equals(checkedItem)) //put the place object in the bundle as a JSON string i.putExtra("Place",new Gson().toJson(p)); } i.putExtra("DevOptions", devtappcounter == 2); //dismiss the dialog d.dismiss(); //launch the activity startActivity(i); } else{ // DO NOT CLOSE DIALOG Toast.makeText(getBaseContext(), "Please select an option.", Toast.LENGTH_SHORT).show(); } } }); } }); //show the dialog d.show(); } else{//NO RESULTS // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage("No store locations were found near your location. Would you like to search again?") .setTitle("Where are you?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked yes button asyncTask = new GetPlaces(); asyncTask.execute(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog dialog.cancel(); } }); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); dialog.show(); } } //this will call google and get places at the users current latlong @Override protected ArrayList<Place> doInBackground(Void... params){ //build the url to be sent to get results StringBuilder urlString = new StringBuilder( "https://maps.googleapis.com/maps/api/place/search/json?"); //may be able to limit this further. this is kinda overkill urlString.append("types=restaurant|cafe|bakery|bar|beauty_salon|bicycle_store|book_store|bowling_alley|clothing_store|convenience_store|" + "department_store|electronics_store|pet_store|shoe_store|shopping_mall|store|furniture_store|gas_station|grocery_or_supermarket|" + "hardware_store|home_goods_store|jewelry_store|liquor_store");//MAYBE REMOVE: Shopping Mall, Bar urlString.append("&location="); urlString.append(Double.toString(latitude)); urlString.append(","); urlString.append(Double.toString(longitude)); if (devtappcounter == 2){ //Toast.makeText(getBaseContext(), dev_range, Toast.LENGTH_LONG).show(); urlString.append("&radius=" + dev_range);//meters } urlString.append("&radius=25");//meters urlString.append("&sensor=false&key=" + Google_Places_API_Key); try { //sends the request String json = getJSON(urlString.toString()); System.out.println(json); JSONObject object = new JSONObject(json); JSONArray array = object.getJSONArray("results"); //takes the JSON array and puts into an array of Places for (int i = 0; i < array.length(); i++) { try { Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i)); Log.v("Places Services ", "" + place); arrayList.add(place); } catch (Exception e) { // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage("There was an error when attempting to get any places. Please try again later.") .setTitle("There was an Error."); builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked yes button asyncTask.cancel(true); } }); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); dialog.show(); } } } catch (JSONException ex) { Toast.makeText(getBaseContext(), ex.getMessage(), Toast.LENGTH_LONG).show(); // 1. Instantiate an AlertDialog.Builder with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 2. Chain together various setter methods to set the dialog characteristics builder.setMessage("There was an error when attempting to get any places. Please try again later.") .setTitle("There was an Error."); builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked yes button asyncTask.cancel(true); } }); // 3. Get the AlertDialog from create() AlertDialog dialog = builder.create(); dialog.show(); } return arrayList; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
46ec688f8f963d7221b0d609cd78c23acad8d778
Java
phanikanth-sayana/cucumber_v2
/cucumber_v2/src/test/java/featureFileSuites/LoginSuiteRunner.java
UTF-8
1,116
2.1875
2
[]
no_license
package featureFileSuites; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import cucumber.api.CucumberOptions; import cucumber.api.testng.CucumberFeatureWrapper; import cucumber.api.testng.TestNGCucumberRunner; @CucumberOptions( features="src//test//resources//features//login.feature", glue="stepdefinitions", format={"pretty", "html:target/cucumber"} ) public class LoginSuiteRunner { TestNGCucumberRunner tcr; @BeforeClass(alwaysRun=true) public void beforeClass() throws Exception { tcr = new TestNGCucumberRunner(this.getClass()); } @DataProvider public Object[][] features() { return tcr.provideFeatures(); } @AfterClass (alwaysRun=true) public void afterClass() { tcr.finish(); } @Test(dataProvider="features") public void feature(CucumberFeatureWrapper cucumberFeature){ tcr.runCucumber(cucumberFeature.getCucumberFeature()); } }
true
58afd10ac9615b43d7a1de215bf7805438b6dbe5
Java
Leherguargin/raptors
/raptorsRobotsApp/src/main/java/pl/raptors/raptorsRobotsApp/repository/type/ReviewTypeRepository.java
UTF-8
372
1.976563
2
[]
no_license
package pl.raptors.raptorsRobotsApp.repository.type; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import pl.raptors.raptorsRobotsApp.domain.type.ReviewType; @Repository public interface ReviewTypeRepository extends MongoRepository<ReviewType,String> { public ReviewType findByName(String name); }
true
1dbafa451fe8167a58cf9409834007be22171ddd
Java
lucienking/land
/src/main/java/com/jksb/land/web/bpm/TrackLogController.java
UTF-8
979
2.203125
2
[]
no_license
package com.jksb.land.web.bpm; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.jksb.land.entity.bpm.TrackLog; import com.jksb.land.service.bpm.TrackLogService; import com.jksb.land.web.BaseController; /** * 流程日志跟踪 controller * @author wangxj * */ @Controller @RequestMapping("/bpm/track") public class TrackLogController extends BaseController { @Autowired private TrackLogService trackLogService; @RequestMapping(method = RequestMethod.GET,value = "/trackDisplay") public String contractDetailInfo(Long id,String orderName,Model model){ List<TrackLog> tracks = trackLogService.getTrackLogByOrder(id,orderName); model.addAttribute("tracks",tracks); return "/bpm/trackDisplay"; } }
true
04980970c1c373b16cd112428ddf51df78e891e8
Java
EEIT10501/FinalProject
/FunWorkProject2019/src/main/java/init/tables/CompanyTableInit.java
UTF-8
2,259
2.34375
2
[]
no_license
package init.tables; import com.funwork.model.Company; import com.funwork.model.User; import init.util.SystemUtils2018; import java.io.BufferedReader; import java.io.FileReader; import java.sql.Blob; import java.sql.Clob; import java.util.logging.Logger; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class CompanyTableInit { Logger logger = Logger.getLogger("com.funwork"); private SessionFactory factory; private static final String UTF8_BOM = "\uFEFF"; public CompanyTableInit(SessionFactory factory) { this.factory = factory; } /** * Initialize Company table. */ public void initCompany() { Session session = factory.getCurrentSession(); Transaction tx = null; String line = ""; try (FileReader fr = new FileReader("data/Company.dat"); BufferedReader br = new BufferedReader(fr);) { tx = session.beginTransaction(); while ((line = br.readLine()) != null) { if (line.startsWith(UTF8_BOM)) { line = line.substring(1); } String[] token = line.split("\\|"); Company cb = new Company(); cb.setName(token[0]); cb.setAddress(token[2]); Blob licBlob = SystemUtils2018.fileToBlob(token[3].trim()); cb.setLicensure(licBlob); cb.setReviewStatus(token[4].trim()); cb.setTaxId(token[1]); cb.setNotificationTimes(Integer.parseInt(token[6])); Blob covBlob = SystemUtils2018.fileToBlob(token[8].trim()); cb.setCoverPic(covBlob); Blob logBlob = SystemUtils2018.fileToBlob(token[7].trim()); cb.setLogo(logBlob); Clob clob = SystemUtils2018.fileToClob(token[9]); cb.setDescription(clob); cb.setSiteUrl(token[10]); cb.setFileName(token[11]); User ub = session.get(User.class, Integer.parseInt(token[5].trim())); cb.setUser(ub); session.save(cb); } tx.commit(); logger.info("Company資料新增成功"); } catch (Exception e) { logger.warning("新建Company表格時發生例外: " + e.getMessage()); if (tx != null) { tx.rollback(); } } } }
true
f019103ab2dcea3314f0d13f1edf7dda4439029e
Java
LittleLin/Android-BootCamp-InstagramPhotoViewer
/src/com/yahoo/apps/instagramphotoviewer/models/InstagramPhoto.java
UTF-8
493
1.820313
2
[]
no_license
package com.yahoo.apps.instagramphotoviewer.models; import java.util.ArrayList; import java.util.List; public class InstagramPhoto { public String username; public String userProfileImageUrl; public String caption; public long postTimestamp; public String imageUrl; public int imageHeight; public int likesCount; public int commentsCount; public List<InstagramComment> comments; public InstagramPhoto() { this.comments = new ArrayList<InstagramComment>(); } }
true
31b15181ef486f54c24325907a525bae38f5bd33
Java
felipe-gonzaga/demo-spring-boot_v2
/src/main/java/br/gov/se/secc/demo/controller/v1/FuncionarioController.java
UTF-8
1,362
2.046875
2
[]
no_license
package br.gov.se.secc.demo.controller.v1; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.PositiveOrZero; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.br.CPF; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import br.gov.se.secc.demo.service.FuncionarioService; import br.gov.se.sefaz.util.result.EntidadeResult; @Validated @RestController @RequestMapping("v1/funcionario") public class FuncionarioController { @Autowired private FuncionarioService funcionarioService; @GetMapping("buscar") public ResponseEntity<EntidadeResult> buscar(@RequestParam(required = false) @CPF String cpf, @RequestParam(required = false) @Size(min = 3, max = 50) String nome, @RequestParam(required = false) @Min(1) @Max(999999999) Integer codDepto, @RequestParam(defaultValue = "0") @PositiveOrZero Integer pagina) { return funcionarioService.buscar(cpf, nome, codDepto, pagina); } }
true
7c1ef831cbfecf33b7a5952ec9c44644b483116e
Java
Deunitato/NUScs2030
/Lab2/Loader.java
UTF-8
1,994
2.90625
3
[]
no_license
import java.util.*; public class Loader{ private int time; private int num; //private Cruise c[]; private int count; boolean first; private Object o; ArrayList<Object> c = new ArrayList<Object>() ; private String ans; private Stats e = new Stats(); public Loader(int num){ //this.c = new Cruise[10]; //this.c= new ArrayList<Cruise>(); this.num = num; this.first = true; this.count =0; } public Object getPrev(){ return this.o; } public Loader(){ this.count =0; } public int getNum(){ return this.num; } public void setCruise(Object a){ c.add(a); this.o = a; this.count=this.count +1; } private int timeConvert(int a, int me){ int hr = (a/100)-(me/100); int min = (a%100)-(me %100); int total = hr *60 +min; return total; } //tells me if the next ship is ready public boolean loadReady(Object next){ if(first){ this.first = false; return true; //if the loader is empty; } else if(o ==null){ return true; } else{ //this.o =c.get(count-1); int Atime = ((Cruise)(this.o)).getTime(); int Btime = ((Cruise)next).getTime(); int timediff = timeConvert(Btime,Atime); if(o instanceof Bigcruise){ //System.out.println(timediff); return (timediff)>=60; } else if(o instanceof Cruise){ return (timediff)>=30; } else { //System.out.println("ok"); return false;} } // return false; } public String getList(){ return this.ans; } public String toString(){ // for(int i =0;i<2;i++){ // System.out.println(c[i]); // } String ans=""; String x = "Loader "+num +" serves:"; x = e.justifyLeft(33,x); for(int i = 0; i<count;i++){ //edit here if(i+1== count){ ans = ans + "| "+c.get(i)+" |\n";} else{ ans = ans + "| "+c.get(i) + " |\n"; } } this.ans = ans; String k = "| "+x+"|\n" + ans; return k; } }
true
bc6c361b2dd411e84fa85f6d18ec6476f2303efa
Java
Anupam1007/RandomProgrammingCodes
/TOPCODER/BridgeCrossing.java
UTF-8
886
3.25
3
[]
no_license
//SRM 146 DIV2 6 901 ponts got but 2nd day 2nd attempt import java.util.*; class BridgeCrossing { public static int minTime(int[] times) { int n=times.length; int ans=0; if (n==1) return times[0];//only one element Arrays.sort(times); int x1=times[0],x2=times[1]; while(n>3) //if 3 or less left, we will hardcode or improvise in other manner lets see how.. { int y1=times[n-1]; int y2=times[n-2]; if((2*(x2)+x1+y1)<(2*(x1)+y1+y2)) { ans+=(2*(x2)+x1+y1); n-=2; } else { ans+=2*x1+y1+y2; n-=2; } } if(n==3) { ans+=times[2]+x1+x2; } else if(n==2) ans= ans+times[1]; else ans=ans+times[0]; return ans; } public static void main(String args[]) { System.out.println(minTime(new int[]{ 10})); } } // { 1, 2, 5, 10 } //17 // { 1, 2, 3, 4, 5 } //16 // { 100 } //100 // { 1, 2, 3, 50, 99, 100 } //162
true
f9361f3303ac365593a34bcc470a78e69d16da0e
Java
jomolpgk332/logical-questionss
/companyquestions/src/company_questions/Sumuntill1.java
UTF-8
409
3.109375
3
[]
no_license
package company_questions; import java.util.Scanner; public class Sumuntill1 { public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("Enter the number"); int n=s.nextInt(); if(n==0) { System.out.println("sum "+n);} else if(n%9==0) { System.out.println("sum is "+9); } else { System.out.println("sum is"+n%9); } } }
true
37d392ade0e26f0153ce995685469adeeef78eb8
Java
LinuxEntrepreneur/buck
/test/com/facebook/buck/util/trace/ChromeTraceParserIntegrationTest.java
UTF-8
3,952
1.78125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util.trace; import static org.junit.Assert.assertEquals; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TemporaryPaths; import com.facebook.buck.testutil.integration.TestDataHelper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.gson.JsonElement; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import java.util.Set; public class ChromeTraceParserIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); private ProjectFilesystem projectFilesystem; private ChromeTraceParser parser; private ProjectWorkspace workspace; @Before public void setUp() throws IOException { projectFilesystem = new ProjectFilesystem(tmp.getRoot()); parser = new ChromeTraceParser(projectFilesystem); workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "chrome_trace_parser", tmp); workspace.setUp(); } @Test public void shouldNotCrashOnEmptyTrace() throws IOException { Set<ChromeTraceParser.ChromeTraceEventMatcher<?>> matchers = ImmutableSet.of( ChromeTraceParser.COMMAND); Map<ChromeTraceParser.ChromeTraceEventMatcher<?>, Object> results = parser.parse( Paths.get("empty_trace.json"), matchers); assertEquals(ImmutableMap.of(), results); } @Test public void canParseCommandFromTrace() throws IOException { Set<ChromeTraceParser.ChromeTraceEventMatcher<?>> matchers = ImmutableSet.of( ChromeTraceParser.COMMAND); Map<ChromeTraceParser.ChromeTraceEventMatcher<?>, Object> results = parser.parse( Paths.get("build_trace_with_command.json"), matchers); String expectedQuery = "buck query deps(fb4a, 1)"; assertEquals(ImmutableMap.of(ChromeTraceParser.COMMAND, expectedQuery), results); assertEquals(Optional.of(expectedQuery), ChromeTraceParser.getResultForMatcher( ChromeTraceParser.COMMAND, results)); } @Test public void canApplyMultipleMatchersToTrace() throws IOException { ChromeTraceParser.ChromeTraceEventMatcher<Integer> meaningOfLifeMatcher = (json, name) -> { if (!"meaningOfLife".equals(name)) { return Optional.empty(); } JsonElement argsEl = json.get("args"); if (argsEl == null || !argsEl.isJsonObject() || argsEl.getAsJsonObject().get("is") == null || !argsEl.getAsJsonObject().get("is").isJsonPrimitive()) { return Optional.empty(); } int value = argsEl.getAsJsonObject().get("is").getAsInt(); return Optional.of(value); }; Set<ChromeTraceParser.ChromeTraceEventMatcher<?>> matchers = ImmutableSet.of( ChromeTraceParser.COMMAND, meaningOfLifeMatcher); Map<ChromeTraceParser.ChromeTraceEventMatcher<?>, Object> results = parser.parse( Paths.get("build_trace_with_multiple_features.json"), matchers); assertEquals( ImmutableMap.of( ChromeTraceParser.COMMAND, "buck query deps(fb4a, 1)", meaningOfLifeMatcher, 42), results); } }
true
d716ec51934ac3db6a54caab7e0dde612167aa77
Java
santfirax/GoogleTranslateChallengeScreenPlay
/src/main/java/com/challenge/googletranslate/tasks/TranslateSentences.java
UTF-8
2,063
2.65625
3
[]
no_license
package com.challenge.googletranslate.tasks; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.Task; import net.serenitybdd.screenplay.actions.Click; import net.serenitybdd.screenplay.actions.Enter; import org.openqa.selenium.Keys; import static com.challenge.googletranslate.userinterface.GoogleTranslateWeb.*; /** * @author José Santiago Molano Perdomo, jose.molano@upb.edu.co * @version 0.0.1 * This class should be access by{ @link GoogleUserTasks#translate(String)} */ public class TranslateSentences implements Task { private final String sentenceToTranslate; private String fromLanguage; private String toLanguage; /** * Constructs a new Task so the actor can Translate sentences in Google Translate App * * @param sentenceToTranslate sentence to translate for the Actor * @since 0.0.1 */ protected TranslateSentences(String sentenceToTranslate) { this.sentenceToTranslate = sentenceToTranslate; } /** * @param fromLanguage, set the language to translate from the sentence * @return TranslateSentences current instance * @since 0.0.1 */ public TranslateSentences fromLanguage(String fromLanguage) { this.fromLanguage = fromLanguage; return this; } /** * @param toLanguage, set the language to translate to the sentence * @return TranslateSentences current instance * @since 0.0.1 */ public TranslateSentences toLanguage(String toLanguage) { this.toLanguage = toLanguage; return this; } @Override public <T extends Actor> void performAs(T actor) { actor.attemptsTo( Click.on(LIST_FROM_LANGUAGES_ON_GOOGLE_TRANSLATE), Enter.theValue(fromLanguage).into(SEARCH_FROM_LANGUAGE_INPUT).thenHit(Keys.ENTER), Click.on(LIST_TO_LANGUAGES_ON_GOOGLE_TRANSLATE), Enter.theValue(toLanguage).into(SEARCH_TO_LANGUAGE_INPUT).thenHit(Keys.ENTER), Enter.theValue(sentenceToTranslate).into(INPUT_TRANSLATE_FROM) ); } }
true
fe98c39e1032645071db526c49fdf2b27bfd7221
Java
cpeisert/Non-Dairy-Soy-Plugin
/src/net/venaglia/nondairy/soylang/elements/path/AttributePredicate.java
UTF-8
4,433
2.390625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010 - 2012 Ed Venaglia * * 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 net.venaglia.nondairy.soylang.elements.path; import com.intellij.psi.PsiElement; import net.venaglia.nondairy.soylang.elements.AttributeElement; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.regex.Pattern; /** * User: ed * Date: 1/28/12 * Time: 10:39 AM * * A predicate that matches soy tags based on their name/value attribute pairs. */ public class AttributePredicate extends AbstractElementPredicate { private final String name; private final Pattern matchValue; private AttributePredicate(@Nullable String name, @Nullable Pattern matchValue) { this.name = name; this.matchValue = matchValue; if (name == null && matchValue == null) { throw new IllegalArgumentException(); } } @Override public boolean test(PsiElement element) { if (element instanceof AttributeElement) { AttributeElement attr = (AttributeElement)element; if (name == null || name.equals(attr.getAttributeName())) { String value = attr.getAttributeValue(""); return this.matchValue == null || this.matchValue.matcher(value).matches(); } else { return false; } } return false; } @Override public String toString() { if (name == null) { return "[*=" + matchValue + "]"; } if (matchValue == null) { return "[" + name + "]"; } return "[" + name + "=" + matchValue + "]"; } /** * @param name The name of the attribute to look for. * @return an ElementPredicate that matches soy tag that has an attribute * with the specified name. */ public static AttributePredicate hasAttribute(@NotNull @NonNls String name) { return new AttributePredicate(name, null); } /** * @param value The value of the attribute to look for. * @return an ElementPredicate that matches soy tag that has an attribute * with the specified value. */ public static AttributePredicate hasValue(@NotNull @NonNls String value) { return new AttributePredicate(null, Pattern.compile(value, Pattern.LITERAL)); } /** * @param match The regexp that will match attribute values to look for. * @return an ElementPredicate that matches soy tag that has an attribute * with a value that matches the specified pattern. */ public static AttributePredicate hasValue(@NotNull @NonNls Pattern match) { return new AttributePredicate(null, match); } /** * @param name The name of the attribute to look for. * @param value The value of the attribute to look for. * @return an ElementPredicate that matches soy tag that has an attribute * with the specified name and value. */ public static AttributePredicate hasAttributeWithValue(@NotNull @NonNls String name, @NotNull @NonNls String value) { return new AttributePredicate(name, Pattern.compile(value, Pattern.LITERAL)); } /** * @param name The name of the attribute to look for. * @param match The regexp that will match attribute values to look for. * @return an ElementPredicate that matches soy tag that has an attribute * with the specified name and a value that matches the specified * pattern. */ public static AttributePredicate hasAttributeWithValue(@NotNull @NonNls String name, @NotNull @NonNls Pattern match) { return new AttributePredicate(name, match); } }
true
25da6aa92e9a28e28610c58d1dd6ae8634aa2ee8
Java
vivekpaypal/SmarterHiTest
/src/main/java/com/test/selenium/fwk/DriverFactory.java
UTF-8
1,258
2.59375
3
[]
no_license
package com.test.selenium.fwk; import java.io.File; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class DriverFactory { private DriverFactory() { } public static WebDriver getInstance(String browser){ String os =System.getProperty("os.name"); if(browser.equals("firefox")){ return new FirefoxDriver(); } if(browser.equals("chrome")){ if(os.equals("Mac OS X")){ System.setProperty("webdriver.chrome.driver", new File("./src/test/resources/drivers/mac/chromedriver").getAbsolutePath()); }else{ System.setProperty("webdriver.chrome.driver", new File("./src/test/resources/drivers/win/chromedriver.exe").getAbsolutePath()); } return new ChromeDriver(); } if(browser.equals("internetexplorer")){ File driver = new File("./src/main/resources/drivers/IEDriverServer.exe"); System.setProperty("webdriver.ie.driver", driver.getAbsolutePath()); return new InternetExplorerDriver(); } return new InternetExplorerDriver(); } }
true
d5f2fe3d4b09dc33304a9f78db635228f6cc707c
Java
krzywus/HotelDatabase
/src/java/Client.java
UTF-8
11,666
2.640625
3
[]
no_license
package java; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Client implements ActionListener{ private static final String username = "AppUser"; private static final String password = "application"; private static final String url = "jdbc:sqlserver://localhost:1433;databaseName=HotelDatabase"; private static Connection connection; private static Statement statement; private String loggedUserName; private MainMenu mainMenu; private LoginFrame loginFrame; private CreateAccountFrame createAccountFrame; private AdminFrame adminFrame; /*-------------------------------------------------------------------------------------------------------------------*/ public Client(){ mainMenu = new MainMenu(this); loginFrame = new LoginFrame(this); createAccountFrame = new CreateAccountFrame(this); } // end Client constructor @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand() == "Login"){ loginAttempt(); }else if(e.getActionCommand() == "Sign In"){ loginFrame.setVisible(false); createAccountFrame = new CreateAccountFrame(this); createAccountFrame.setVisible(true); }else if(e.getActionCommand() == "Check rooms availability"){ mainMenu.changeView(e.getActionCommand()); }else if(e.getActionCommand() == "Check Availability"){ checkAvailability(); }else if(e.getActionCommand() == "Make Reservation"){ mainMenu.changeView(e.getActionCommand()); }else if(e.getActionCommand() == "Submit Reservation"){ submitReservation(); }else if(e.getActionCommand() == "Check Usernames"){ checkUsernames(); }else if(e.getActionCommand() == "Remove Username"){ removeUsername(); }else if(e.getActionCommand() == "Back"){ mainMenu.changeView(e.getActionCommand()); }else if(e.getActionCommand() == "Register"){ registerAccount(); }else if(e.getActionCommand() == "Logout"){ mainMenu.setVisible(false); loginFrame = new LoginFrame(this); loginFrame.setVisible(true); }else if(e.getActionCommand() == "Exit"){ System.exit(0); } }// end actionPerformed private void loginAttempt() { String username = loginFrame.usernameField.getText(); loggedUserName = username; char[] password = loginFrame.passwordField.getPassword(); int accessLevel = 0; try { CallableStatement procedure = connection.prepareCall("{ CALL LoginAttempt(?,?,?,?) }"); procedure.setString(1, username); // IN parameter procedure.setString(2, String.valueOf(password) ); // IN parameter procedure.registerOutParameter(3, java.sql.Types.NVARCHAR); // OUT parameter procedure.registerOutParameter(4, java.sql.Types.INTEGER); // OUT parameter procedure.execute(); String responseMessage = procedure.getString(3); accessLevel = procedure.getInt(4); //System.out.println(responseMessage); //System.out.println(accessLevel); if(responseMessage.equals("Invalid username") || responseMessage.equals("Invalid password")){ loginFrame.infoLabel.setText(responseMessage); return; } } catch (SQLException e) { e.printStackTrace(); } if(accessLevel == 1){ loginFrame.setVisible(false); mainMenu = new MainMenu(this); mainMenu.setVisible(true); }else if(accessLevel == 3){ loginFrame.setVisible(false); adminFrame = new AdminFrame(this); adminFrame.setVisible(true); } }//end loginAttempt /** Method invoked when user tries to register new account for application. * On success new account i registered and login frame brought back. * On failure message is displayed in account frame. */ private void registerAccount() { String username = createAccountFrame.usernameField.getText(); String id_series = createAccountFrame.seriesField.getText(); char[] password = createAccountFrame.passwordField.getPassword(); if(username.equals("") || id_series.equals("") || String.valueOf(password).equals("") ){ createAccountFrame.infoLabel.setText("Some required field is empty."); return; } try { CallableStatement procedure = connection.prepareCall("{ CALL CreateAccount(?,?,?,?,?) }"); procedure.setString(1, username); // IN parameter procedure.setString(2, String.valueOf(password) ); // IN parameter procedure.setInt(3, 1); // IN parameter procedure.setString(4, String.valueOf(id_series) ); // IN parameter procedure.registerOutParameter(5, java.sql.Types.NVARCHAR); // OUT parameter procedure.execute(); String responseMessage = procedure.getString(5); System.out.println(responseMessage); if(responseMessage != null) if(responseMessage.equals("Username in use.")){ createAccountFrame.infoLabel.setText(responseMessage); return; } } catch (SQLException e) { e.printStackTrace(); } createAccountFrame.setVisible(false); loginFrame.setVisible(true); loginFrame.infoLabel.setText("Registration successful."); return; }// end registerAccount /** Method invoked when admin removes and username from database. */ private void removeUsername() { try { Statement statement = connection.createStatement(); String Sql = "DELETE FROM AppUser WHERE Login='" + adminFrame.usernameToDeletion.getText() + "'"; statement.executeUpdate(Sql); statement.close(); adminFrame.infoLabel.setText("User " + adminFrame.usernameToDeletion.getText()+ " was removed."); } catch (SQLException e) { JOptionPane.showMessageDialog(mainMenu, "Something went wrong. No such user."); e.printStackTrace(); } }//end removeUsername /** Method to invoke when admin wants to check usernames in the database. */ private void checkUsernames() { try { Statement statement = connection.createStatement(); String Sql = "SELECT Login FROM AppUser"; ResultSet rs = statement.executeQuery(Sql); String selectResultString = "Username:\n\n"; while (rs.next()) { selectResultString += rs.getString("Login") + "\n"; } JTextArea msg = new JTextArea(selectResultString); JScrollPane scrollPane = new JScrollPane(msg); JOptionPane.showMessageDialog(mainMenu, scrollPane); } catch (SQLException e) { JOptionPane.showMessageDialog(mainMenu, "Something went wrong. Sorry!"); e.printStackTrace(); } }// end checkUsernames /** Metoda wykonuje akcje podczas wysylania prosby o rezewacje. */ private void submitReservation() { String submit[] = mainMenu.getReservationSubmit(); //System.out.println(submit[0]); System.out.println(submit[1]); System.out.println(submit[2]); System.out.println(submit[3]); //System.out.println(checkDates(submit[2],submit[3])); if(!checkDates(submit[2],submit[3])){ JOptionPane.showMessageDialog(mainMenu, "Reservation not possible. Wrong date."); return; } try { //get clientID Statement statement = connection.createStatement(); String Sql = "SELECT TOP 1 c.ID FROM Client c INNER JOIN AppUser ON Account = c.ID " + "WHERE Login = '" + loggedUserName + "'"; ResultSet rs = statement.executeQuery(Sql); String clientID = ""; while (rs.next()) { clientID = rs.getString("ID"); } // znalezienie id pokoju switch(submit[0]){ case "Urnova Wroclaw": { char temp = submit[1].charAt(0); submit[1] = "10" + temp; break; } case "Urnova Warszawa": { char temp = submit[1].charAt(0); submit[1] = "20" + temp; break; } case "Urnova Katowice": { char temp = submit[1].charAt(0); submit[1] = "30" + temp; break; } } String roomID = ""; Sql = "SELECT TOP 1 r.ID FROM Room r WHERE RoomNumber = '" + submit[1] + "'"; rs = statement.executeQuery(Sql); while (rs.next()) { roomID = rs.getString("ID"); } Sql = "INSERT INTO Reservation(BegDate,EndDate,Paid, ClientID, RoomID) VALUES(" + "'"+submit[2]+"','" + submit[3] + "'," + "0" + "," + clientID + "," + roomID + ")"; statement.executeUpdate(Sql); rs.close(); statement.close(); JOptionPane.showMessageDialog(mainMenu, "Reservation made for selected date.\nHave a nice stay!"); } catch (SQLException e) { JOptionPane.showMessageDialog(mainMenu, "Reservation not possible. Room reserved in that time."); //e.printStackTrace(); } }// submitReservation /** Metoda wykonuje akcje podczas sprawdzania czy pokoj jest dostepny.*/ private void checkAvailability() { String submit[] = mainMenu.getCheckSubmit(); if(!checkDates(submit[2],submit[3])){ JOptionPane.showMessageDialog(mainMenu, "Wrong date."); return; } if(!checkPersonNumber(submit[1])){ JOptionPane.showMessageDialog(mainMenu, "Please insert a number into PersonNumber field."); return; } try { Statement statement = connection.createStatement(); String Sql = "SELECT r.RoomNumber, r.Price, t.MaxNumberOfPeople FROM Room r " + "INNER JOIN RoomType t ON t.ID = Type " + "WHERE Hotel = '" + submit[0] + "' AND MaxNumberOfPeople >= " + submit[1]; ResultSet rs = statement.executeQuery(Sql); String selectResultString = "Rooms Available:\n\n"; selectResultString += "RoomNumber\tPrice\tMaxPeople\n"; while (rs.next()) { selectResultString += rs.getString("RoomNumber") + "\t"; selectResultString += rs.getString("Price")+ "\t"; selectResultString += rs.getString("MaxNumberOfPeople")+ "\n"; } JTextArea msg = new JTextArea(selectResultString); JScrollPane scrollPane = new JScrollPane(msg); JOptionPane.showMessageDialog(mainMenu, scrollPane); } catch (SQLException e) { JOptionPane.showMessageDialog(mainMenu, "Something went wrong. Sorry!"); e.printStackTrace(); } }// check availability /** Metoda sprawdza czy data poczatkowa jest wczesniejsza niz koncowa. */ private boolean checkDates(String begDate, String endDate){ int begYear = Integer.parseInt(begDate.substring(0,4)); int endYear = Integer.parseInt(endDate.substring(0,4)); if( begYear > endYear) return false; if( begYear == endYear){ int begMonth = Integer.parseInt(begDate.substring(5,7)); int endMonth = Integer.parseInt(endDate.substring(5,7)); if( begMonth > endMonth ) return false; if( begMonth == endMonth ){ int begDay = Integer.parseInt(begDate.substring(8,10)); int endDay = Integer.parseInt(endDate.substring(8,10)); if( begDay >= endDay ) return false; }else return true; }else return true; return true; }// end checkDates /** Metoda sprawdza czy tekst wpisany do liczby osob jest liczba. */ private boolean checkPersonNumber(String personNumber){ try{ Integer.parseInt(personNumber); }catch(NumberFormatException e){ return false;} return true; }// end checkDates /** Method*/ private void connectDatabase(){ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); connection = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }//end connectDatabase /** Metoda glowna klienta. Pokazuje GUI.*/ public static void main(String[] args) { Client client = new Client(); client.connectDatabase(); client.loginFrame.setVisible(true); } // end main }
true
20656af3ff1d133a9a49d05cbcc47ace929558ad
Java
holon-platform/holon-core
/http/src/main/java/com/holonplatform/http/Cookie.java
UTF-8
2,356
2.359375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016-2017 Axioma srl. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.holonplatform.http; import java.io.Serializable; import com.holonplatform.http.internal.HttpCookie; /** * Represents a HTTP cookie * * @since 5.0.0 * * @see HttpRequest */ public interface Cookie extends Serializable { /** * Cookie default version according to RFC 2109 */ public static final int DEFAULT_VERSION = 1; /** * Get the name of the cookie * @return the cookie name */ String getName(); /** * Get the value of the cookie * @return the cookie value */ String getValue(); /** * Get the version of the cookie * @return the cookie version */ int getVersion(); /** * Get the domain of the cookie * @return the cookie domain */ String getDomain(); /** * Get the path of the cookie * @return the cookie path */ String getPath(); // Builder /** * Get a builder to create a {@link Cookie} instance. * @return Cookie builder */ public static Builder builder() { return new HttpCookie.CookieBuilder(); } /** * Cookie builder */ public interface Builder { /** * Set the cookie name * @param name Cookie name (not null) * @return this */ Builder name(String name); /** * Set the cookie value * @param value Cookie value * @return this */ Builder value(String value); /** * Set the cookie version * @param version Cookie version * @return this */ Builder version(int version); /** * Set the cookie domain * @param domain Cookie domain * @return this */ Builder domain(String domain); /** * Set the cookie path * @param path Cookie path * @return this */ Builder path(String path); /** * Build the cookie instance * @return Cookie instance */ Cookie build(); } }
true
aa7e43c787ebcaa6ea1ae193f5269d3c10352342
Java
lihuajun526/integral
/vipservice/src/main/java/com/operational/platform/vip/controller/SysController.java
UTF-8
1,694
1.96875
2
[]
no_license
package com.operational.platform.vip.controller; import com.operational.platform.vip.base.BaseController; import com.operational.platform.vip.constant.Constant; import com.operational.platform.vip.exception.RequestException; import com.operational.platform.vip.util.XHttpClient; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; /** * Created by lihuajun on 16-7-6. */ @Controller @RequestMapping("/sys") public class SysController extends BaseController { /** * 更新菜单 * * @return */ @RequestMapping("/menu/update") @ResponseBody public String updateMenu() throws RequestException { String menu = "{\"button\":[{\"type\":\"view\",\"name\":\"VIP会员\",\"url\":\"http://lihuajun526.xicp.net/goods/list\"},{\"type\":\"click\",\"name\":\"会员账号\",\"key\":\"getVip\"},{\"name\":\"黑眼圈365\",\"sub_button\":[{\"type\":\"view\",\"name\":\"投诉\",\"url\":\"http://www.soso.com/\"},{\"type\":\"view\",\"name\":\"建议\",\"url\":\"http://v.qq.com/\"}]}]}"; HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/menu/create"); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("access_token", Constant.ACCESS_TOKEN)); params.add(new BasicNameValuePair("body", menu)); XHttpClient.doRequest(httpPost); return ""; } }
true
f97a35f9c85b8abef40026436649c3c7475ffa33
Java
mrioan/phonebook-service
/src/main/java/com/centralway/assessment/phonebook/model/PasswordConverter.java
UTF-8
851
2.609375
3
[]
no_license
package com.centralway.assessment.phonebook.model; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * Encrypts passwords so that they are not stored in plain-text in the DB. */ @Converter public class PasswordConverter implements AttributeConverter<String, String> { private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); @Override public String convertToDatabaseColumn(String plainTextPassword) { return passwordEncoder.encode(plainTextPassword); } @Override public String convertToEntityAttribute(String encryptedPassword) { //we do not want to decode passwords :) return encryptedPassword; } }
true
4bfc35b5636d674b883640f4311ec28be2597b3d
Java
haski/ob1k
/ob1k-cache/src/test/java/com/outbrain/ob1k/cache/AbstractMemcachedClientTest.java
UTF-8
5,540
2.328125
2
[ "Apache-2.0" ]
permissive
package com.outbrain.ob1k.cache; import com.outbrain.ob1k.concurrent.ComposableFuture; import com.thimbleware.jmemcached.CacheImpl; import com.thimbleware.jmemcached.LocalCacheElement; import com.thimbleware.jmemcached.MemCacheDaemon; import com.thimbleware.jmemcached.storage.hash.ConcurrentLinkedHashMap; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.Serializable; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; /** * Base test class for memcached client wrappers * @author Eran Harel */ public abstract class AbstractMemcachedClientTest { public static final int MEMCACHED_PORT = 11311; private static MemCacheDaemon<LocalCacheElement> cacheDaemon; private TypedCache<String, Serializable> client; @BeforeClass public static void setupsBeforeClass_super() throws Exception { createCacheDaemon(); } private static void createCacheDaemon() { if (cacheDaemon != null) { return; } cacheDaemon = new MemCacheDaemon<>(); cacheDaemon.setCache(new CacheImpl(ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, 1000, 4194304))); cacheDaemon.setAddr(new InetSocketAddress(MEMCACHED_PORT)); cacheDaemon.setBinary(false); // NOTE: JMemcached seem to have binary protocol bugs... cacheDaemon.setVerbose(false); cacheDaemon.start(); } @AfterClass public static void teardownAfterClass() { cacheDaemon.stop(); } @Before public void setup() throws Exception { client = createCacheClient(); } protected abstract TypedCache<String, Serializable> createCacheClient() throws Exception; @Test public void testGetHit() throws IOException, ExecutionException, InterruptedException { final String key = "key1"; final String expectedValue = "value1"; final ComposableFuture<Serializable> res = client.setAsync(key, expectedValue) .flatMap(result -> client.getAsync(key)); final Serializable result = res.get(); Assert.assertEquals("unexpected result returned from getAsync()", expectedValue, result); } @Test public void testGetMiss() throws IOException, ExecutionException, InterruptedException { final ComposableFuture<Serializable> res = client.getAsync("keyMiss1"); final Serializable result = res.get(); Assert.assertNull("getAsync for unset key should have returned null", result); } @Test public void testGetBulkHit() throws ExecutionException, InterruptedException { final Map<String, String> expected = new HashMap<>(); for (int i=0; i< 100; i++) { expected.put("bulkKey" + i, "value" + i); } final ComposableFuture<Map<String, Serializable>> res = client.setBulkAsync(expected) .flatMap(result -> client.getBulkAsync(expected.keySet())); final Map<String, Serializable> getResults = res.get(); Assert.assertEquals("unexpected result returned from getBulkAsync()", expected, getResults); } @Test public void testGetBulkMiss() throws ExecutionException, InterruptedException { final Map<String, String> entries = new HashMap<>(); for (int i=0; i< 100; i++) { entries.put("bulkKeyMiss" + i, "value" + i); } final ComposableFuture<Map<String, Serializable>> res = client.getBulkAsync(entries.keySet()); final Map<String, Serializable> results = res.get(); Assert.assertTrue("getBulkAsync for unset keys should have returned empty map", results.isEmpty()); } @Test public void testDelete() throws IOException, ExecutionException, InterruptedException { final String key = "key1"; final String expectedValue = "value1"; final ComposableFuture<Boolean> res = client.setAsync(key, expectedValue) .flatMap(result -> client.deleteAsync(key)); final Boolean result = res.get(); Assert.assertTrue("unexpected result returned from getAsync()", result); Assert.assertNull("value was not deleted", client.getAsync(key).get()); } @Test public void testCas() throws ExecutionException, InterruptedException { final String counterKey = "counterKey"; client.setAsync(counterKey, 0).get(); final int iterations = 1000; final int threadCount = 2; final int successCount = runMultiThreadedCas(counterKey, iterations, threadCount); final int expectedSetCount = iterations * threadCount; Assert.assertEquals("Successful sets", expectedSetCount, successCount); Assert.assertEquals(expectedSetCount, client.getAsync(counterKey).get()); } private int runMultiThreadedCas(final String counterKey, final int iterations, final int threadCount) throws InterruptedException { final AtomicInteger successCount = new AtomicInteger(0); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(() -> { for (int t = 0; t < iterations; t++) { try { final Boolean res = client.setAsync(counterKey, (key, value) -> (Integer)value + 1, iterations).get(); if (res) { successCount.incrementAndGet(); } } catch (final Exception e) { throw new RuntimeException(e); } } }); threads[i].start(); } for (final Thread thread : threads) { thread.join(); } return successCount.get(); } }
true
4a8248dcdd7c7521a77dec24c0a540771fae984f
Java
kamilszelag86/where-is-my-stuff
/src/main/java/pl/coderslab/whereismystuff/item/entity/Item.java
UTF-8
1,442
2.25
2
[]
no_license
package pl.coderslab.whereismystuff.item.entity; import lombok.Data; import pl.coderslab.whereismystuff.category.entity.Category; import pl.coderslab.whereismystuff.location.entity.Location; import pl.coderslab.whereismystuff.team.entity.Team; import pl.coderslab.whereismystuff.user.entity.User; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.List; @Entity @Table(name = Item.TABLE_NAME) @Data public class Item { public static final String TABLE_NAME = "items"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank private String name; private String description; private String itemImage; private String receiptImage; @ManyToOne @NotNull private User user; @ManyToOne @NotNull private Team team; @ManyToOne private Location location; @ManyToMany(fetch = FetchType.EAGER) private List<Category> categories; public String getItemImagePath() { if (itemImage == null || itemImage.isBlank() || id == null) { return null; } return "/item-images/" + id + "/" + itemImage; } public String getReceiptImagePath() { if (receiptImage == null || receiptImage.isBlank() || id == null) { return null; } return "/item-images/" + id + "/" + receiptImage; } }
true
235b787ba47d8712e89f3ec1d90c46268fecef3b
Java
liveqmock/framework-1
/src/main/java/com/mopon/entity/logs/ErrorType.java
UTF-8
511
2.890625
3
[]
no_license
package com.mopon.entity.logs; public enum ErrorType { SYSTEM_ERROR(1), APPLICATION_ERROR(2), OPERATION_ERROR(3); private final int type; private ErrorType(int type) { this.type = type; } public int value() { return this.type; } public static ErrorType valueOf(int type) { for (ErrorType status : values()) { if (status.type == type) { return status; } } throw new IllegalArgumentException("No matching constant for [" + type + "]"); } }
true
57ed4891a1ab7e6fca10dd0da90df3e86c5f409c
Java
JuanMaynard/ProyectoPets
/ProyectoPets-con BD/src/main/java/com/cfs3/proyectopets/FichaCtr.java
UTF-8
6,945
2.78125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.cfs3.proyectopets; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; /** * * @author AleC */ public class FichaCtr { List<FichaDto> listFicha; //constructora public FichaCtr() { this.listFicha = new ArrayList<>(); } //metodos void agregarFicha(int idFicha,MascotaDto mascota, UsuarioDto usuario,String estado, String descripcion,Date fecha ) { //agrega una ficha FichaDto ficha = new FichaDto(idFicha,mascota,usuario,estado,descripcion,fecha); listFicha.add(ficha); } private boolean existeFicha(UsuarioDto usuario,MascotaDto mascota, String estado) { //controla si existe una ficha con una mascota y un estado determinado Iterator<FichaDto> listF = this.listFicha.iterator(); boolean corte = false; FichaDto ficha; while (!corte) { if (listF.hasNext()) { ficha = listF.next(); if (ficha.getUsuario().equals(usuario)&& ficha.getMascota().equals(mascota)&& ficha.getEstado().equals(estado)) { corte = true;//un ficha para un idMascota con un IdSuario y un estado existe. } } else { return false;//no existe una ficha con ese IdUsuario IdMascota y ese estado. } } return true; } public void eliminarFicha(int i){ //elimnina la ficha i Iterator<FichaDto> listF = this.listFicha.iterator(); boolean corte = false; FichaDto ficha; while (!corte) { if (listF.hasNext()) { ficha = listF.next(); if (ficha.getIdFicha()== i) { this.listFicha.remove(ficha); System.out.println("Se ha eliminado la ficha: "+ficha.getIdFicha()+" Mascota: "+ficha.getMascota().getIdMascota()); corte = true;//la ficha con idFicha existe y fue eliminada. } } else { System.out.println("La ficha "+i+" "+"no existe");//no existe una ficha con ese id corte=true; } } } public void eliminarFichasMasco(MascotaDto mascota){ //elimina todas las fichas relacionadas con una mascota Iterator<FichaDto> listF = this.listFicha.iterator(); boolean corte = false; FichaDto ficha; while (listF.hasNext()) { ficha = listF.next(); if (ficha.getMascota().equals(mascota)) { System.out.println("Se ha eliminado la ficha: "+ficha.getIdFicha()+"Mascota: "+ficha.getMascota().getIdMascota()); listF.remove(); } } } public void cambiarUsuario(UsuarioDto usuario, UsuarioDto nuevoU){ Iterator<FichaDto> listF = this.listFicha.iterator(); boolean corte = false; FichaDto ficha; while (!corte) { if (listF.hasNext()) { ficha = listF.next(); if (ficha.getUsuario().equals(nuevoU)){ ficha.setUsuario(nuevoU); corte = true;//un usuario con ese id existe y fue reemplazado } } else { System.out.println("El usuario "+nuevoU.getIdUsuario()+" "+"no existe en una ficha");//no existe un usuario con ese número de id corte=true; } } } public void modificarEstado(int idFicha, String estado){ Iterator<FichaDto> listF = this.listFicha.iterator(); boolean corte = false; FichaDto ficha; while (!corte) { if (listF.hasNext()) { ficha = listF.next(); if (ficha.getIdFicha()== idFicha) { ficha.setEstado(estado); corte = true;//la ficha con idFicha existe y su estado fue reemplazado. } } else { System.out.println("La ficha "+idFicha+" "+"no existe");//no existe una ficha con ese id corte=true; } } } public List<FichaDto> buscarMascotaenFicha(String estado,String descripcion){ //devuelve una lista de fichas de un determinado estado y descripción List<FichaDto> resultado=new ArrayList<>(); Iterator<FichaDto> listF = this.listFicha.iterator(); FichaDto ficha; while (listF.hasNext()) { ficha = listF.next(); if ((ficha.getDescripcion().contains(descripcion))&&(ficha.getEstado()==estado)) { resultado.add(ficha); } } return resultado; } public FichaDto buscarFicha(int idFicha){ //busca una ficha con IdFicha en base de datos Iterator<FichaDto> listF = this.listFicha.iterator(); boolean corte = false; FichaDto ficha=null; while (!corte) { if (listF.hasNext()) { ficha = listF.next(); if (ficha.getIdFicha()==idFicha) { corte = true;//ficha con ese Id encontrada! } } else { System.out.println("La ficha con ID"+idFicha+" "+"no existe");//no existe una ficha con ese ID corte=true; } } return ficha; } public void buscarMascotaEn(String estado1, String descripcion1) { List<FichaDto> lfi = new ArrayList<>(); lfi = this.buscarMascotaenFicha(estado1, descripcion1); //busca en ficha mascotas en un estado que cumpla una descripcion dada System.out.println(" "); System.out.println("Listado de Mascotas en estado: " + estado1 + " descripción: " + descripcion1); for (FichaDto i : lfi) { //genera una lista de mascotas con las mascotas que cumplen los criterios System.out.println("idMascota " + i.getMascota().getIdMascota() + " " + " Nombre: " + i.getMascota().getNombre() + " " + " Encontrado en: " + i.getDescripcion()); } } @Override public String toString(){ String fi="Fin listado Fichas"; System.out.println(""); System.out.println("Listado de fichas"); for(FichaDto f:listFicha){ System.out.println("ID ficha "+f.getIdFicha()+" ID Mascota "+f.getMascota().getIdMascota()+" ID usuario "+f.getUsuario().getIdUsuario()+" Estado "+f.getEstado()+" Descripción "+f.getDescripcion()+" Fecha "+f.getFecha()); } return fi; } }
true
227561221ace0b0365d9e4fd09ef0f32e1755ffe
Java
colbach/Bachelor-Projekt
/Versionen/1.1/Quellcode/src/projectrunner/callbacks/OnFinishCallback.java
UTF-8
116
1.976563
2
[]
no_license
package projectrunner.callbacks; public interface OnFinishCallback<T> { public void onFinish(T t); }
true
64c73b2aa6775268827f9a90b7465b8a5241f845
Java
juancarllos88/pizzaria-api
/src/main/java/br/com/pizzaria/core/api/presentation/dto/pizza/PizzaCompletaResponseTO.java
UTF-8
1,155
2.0625
2
[]
no_license
package br.com.pizzaria.core.api.presentation.dto.pizza; import java.io.Serializable; import java.util.List; import br.com.pizzaria.core.api.presentation.dto.adicional.AdicionalResponseTO; import br.com.pizzaria.core.api.presentation.dto.sabor.SaborResponseTO; import br.com.pizzaria.core.api.presentation.dto.tamanho.TamanhoResponseTO; public class PizzaCompletaResponseTO implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Long id; private TamanhoResponseTO tamanho; private SaborResponseTO sabor; private List<AdicionalResponseTO> adicionais; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public TamanhoResponseTO getTamanho() { return tamanho; } public void setTamanho(TamanhoResponseTO tamanho) { this.tamanho = tamanho; } public SaborResponseTO getSabor() { return sabor; } public void setSabor(SaborResponseTO sabor) { this.sabor = sabor; } public List<AdicionalResponseTO> getAdicionais() { return adicionais; } public void setAdicionais(List<AdicionalResponseTO> adicionais) { this.adicionais = adicionais; } }
true
47a260e972b48dc25c4b8aa8d73d6cad37e2f4ab
Java
CODavies/thanos
/src/Chapter2/CalculatingEnergy.java
UTF-8
707
3.875
4
[]
no_license
package Chapter2; import java.util.Scanner; public class CalculatingEnergy { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the amount of water in kilograms: "); double waterInKilograms = input.nextDouble(); System.out.println("Enter the initial temperature: "); double initialTemperature = input.nextDouble(); System.out.println("Enter the final temperature: "); double finialTemperature = input.nextDouble(); double energyNeeded = waterInKilograms * (finialTemperature - initialTemperature) * 4184; System.out.println("The energy needed is " + energyNeeded); } }
true
47db94da38b58915c390ae6e38a5f6d0ba2023f8
Java
mellobaby/Pattern
/Assignment 6/src/com/company/Builders/Manual.java
UTF-8
1,150
3.3125
3
[]
no_license
package com.company.Builders; public class Manual { private final materialType material; private final int walls; private final int doors; private final int windows; private final roofType roof; private final garageType garage; private final int rooms; public Manual(materialType material,int walls,int doors,int windows,roofType roof,garageType garage,int rooms) { this.material = material; this.walls = walls; this.doors = doors; this.windows = windows; this.roof = roof; this.garage = garage; this.rooms = rooms; } public String print() { String info = ""; info += "Type of material: " + material + "\n"; info += "Count of walls: " + walls + "\n"; info += "Count of doors: " + doors + "\n"; info += "Count of windows: " + windows + "\n"; info += "Type of roof: " + roof + "\n"; if (this.garage != null) { info += "Type of garage:"+ garage+ "\n"; } else { info += "No garage" + "\n"; } return info; } }
true
e2b5d2885d12a477de796f993beb004495a4861c
Java
EtienneBonvin/group-up
/app/src/main/java/ch/epfl/sweng/groupup/object/account/Member.java
UTF-8
3,447
2.71875
3
[]
no_license
package ch.epfl.sweng.groupup.object.account; import android.location.Location; import ch.epfl.sweng.groupup.lib.Optional; import ch.epfl.sweng.groupup.lib.database.DatabaseUser; /** * This class represents members of a group (which are User objects) */ public final class Member extends User { public static final String UNKNOWN_USER_ = "UNKNOWN_USER_"; public Member(String UUID, String displayName, String givenName, String familyName, String email, Location location) { super(displayName, givenName, familyName, email, UUID, location); } public Member(Optional<String> UUID, Optional<String> displayName, Optional<String> givenName, Optional<String> familyName, Optional<String> email, Optional<Location> location) { super(displayName, givenName, familyName, email, UUID, location); } /** * Converts a member to its database representation. * * @return - the member as a database user */ public DatabaseUser toDatabaseUser() { return new DatabaseUser(getGivenName(), getFamilyName(), getDisplayName(), getEmail(), getUUID(), getLocation()); } /** * Returns a new member with the given display name * * @param newDisplayName the new display name of the member * * @return a new member with the given display name */ public Member withDisplayName(String newDisplayName) { return new Member(UUID, Optional.from(newDisplayName), givenName, familyName, email, location); } /** * Returns a new member with the given email * * @param newEmail the new email of the member * * @return a new member with the given email */ public Member withEmail(String newEmail) { return new Member(UUID, displayName, givenName, familyName, Optional.from(newEmail), location); } /** * Returns a new member with the given first name * * @param newFirstName the new first name of the member * * @return a new member with the given first name */ public Member withFirstName(String newFirstName) { return new Member(UUID, displayName, Optional.from(newFirstName), familyName, email, location); } /** * Returns a new member with the given last name * * @param newLastName the new last name of the member * * @return a new member with the given last name */ public Member withLastName(String newLastName) { return new Member(UUID, displayName, givenName, Optional.from(newLastName), email, location); } /** * Returns a new member with the given location. * * @param location - the new location of the member * * @return - a new member with the given location */ public Member withLocation(Location location) { return new Member(UUID, displayName, givenName, familyName, email, Optional.from(location)); } /** * Returns a new member with the given UUID * * @param UUID the new UUID of the member * * @return a new member with the given UUID */ public Member withUUID(String UUID) { return new Member(Optional.from(UUID), displayName, givenName, familyName, email, location); } }
true
989e9163873119d007ed26a4d1eca3b399198c84
Java
devtrainer14/Java-Programs
/src/PKG_Collection/PriceComparator.java
UTF-8
440
2.8125
3
[]
no_license
package PKG_Collection; import java.util.Comparator; public class PriceComparator implements Comparator { Bean_Class b1,b2; @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub b1 = (Bean_Class) o1; b2 = (Bean_Class) o2; /* if(b1.price==b2.price) { return 0; }else if(b1.price>b2.price) { return 1; }else{ return-1; }*/ return b1.brand.compareTo(b2.brand); } }
true
0f93a63d93cca9424069b910f9d8d7ffbabe869e
Java
zhutonglmh/spring-cloud
/product-server-one/src/main/java/com/zt/demo/aopdemo/annotation/MyAnnotation.java
UTF-8
256
2
2
[]
no_license
package com.zt.demo.aopdemo.annotation; import java.lang.annotation.*; /** * @author zhutong * @date 2019/3/22 16:40 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation { String value(); }
true
2c6a801c7fb837cf8995fda2ffa9495d6d4e9c31
Java
zhongdj/net.madz.crmp.etl
/Madz.DatabaseMetaData/src/main/java/net/madz/db/metadata/jdbc/JdbcForeignKeyMetaData.java
UTF-8
1,758
2.421875
2
[]
no_license
package net.madz.db.metadata.jdbc; import java.util.List; import net.madz.db.metadata.jdbc.type.JdbcCascadeRule; import net.madz.db.metadata.jdbc.type.JdbcKeyDeferrability; /** * JDBC DatabaseMetaData about a foreign-key constraint */ public interface JdbcForeignKeyMetaData extends JdbcMetaData { /** The name of foreign key */ String getForeignKeyName(); /** * Foreign key index * * This is the index that is referring to another table * * @return SqlIndexMetaData or null if there is no foreign key index; MySQL * appears to always give us a value */ JdbcIndexMetaData getForeignKeyIndex(); JdbcTableMetaData getForeignKeyTable(); /** * primary key index * * This is the index that being referred to * * @return SqlIndexMetaData or null if there is no primary key index; MySQL * appears to always give us null */ JdbcIndexMetaData getPrimaryKeyIndex(); JdbcTableMetaData getPrimaryKeyTable(); /** * Defines what is to happen to this record when the referenced record is * deleted. */ JdbcCascadeRule getDeleteCascadeRule(); /** * Defines what is to happen to this record when the referenced record's * primary key is updated. */ JdbcCascadeRule getUpdateCascadeRule(); /** * Deferrability rule on this key */ JdbcKeyDeferrability getKeyDeferrability(); List<? extends Entry> getEntrySet(); /** * Number of relationships in the key */ Integer size(); public interface Entry { JdbcColumnMetaData getForeignKeyColumn(); JdbcColumnMetaData getPrimaryKeyColumn(); JdbcForeignKeyMetaData getKey(); } }
true