id
stringlengths
36
36
text
stringlengths
1
1.25M
2996baa2-f919-4152-a7e9-e7f8ed0c8740
public void putImageFile(String dir, String fileName, Date date);
249edbaf-7d8b-459d-ae0a-1a6011694dff
public ChatClient(String host, int port) { this.host= host; this.port = port; }
55bfe86b-bbb0-4568-b301-8a4e6b8f2b0c
public ChatClient(ServiceInfo si){ this.si = si; this.host = si.getHost(); this.port = si.getPort(); }
fee349e4-a984-4f01-9b68-10e52cb4226e
public ChatClient() { ; }
d65ea93c-1e7e-469e-9515-4ed4981c32eb
public void connect() { try { Debug.print("I'm client, start to connect to host:"+host); Socket skt = new Socket(host, port); Debug.print("Connected"); RSA rsa = new RSA(); rsa.setN(this.n); rsa.setE(this.e); InputStreamReader isr = new InputStreamReader(System.in); String publicKey = "("+this.e+" "+this.n+")"; System.out.println("Encoding with"+publicKey); while(true) { char c = (char)isr.read(); String toSend = ""; if(c == '\n'){ toSend = "\n"; }else{ toSend = rsa.getcypher(c+""); System.out.println(c+" is encoded to "+toSend); } for(int i = 0; i < toSend.length(); i++){ skt.getOutputStream().write(toSend.charAt(i)); } } } catch(ConnectException e){ System.err.println("starter haven't started listening yet!!!\n please give server input info and run again!!!"); }catch (IOException e) { System.err.println("Connect error"); e.printStackTrace(); } }
3ec1c12e-1c5d-4020-94d0-73fe558fab75
public void run(){ this.connect(); }
e8a4a5a8-14e7-428d-bc79-e40b2d562a00
public long getN() { return n; }
7e5896c1-16dd-47ba-9304-a81b16901ffc
public void setN(long n) { this.n = n; }
e0bab9d1-c40c-4238-bce0-a241fe76b7f3
public long getE() { return e; }
bd805744-7b63-45bb-8cfe-195f6919be67
public void setE(long e) { this.e = e; }
69f9de3b-d486-4acb-99c0-e95421887ec3
public Chat() { }
d4a55a0a-a04c-4826-9a8d-28300197c9f1
public void mode1(int port) { System.out.println("I'm starter!!"); Debug.print("mode1"); cs = new ChatServer(port); cs.setMode(ChatServer.SERVICE_MODE.STARTER); cs.start(); }
aebf0c30-41eb-465d-9c41-2e7d2cf5219b
public void mode2(int port, String host) { System.out.println("I'm follower!!"); cs = new ChatServer(); cs.setMode(ChatServer.SERVICE_MODE.FOLLOWER); cc = new ChatClient(host, port); cs.setClient(cc); cs.start(); }
b132b784-ae32-4c0b-a769-40eacd1be16e
public static void main(String[] args) { Chat ch = new Chat(); if(args.length == 1) { int port = Integer.parseInt(args[0]); ch.mode1(port); }else if(args.length == 2){ Debug.print(args[0]); Debug.print(args[1]); int port = Integer.parseInt(args[0]); String host = args[1]; ch.mode2(port, host); } else{ System.out.println("usage: java chat <port num> [<host name>]"); System.exit(0); } }
8707668f-8928-498e-891c-7b17000511ce
Key(long n, long e){ this.RSA_N = n; this.encryptKey = e; }
8f0d4ea2-ff9a-4e29-9d11-2255c5cc628e
public void setM(long m) { this.RSA_M = m; }
45bb4f81-e9c7-4d1c-a0b7-d48e53cd0b9f
public long getM() { return this.RSA_M; }
d01a1e11-624f-4534-b3cd-bfd5eab923b1
public void setDecryptKey(long d) { this.decryptKey = d; }
a91cb55b-fe76-4b60-accf-190d745bb20c
public long getEncryptKey() { return this.encryptKey; }
7ff2e3df-70e1-4560-bcc1-8107a1c56d3c
public void setEncryptKey(long encryptKey) { this.encryptKey = encryptKey; }
b5895567-c637-4cb2-ae9a-fe010a0a17cc
public long getDecryptKey() { return this.decryptKey; }
1af43377-ea7f-4170-8e88-7931c7703bf9
public static void print(String s) { if(DEBUG) { System.out.println("debug:"+s); } }
cdf532af-8611-4261-8de1-33ee3afcd476
ServiceInfo(){ ; }
4325f5e0-f123-4fcf-8c18-48badc07fb74
public synchronized String getHost() { if(host == null || host.length() == 0) { try { this.wait(); } catch (InterruptedException e) { Debug.print("wait exception!!"); // TODO Auto-generated catch block e.printStackTrace(); } } return host; }
6998f76d-25ac-4f7d-9077-19baa19eb678
public synchronized void setInfo(String host, int port) { this.port = port; this.host = host; this.notifyAll(); }
3ffae740-622d-4281-8aca-db8102454c21
public synchronized int getPort() { if(port == 0) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return port; }
82e69823-507d-4d5c-8794-ff71868e2193
public RSA(){ this(15, 20, false); }
58f6fa6b-f52b-4a16-9fc0-a35589c9c183
public RSA(long a, long b ,boolean fix){ if(fix){ this.a = a; this.b = b; }else{ this.a = prime(a); this.b = prime(b); } n = this.a * this.b; m = (this.a - 1)*(this.b - 1); e = coprime(m); d = modulo_inverse(e, m); Debug.print("n is "+n); Debug.print("m is "+m); Debug.print("e is "+e); Debug.print("d is "+d); }
e726a902-a3cf-4019-9e73-ef74529da490
public long crack(long input){ long root = (long) Math.sqrt((double)input); for(long i = 2; i < root; i++){ if(input % i == 0){ return input / i; } } return 0; }
e1faeb17-231d-452e-bbd3-5fb7c02c56ed
public String getcypher(String input){ StringBuffer output = new StringBuffer(); for(int i = 0; i < input.length(); i++){ output.append(endecrypt(input.charAt(i), e, n)); output.append(' '); } return output.toString(); }
4d14909d-2383-406c-8a7e-2471801683aa
public String decypher(String input){ String[] cyphers = input.split(" "); StringBuffer sb = new StringBuffer(); for(int i= 0; i < cyphers.length; i++){ long num = Long.parseLong(cyphers[i]); long temp = endecrypt(num, d, n); Debug.print("temp is:"+temp); char c = (char)temp; sb.append(c); } return sb.toString(); }
795e817c-173b-4487-9553-b34ae85118b1
public long prime(long n){ long start = 2; n--; while(n > 0){ start++; if(isPrime(start)){ n --; } } return start; }
b0bc07b7-593a-4bbc-95b9-9f3460593289
public static boolean isPrime(long a){ long root = (long) Math.sqrt((double)a); for(int i = 2; i <= root; i++){ if(a % i == 0){ return false; } } return true; }
1c616d24-9ec2-467f-8fb4-68be38ac96ca
public long endecrypt(long msg, long key, long c){ Debug.print(msg+" key:"+key+"c:"+c); return modulo(msg, key, c); }
3f600774-7e6e-4172-87df-8866db949b3d
public static long coprime(long x){ long a = Math.abs(new Random().nextLong()) % x; // a = Math.abs(a); if(a == 0){ a++; } while(GCD(a, x) != 1){ a = Math.abs(new Random().nextLong()) % x; // a = Math.abs(a); } return a; }
e202be46-1ef7-47e9-ac9b-73ee799e568c
public static long GCD(long a, long b){ if(b > a){ long c = b; b = a; a = c; } if(b == 0){ return a; }else{ return GCD(b, a % b); } }
41459d9a-7694-4168-899a-dc7b8aab9c58
public static long modulo(long a, long b, long c){ BigInteger biA = new BigInteger(a+""); BigInteger biB = new BigInteger(b+""); BigInteger biC = new BigInteger(c+""); return biA.modPow(biB, biC).longValue(); }
cdda3454-74ad-427d-8435-46bdadef3dcd
public static long modulo_inverse(long base, long m){ long orgM = m; long orgBase = base; long gcd = GCD(base, m); long x = 0; long lastX = 1; long y = 1; long lastY = 0; long quotient, tempM,tempX,tempY; while(m != 0){ quotient = base / m; tempM = m; m = base % m; base = tempM; tempX = x; x = lastX - (quotient * x); lastX = tempX; tempY = y; y = lastY - quotient * y; lastY = tempY; } if(gcd > 1){ return 0; }else{ Debug.print("lastX:"+lastX+"lastY"+lastY); if(lastX > 0){ return lastX % orgM; }else{ return orgM+(lastX % orgM); } } }
afb69c5a-d1c2-4a87-80b1-57189315d92f
public long getA() { return a; }
5e630d7b-e696-4f10-9fed-64d00f70b451
public void setA(long a) { this.a = a; }
94e9d72c-db0b-4e06-8631-dbe11e373049
public long getB() { return b; }
3bbc7faa-328c-4e22-bb83-9e42d52b4e01
public void setB(long b) { this.b = b; }
665fd4af-9520-445a-a217-22b795a9d710
public long getN() { return n; }
96e714e2-8bff-46df-bc54-3e703ef3b80a
public void setN(long n) { this.n = n; }
5c6cf616-a980-437a-9464-c2c6ca576623
public long getE() { return e; }
3ccf688e-32ea-4ca4-800f-31fbd2426ac0
public void setE(long e) { this.e = e; }
82730f74-1360-4697-8279-7a79ce954819
public long getM() { return m; }
076db8e7-0dae-47be-b9f3-4f20f624e24f
public void setM(long m) { this.m = m; }
da4879d2-b133-4867-8a45-28ec28a61d6a
public long getD() { return d; }
e36d3d19-3745-44bb-a161-fdb2d3b3a371
public void setD(long d) { this.d = d; }
300dcc21-be40-4bcf-8051-391e94409763
@Test public void test() { r = new Random(); RSA rsa = new RSA(); //System.out.println("P:" +p +"Q:"+ q); BruteForce bruteForce = new BruteForce(rsa.n,rsa.e); Key k = bruteForce.bruteForceCrack(); System.out.println("RSA-E:"+ rsa.e + "RSA_N:"+ rsa.n + "RSA_M" + rsa.m); System.out.println("D:" + k.getDecryptKey()); }
4268a429-876d-4a64-9827-41038e73d0dd
public ChatServer() { this(DEFAULT_PORT); }
83a84f2a-74d4-49b3-abaa-7bf4ef75b037
public ChatServer(int port) { this.port = port; }
71dc1dcf-4a3f-4e1c-a1e3-bde53e113003
public void launch() { try { //input own a and b, not fix mode System.out.println("Please input a to find ath prime"); Scanner s = new Scanner(System.in); int a = s.nextInt(); System.out.println("Please input b to find bth prime"); int b = s.nextInt(); if(a <=6){ a += 6; System.out.println("Input too small, auto shifted;"); } if(b <= 6){ b += 6; System.out.println("Input too small, auto shifted;"); } RSA geRSA = new RSA(a, b, false); System.out.println("Your public key n is "+geRSA.getN()+" and e is "+geRSA.getE()); // input other's n and e System.out.println("Please input the other people's n"); n = s.nextInt(); System.out.println("n is "+n); System.out.println("Please input e"); e = s.nextInt(); System.out.println("e is "+e); if(mode == ChatServer.SERVICE_MODE.FOLLOWER){ client.setN(n); client.setE(e); client.start(); } ServerSocket sskt = new ServerSocket(this.port); System.out.println("Listener start listen!"); Socket skt = sskt.accept(); //inputstream: InputStream its = skt.getInputStream(); System.out.println("Connection formed"); if(mode == ChatServer.SERVICE_MODE.STARTER){ String host = skt.getInetAddress().getHostAddress(); client = new ChatClient(host, DEFAULT_PORT); client.setN(n); client.setE(e); client.start(); } InputStreamReader isr = new InputStreamReader(its); BufferedReader br= new BufferedReader(isr); String line = br.readLine(); while(true) { String decypher = geRSA.decypher(line); if(decypher.equals(".bye") || decypher.equals("quit")){ break; } System.out.print("Received: "); System.out.println(geRSA.decypher(line)); line = br.readLine(); if(line == null){ System.out.println("Connection broken, auto quit"); break; } } System.out.println("Exit..."); client.interrupt(); System.exit(0); } catch (IOException e) { System.err.println("Server Socket error"); e.printStackTrace(); } }
8b99cb3e-15ba-47a2-9166-147a635268bd
public void run() { this.launch(); }
7c843f89-5a90-4736-a384-1e142674c2b0
public SERVICE_MODE getMode() { return mode; }
171f7b1b-8395-4947-ba38-cbaddc59c813
public void setMode(SERVICE_MODE mode) { this.mode = mode; }
a09a3605-bcdb-405a-8bb6-6f0040d87bef
public long getN() { return n; }
a1c80ed1-fd0a-418c-8e88-c034e362d319
public void setN(long n) { this.n = n; }
a2bd6f53-5da3-478e-ba63-70413a0717cd
public long getE() { return e; }
4adfbbca-77f1-4b64-97de-cfedd9aaaed9
public void setE(long e) { this.e = e; }
d3476201-0887-4b9a-8f86-c5b03754bf9e
public ChatClient getClient() { return client; }
640b60b6-0752-4da6-a353-68b34c96c8fe
public void setClient(ChatClient client) { this.client = client; }
177261b6-e5ed-4b1d-8d01-738b8214b0f9
BruteForce(long n, long e){ this.n = n; this.e = e; }
83447019-3f9f-44e4-a6e7-08c35abf39a5
private boolean isPrime() { for(long i = 2; i < Math.sqrt(n);++i) { if(n%i == 0) return false; } return true; }
67d9a7ce-c670-4b9b-9fa1-52d826b549f8
public Key bruteForceCrack() { if(isPrime()) { return null; } else { crackedKey = new Key(this.n,this.e); factorizeN(); return crackedKey; } }
71e0008e-f406-45c7-acb1-490d905ad008
private void factorizeN() { for(long i = 2; i < Math.sqrt(n);++i) { if(n%i == 0) { long factor1 = i; long factor2 = n/i; crackedKey.setM((factor1 - 1) * (factor2 - 1)); crackedKey.setDecryptKey(modulo_inverse(this.e,crackedKey.getM())); break; } } }
79c884c9-22e1-4193-9df2-b15669a519e8
private long GCD(long a, long b){ if(b > a){ long c = b; b = a; a = c; } if(b == 0){ return a; }else{ return GCD(b, a % b); } }
3fd7209f-6a5a-4e29-bd43-36fa80ecad4c
private long modulo_inverse(long base, long m){ long orgM = m; long orgBase = base; long gcd = GCD(base, m); long x = 0; long lastX = 1; long y = 1; long lastY = 0; long quotient, tempM,tempX,tempY; while(m != 0){ quotient = base / m; tempM = m; m = base % m; base = tempM; tempX = x; x = lastX - (quotient * x); lastX = tempX; tempY = y; y = lastY - quotient * y; lastY = tempY; } if(gcd > 1){ return 0; }else{ Debug.print("lastX:"+lastX+"lastY"+lastY); if(lastX > 0){ return lastX % orgM; }else{ return orgM+(lastX % orgM); } } }
7f973358-9aba-4315-a373-9981b3e194b1
public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Please enter the public key number(n):"); long input_n = sc.nextLong(); System.out.println(); System.out.print("Please enter the public key value(e):"); long input_e = sc.nextLong(); System.out.println(); BruteForce bf = new BruteForce(input_n,input_e); Key k = bf.bruteForceCrack(); if(k == null) { System.out.println("The input key pair in not factorizable"); } else { System.out.println("The private key(d,m) pair for the input is ("+ k.getDecryptKey() + "," + k.getM()+")"); } while(true){ System.out.println("please input encrypt number:"); long input = sc.nextLong(); int letter = (int)RSA.modulo(input, k.getDecryptKey(), input_n); System.out.println("decrypt result is:"+letter); System.out.println("letter is:"+(char)letter); } }
829b1fdc-2da1-440f-9292-7726a9d600f8
@Test public void testRSA() { fail("Not yet implemented"); }
dd4eb337-05a5-4b64-b851-ef7bd313dc44
@Test public void testRSAIntInt() { fail("Not yet implemented"); }
1e5c6870-1de3-4bdf-87dc-c31a70d27e18
@Test public void testGetcypher() { RSA rsa = new RSA(400, 200, false); Debug.print(""+rsa.a); Debug.print(""+rsa.b); Debug.print("e:"+rsa.e); Debug.print("n:"+rsa.n); // System.out.println(rsa.isPrime(4)); // System.out.println(rsa.prime(5)); // System.out.println(rsa.modulo_inverse(343, 557)); // System.out.println(rsa.d); // System.out.println(rsa.modulo(97, 731, 1288)); // System.out.println(rsa.decypher(rsa.getcypher("thi is bad"))); System.out.print(rsa.crack(3033191)); }
81cd6d2a-5cbb-49a4-900e-a44792f62dd6
@Test public void testPrime() { Scanner s = new Scanner(System.in) ; }
f90101b7-f10e-4034-975d-3d2035e637f2
@Test public void testIsPrime() { fail("Not yet implemented"); }
3d9db7f3-c9d0-4f70-841f-9a92bce3a11a
@Test public void testEndecrypt() { fail("Not yet implemented"); }
25bc9489-48e5-4f61-a483-f9216299b8d1
@Test public void testCoprime() { fail("Not yet implemented"); }
fc452489-6849-47fa-a930-d318b81d6f21
@Test public void testGCD() { fail("Not yet implemented"); }
a2e06513-ee33-4cde-bdb7-ccb079855ce0
@Test public void testModulo() { fail("Not yet implemented"); }
c70f1fff-ef4a-44f2-a04d-ad623e7fbc23
@Test public void testModulo_inverse() { fail("Not yet implemented"); }
68fdb823-bb56-4adc-a04a-bef06d1731ea
public static void main(String args[]) throws IOException { String[] queyString = new String[]{"mondego", "machine%20learning", "software%20engineering", "security", "student%20affairs", "Crista%20Lopes", "REST", "computer%20games", "information%20retrieval"}; String noOfResults = "8"; for(String query : queyString) { URL url = new URL( "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&" + "q="+ query +"%20site:ics.uci.edu&userip=USERS-IP-ADDRESS&rsz=" + noOfResults); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://www.ics.uci.edu/"); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while((line = reader.readLine()) != null) { builder.append(line); } JSONObject json = new JSONObject(builder.toString()); // System.out.println(json); JSONArray jsonArray = json.getJSONObject("responseData").getJSONArray("results"); System.out.println("=========================================="); System.out.println(); System.out.println("-------------------------------------"); System.out.println("Query String: " + query.replace("%20", " ")); System.out.println("-------------------------------------"); System.out.println(); for(int i=0; i<jsonArray.length(); i++) { JSONObject o = (JSONObject) jsonArray.get(i); System.out.println("Title: " + o.get("titleNoFormatting")); System.out.println("URL: " + o.get("url")); // System.out.println("Content: " + o.get("content")); System.out.println(); System.out.println(); } System.out.println("=========================================="); } }
cb9e2e4f-8915-4eda-ae65-4b0fd45b8579
public static void main(String[] args) { int noOfEntries = 5; // Before Optimization // Crista Lopes /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 100, 99, 98, 33, 5 });*/ // mondego /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 4, 3, 6 });*/ // software engineering /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 23, 12, 19, 21, 8 });*/ // security /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 2, 54, 58, 21, 30 });*/ // Machine learning /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 56, 32, 62 });*/ // information retrieval /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 1, 2, 4, 10, 5 });*/ // student affairs /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 100, 99, 98, 97, 96 });*/ // graduate courses /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 92, 96, 100, 90, 50 });*/ // computer games /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 100, 99, 98, 97, 96 });*/ // rest /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] {99, 100, 73, 20, 22 });*/ // --------------------------------------------------- // After Optimization // Crista Lopes /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 5, 4, 3, 1, 8 });*/ // mondego /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 2, 1, 3, 6, 8 });*/ // software engineering /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 23, 12, 19, 21, 8 });*/ // security /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 2, 54, 58, 21, 30 });*/ // Machine learning List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 56, 32, 62 }); // information retrieval /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 1, 2, 4, 10, 5 });*/ // student affairs /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 3, 2, 37, 10, 8 });*/ // graduate courses /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 3, 7, 8, 10, 12 });*/ // computer games /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 3, 1, 77, 16, 37 });*/ // rest /*List<Integer> googleOrder = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> luceneOrder = Arrays.asList(new Integer[] { 6, 100, 48, 50, 2 });*/ double ndcgValue = evaluateNDCG(luceneOrder, googleOrder, noOfEntries); System.out.println(1/ndcgValue); }
c13dcdec-82d8-4b93-ab28-9c636e4a3b38
public static double evaluateNDCG(List<Integer> urls, List<Integer> googleOrder, int noOfEntries) { double luceneUrlDCG = computeDCG(urls, googleOrder, noOfEntries); double idealDCG = computeDCG(googleOrder, googleOrder, noOfEntries); double normalized = luceneUrlDCG / idealDCG; return normalized; }
188ae96c-b756-49ee-af5e-2e0675e6e6fd
private static double computeDCG(List<Integer> urls, List<Integer> googleOrder, int noOfEntries) { double gain = 0; double logTwo = Math.log(2); int rank = 0; for (int i = 0; i < noOfEntries; i++) { Integer item = googleOrder.get(i); Integer val = urls.get(item-1); rank++; if(rank < 2) { gain += val; } else { gain += val * logTwo / Math.log(rank); } } return gain; }
82fe1c17-ee2c-4808-9093-8b61ef2446c4
IRIndexer(String indexDir) throws IOException { FSDirectory dir = FSDirectory.open(new File(indexDir)); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer); writer = new IndexWriter(dir, config); }
f4973759-2a42-4b1d-b064-b86c9ff6114c
public static void main(String[] args) throws IOException { // Reading the Stop Words String swLine = null; File swFile = new File("src/ir/assignments/UtilFiles/StopWords"); BufferedReader swInputBR = new BufferedReader(new FileReader(swFile)); while (( swLine = swInputBR.readLine()) != null) { stopWords.add(swLine.trim()); } swInputBR.close(); System.out.println("Enter the path where the index will be created:"); String indexLocation = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); IRIndexer indexer = null; try { indexLocation = s; indexer = new IRIndexer(s); } catch (Exception ex) { System.out.println("Cannot create index..." + ex.getMessage()); System.exit(-1); } try { System.out.println("Enter the full path of the file to add into the index"); s = br.readLine(); //try to add file into the index indexer.indexFileOrDirectory(s); } catch (Exception e) { System.out.println("Error indexing " + s + " : " + e.getMessage()); } indexer.closeIndex(); }
fc511e79-d169-44cf-971b-3240a81b5d95
public void indexFileOrDirectory(String fileName) throws IOException, InterruptedException { int j=1; addFiles(new File(fileName)); int originalNumDocs = writer.numDocs(); for (File f : queue) { j=1; Document doc = new Document(); Scanner scanner = new Scanner(f); StringBuilder builder = new StringBuilder(); String docId = "", url = "", path = "", parentURL = ""; String title = "", h1 = "", h2 = "", h3 = ""; String bold = "", strong = "", em = "", anchorText = "", parsedData = ""; ArrayList<String> tempArrList = new ArrayList<String>(); while (scanner.hasNextLine()) { String currLine = scanner.nextLine(); if(j==1) { docId = currLine; j++; System.out.println("docId: " + currLine); } else if(j==2) { url = currLine; j++; System.out.println("URL: " + currLine); } else if(j==3) { path = currLine; j++; System.out.println("Path: " + currLine); } else if(j==4) { parentURL = currLine; j++; System.out.println("docParent URL: " + currLine); } else if(j==5) { title = currLine; j++; System.out.println("Title: " + currLine); } else if(j==6) { h1 = currLine; j++; System.out.println("h1: " + currLine); } else if(j==7) { h2 = currLine; j++; System.out.println("h2: " + currLine); } else if(j==8) { h3 = currLine; j++; System.out.println("h3: " + currLine); } else if(j==9) { bold = currLine; j++; System.out.println("Bold: " + currLine); } else if(j==10) { strong = currLine; j++; System.out.println("String: " + currLine); } else if(j==11) { em = currLine; j++; System.out.println("Em: " + currLine); } else if(j==12) { anchorText = currLine; j++; System.out.println("AnchorText: " + currLine); } else if(j==13) { parsedData = currLine; j++; tempArrList = Utilities.removeStopWords(Arrays.asList(parsedData), stopWords); for (String string : tempArrList) { builder.append(string + " "); } System.out.println("Parsed Data: " + currLine); } } // Adding the title to the index Field titleField = new TextField("title",title,Field.Store.YES); titleField.setBoost(9.1f); doc.add(titleField); Field h1Field = new TextField("h1",h1,Field.Store.YES); h1Field.setBoost(50f); doc.add(h1Field); Field h2Field = new TextField("h2",h2,Field.Store.YES); h2Field.setBoost(35f); doc.add(h2Field); Field h3Field = new TextField("h3",h3,Field.Store.YES); h3Field.setBoost(25f); doc.add(h3Field); Field boldField = new TextField("bold",bold,Field.Store.YES); boldField.setBoost(17f); doc.add(boldField); Field strongField = new TextField("strong",strong,Field.Store.YES); strongField.setBoost(17f); doc.add(strongField); Field emField = new TextField("em",em,Field.Store.YES); emField.setBoost(20f); doc.add(emField); Field anchorTxtField = new TextField("anchortxt",anchorText,Field.Store.YES); anchorTxtField.setBoost(25f); doc.add(anchorTxtField); Field parsedDataField = new TextField("parseddata",builder.toString(),Field.Store.YES); parsedDataField.setBoost(75f); doc.add(parsedDataField); doc.add(new StringField("filename",url,Field.Store.YES)); writer.addDocument(doc); System.out.println("Added: " + f); scanner.close(); } int newNumDocs = writer.numDocs(); System.out.println(""); System.out.println("************************"); System.out.println((newNumDocs - originalNumDocs) + " documents added."); System.out.println("************************"); queue.clear(); }
ebd744e0-926b-47d8-afa4-076d6417d614
public static int nthOccurrence(String str, char c, int n) { int pos = str.indexOf(c, 0); while (n-- > 0 && pos != -1) pos = str.indexOf(c, pos+1); return pos; }
3ed2b208-8958-4d8f-bbc1-065795bfb943
private void addFiles(File file) { if (!file.exists()) { System.out.println(file + " does not exist."); } if (file.isDirectory()) { for (File f : file.listFiles()) { addFiles(f); } } else { queue.add(file); } }
f80dde9b-19a1-46ff-825f-33db0810514b
public void closeIndex() throws IOException { writer.close(); }
61dcbc84-19c1-460a-bea7-7a4c6938dddb
public SearchResults() { jObject = new JSONObject(); }
0647d978-8b66-4aa2-a3a3-f39222a2ced8
public JSONObject getSearchJSONObject() { return jObject; }
aa4ae7af-b09c-4353-becb-1315272309e2
@SuppressWarnings("null") public static void main(String[] args) throws ParseException, CorruptIndexException, IOException { JSONArray jSearchObjectArray = new JSONArray(); JSONObject finaljSearchObject = new JSONObject(); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); String queryString = "crista lopes"; StringTokenizer st = new StringTokenizer(queryString); String token = null; int j = 1; BooleanQuery query = new BooleanQuery(); while(st.hasMoreTokens()) { token = st.nextToken(); TermQuery titleTerm = new TermQuery(new Term("title",token)); titleTerm.setBoost(80.0f); TermQuery contentsTerm = new TermQuery(new Term("parseddata",token)); contentsTerm.setBoost(190.0f); TermQuery anchorTerm = new TermQuery(new Term("anchortxt",token)); anchorTerm.setBoost(25.0f); TermQuery boldTerm = new TermQuery(new Term("bold",token)); boldTerm.setBoost(55.0f); TermQuery strongTerm = new TermQuery(new Term("strong",token)); strongTerm.setBoost(60.0f); TermQuery emTerm = new TermQuery(new Term("em",token)); emTerm.setBoost(65.0f); query.add(titleTerm, Occur.SHOULD); query.add(contentsTerm, Occur.SHOULD); query.add(anchorTerm, Occur.SHOULD); query.add(boldTerm, Occur.SHOULD); query.add(strongTerm, Occur.SHOULD); query.add(emTerm, Occur.SHOULD); ++j; } //Query query = new QueryParser(Version.LUCENE_40, "contents", analyzer).parse(queryString); int hitsPerPage = 100; File indexDirectory = new File("C:\\IR_Archieve\\index"); IndexReader reader = DirectoryReader.open(FSDirectory.open(indexDirectory)); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true); searcher.search(query, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; System.out.println("Found " + hits.length + " hits."); for(int i=0;i<hits.length;i++) { JSONObject jSearchObject = new JSONObject(); int docId = hits[i].doc; Document d = searcher.doc(docId); try { System.out.println((i + 1) + ". " + "\t" + d.get("filename") + "\t" + d.get("title") + "\t :: " + d.get("parseddata").substring(100, 150)); } catch(Exception e) {} jSearchObject.put("URL",d.get("filename")); jSearchObject.put("Title",d.get("title")); jSearchObject.put("Anchor",d.get("anchor")); jSearchObject.put("Contents",d.get("contents")); jSearchObjectArray.put(i,jSearchObject); } System.out.println(jSearchObjectArray.length()); finaljSearchObject.put("Results",jSearchObjectArray); System.out.println(finaljSearchObject.get("Results")); }
f3e6e892-0eba-4b35-8556-057f0c26a80b
public static void main(String[] args) throws Exception { //CrawlController controller = new CrawlController("/data/crawl/root"); crawl("http://www.ics.uci.edu/"); }
7d5dfd5b-a31e-441e-aca9-9baa911b3b14
public static void crawl(String seedURL) throws Exception { //CrawlController controller = new CrawlController("/data/crawl/root"); long startTime = System.currentTimeMillis(); String crawlStorageFolder = "C:\\IR\\"; int numberOfCrawlers = 8; CrawlConfig config = new CrawlConfig(); config.setCrawlStorageFolder(crawlStorageFolder); // * Instantiate the controller for this crawl. PageFetcher pageFetcher = new PageFetcher(config); RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); String userAgentString = "UCI IR Crawler 84568218_15289486"; config.setUserAgentString(userAgentString); config.setPolitenessDelay(300); // * You can set the maximum crawl depth here. The default value is -1 for // * unlimited depth config.setMaxDepthOfCrawling(-1); config.setConnectionTimeout(1000); // * You can set the maximum number of pages to crawl. The default value // * is -1 for unlimited number of pages config.setMaxPagesToFetch(-1); // * For each crawl, you need to add some seed urls. These are the first // * URLs that are fetched and then the crawler starts following links // * which are found in these pages // controller.addSeed("http://www.ics.uci.edu/~welling/"); // controller.addSeed("http://ics.uci.edu/~lopes/"); controller.addSeed(seedURL); // * Start the crawl. This is a blocking operation, meaning that your code // * will reach the line after this only when crawling is finished. controller.start(BasicCrawler.class, numberOfCrawlers); long endTime = System.currentTimeMillis(); System.out.println("Total Time: " + (endTime - startTime)); }
d0d80130-56fa-4ee4-baf5-1f7298fa7e4a
@Override public boolean shouldVisit(WebURL url) { String href = url.getURL().toLowerCase(); return (!FILTERS.matcher(href).matches() && href.contains(".ics.uci.edu")) && !href.startsWith("https") && !href.contains("calendar.ics.uci.edu") && !href.contains("http://archive.ics.uci.edu") && !href.contains("ftp.ics.uci.edu") && (!href.contains("http://djp3-pc2.ics.uci.edu/LUCICodeRepository") || !href.startsWith("http://djp3-pc2.ics.uci.edu/LUCICodeRepository")) && !href.contains("rss.ics.uci.edu") && !href.contains("feed=rss") && !href.contains(".css?") && !href.contains("http://testlab.ics.uci.edu/") && !href.contains("http://phoenix.ics.uci.edu") && !href.contains("networkdata.ics.uci.edu") && !href.contains("ics.uci.edu/~lopes/datasets") && !href.contains("http://mlearn.ics.uci.edu/MLRepository.html") && !href.contains("sourcerer.ics.uci.edu/") && !href.contains("http://www.ics.uci.edu/~eppstein/pix/") && !href.contains("http://www.ics.uci.edu/~xhx/project"); }
3593fabd-4821-4d8b-8cfb-53dde8451d88
@Override public void visit(Page page) { int docid = page.getWebURL().getDocid(); String url = page.getWebURL().getURL(); String domain = page.getWebURL().getDomain(); String path = page.getWebURL().getPath(); String subDomain = page.getWebURL().getSubDomain(); String parentUrl = page.getWebURL().getParentUrl(); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String text = htmlParseData.getText(); String html = htmlParseData.getHtml(); List<WebURL> links = htmlParseData.getOutgoingUrls(); // There is a unique file for each document containing the length. String fileName = docid + "_logger"; try { if(text.length() != 0) { String parsedData = htmlParseData.toString(); if(parsedData.trim().length() != 0 || !parsedData.equals(" +")) { System.out.println("============="); System.out.println("============="); System.out.println("Docid: " + docid); System.out.println("URL: " + url); System.out.println("Domain: '" + domain + "'"); System.out.println("Sub-domain: '" + subDomain + "'"); System.out.println("Path: '" + path + "'"); System.out.println("Parent page: " + parentUrl); System.out.println("Text length: " + text.length()); System.out.println("Html length: " + html.length()); System.out.println("Number of outgoing links: " + links.size()); // Getting the text within <title> ... </title> ArrayList<String> extracts = getTagContents(Jsoup.parse(html)); // title, h1, h2, h3, b, strong, em, a String title = extracts.get(0); String h1 = extracts.get(1); String h2 = extracts.get(2); String h3 = extracts.get(3); String bold = extracts.get(4); String strong = extracts.get(5); String em = extracts.get(6); String anchorText = extracts.get(7); // Extracting anchor tag texts // Formatting the crawled webpage's (data) contents parsedData = parseData(parsedData); writeSeperateFile(docid, url, path, parentUrl, title, h1, h2, h3, bold, strong, em, anchorText, parsedData, fileName); writeSingleFile(docid, url, path, parentUrl, title, h1, h2, h3, bold, strong, em, anchorText, parsedData); FileWriter fstream_answers = new FileWriter("urlnames", true); BufferedWriter out_answers = new BufferedWriter(fstream_answers); out_answers.write(url); out_answers.newLine(); out_answers.close(); } } } catch (IOException e) { e.printStackTrace(); } } }
41c35881-298b-4701-9b4c-0b5e39f5cb9b
public static String parseData(String data) { // This converts words of form HelloWorld to Hello World // Reference: http://stackoverflow.com/questions/4886091/insert-space-after-capital-letter data = data.replaceAll("(\\p{Ll})(\\p{Lu})(\\p{Ll})","$1 $2$3"); // Writing all the data in a single large file // Each line will correspond to one web page. data = data.replaceAll("(\\r|\\n)", " "); // Removing extra white spaces between characters with a single white space data = data.replaceAll(" +", " "); // Reference: http://stackoverflow.com/questions/7552253/how-to-remove-special-characters-from-an-string data = data.replaceAll("[^\\w\\s]",""); data = data.replaceAll("[^\\p{L}\\p{N}]"," "); data = data.trim(); data = data.toLowerCase(); // Removing extra white spaces between characters data = data.replaceAll(" +", " "); // Removing data of the form &nbsp; - anything that begins with & and ends with ; data = data.replaceAll("\\&.*?\\;", ""); return data; }
ac4953f2-0b3e-491d-bff5-1c53a88236f7
public static ArrayList<String> getTagContents(Document doc) { // title, h1, h2, h3, b, strong, em, a ArrayList<String> extracts = new ArrayList<String>(); // Extracting the title Element title = doc.select("title").first(); extracts.add((title==null)?"":title.text()); // Extracting h1 String h1String = ""; Elements h1List = doc.select("h1"); for (Element h1 : h1List) { h1String += h1.text() + " "; } extracts.add((h1String==null)?"":h1String); // Extracting h2 String h2String = ""; Elements h2List = doc.select("h2"); for (Element h2 : h2List) { h2String += h2.text() + " "; } extracts.add((h2String==null)?"":h2String); // Extracting h1 String h3String = ""; Elements h3List = doc.select("h3"); for (Element h3 : h3List) { h1String += h3.text() + " "; } extracts.add((h3String==null)?"":h3String); // Extracting b String bString = ""; Elements bList = doc.select("b"); for (Element b : bList) { bString += b.text() + " "; } extracts.add((bString==null)?"":bString); // Extracting strong String strongString = ""; Elements strongList = doc.select("strong"); for (Element strong : strongList) { strongString += strong.text() + " "; } extracts.add((strongString==null)?"":strongString); // Extracting em String emString = ""; Elements emList = doc.select("em"); for (Element em : emList) { emString += em.text() + " "; } extracts.add((emString==null)?"":emString); // Extracting a String aString = ""; Elements aList = doc.select("a"); for (Element a : aList) { emString += a.text() + " "; } extracts.add((aString==null)?"":aString); return extracts; }
70b6c96b-f784-4ad6-90b0-7a50a534ea1d
public static void writeSeperateFile(Integer docId, String url, String path, String parentUrl, String title, String h1, String h2, String h3, String bold, String strong, String em, String anchorText, String parsedData, String fileName) throws IOException { FileWriter fstream = new FileWriter(PATH_LOCATION+fileName); BufferedWriter out = new BufferedWriter(fstream); out.write(docId.toString()); out.newLine(); out.write(url); out.newLine(); out.write(path); out.newLine(); if(parentUrl != null) { out.write(parentUrl); out.newLine(); } out.write(title); out.newLine(); out.write(h1); out.newLine(); out.write(h2); out.newLine(); out.write(h3); out.newLine(); out.write(bold); out.newLine(); out.write(strong); out.newLine(); out.write(em); out.newLine(); out.write(anchorText); out.newLine(); out.write(parsedData); out.close(); }