id
stringlengths
36
36
text
stringlengths
1
1.25M
fad42d12-7d9e-4e97-909a-40ab41ac1817
public static void main(String[] args) throws SchedulerException { new NotifierDaemon().startDaemon(); }
ae0eeed3-4554-4228-bc47-53634e6fc023
@Override public String toString() { return "RequestResult [requestResultCode=" + requestResultCode + ", responseString=" + responseString + "]"; }
37c27b0e-a654-4531-87bc-864888f8f1f4
public RequestResult sendRequest(String IP, int port, int connectTimeout, int waitTimeout, String requestMsg, String refID) { RequestResult result = new RequestResult(); DataInputStream incomingStream = null; DataOutputStream outgoingStream = null; String replyMsg = ""; Socket clientsock = null; try { SocketAddress sockaddr = new InetSocketAddress(IP, port); clientsock = new Socket(); log.debug("[" + refID + "][send to server] Socket ID created"); int timeoutConnectMs = connectTimeout; int timeoutWaitMs = waitTimeout; clientsock.setSoTimeout(timeoutWaitMs); clientsock.connect(sockaddr, timeoutConnectMs); log.debug("[" + refID + "][send to server] Socket connected"); outgoingStream = new DataOutputStream(clientsock.getOutputStream()); requestMsg = requestMsg + "\r\r"; byte[] buf = requestMsg.getBytes(); outgoingStream.write(buf); Thread.sleep(10L); outgoingStream.flush(); log.debug("[" + refID + "][Request Msg] -> " + requestMsg); log.debug("[" + refID + "] Data Flushed"); log.debug("[" + refID + "][send to server] Buffer sent"); incomingStream = new DataInputStream(clientsock.getInputStream()); log.debug("[" + refID + "][send to server] Waiting reply"); long startTime = new Date().getTime(); long timeRunning = 0L; int token; while ((token = incomingStream.read()) != -1) { char ch = (char) token; replyMsg = replyMsg + (char) token; if (ch == '\n') { break; } timeRunning = new Date().getTime() - startTime; } log.debug("[" + refID + "][send to server] time running:" + timeRunning + " MSec"); log.debug("[" + refID + "][send to server] completed"); clientsock.close(); outgoingStream.close(); incomingStream.close(); result.requestResultCode = 0; result.responseString = replyMsg; log.debug("[" + refID + "][Response Msg] <- " + replyMsg); } catch (IOException ioExp) { log.error("[" + refID + "][send to server] Exception error:" + ioExp.getMessage()); result.requestResultCode = -2; result.responseString = ioExp.getMessage(); } catch (Exception ex) { log.error("[" + refID + "][send to server] Error: [" + ex.getMessage() + "]"); result.requestResultCode = -1; result.responseString = ex.getMessage(); } finally { try { closeSilently(clientsock); clientsock.close(); outgoingStream.close(); incomingStream.close(); } catch (Exception ex) { log.error("[" + refID + "][send to server] Error: [" + ex.getMessage() + "]"); } } return result; }
5f30e3ad-b78a-4ef4-9d5e-970b0ade3fcc
public void closeSilently(Socket s) { if (s != null) { try { s.close(); } catch (IOException e2) { log.error("Exception while closing socket: " + e2.toString()); } } }
b779661c-2b43-45a2-bace-d53630325d81
public static boolean isEmpty(String s) { return ((s == null) || (s.length() == 0)); }
ba4ef6d3-4f5c-4057-963f-4f5e69776f1e
public static boolean isBlank(String s) { return ((s == null) || (s.trim().length() == 0)); }
fc962a91-6d3f-4177-91c6-3a70bb5b21c0
public static String getUUID() { UUID uuid = java.util.UUID.randomUUID(); return uuid.toString(); }
27d464ea-341a-40eb-93b2-6efeda1caaa6
public PropertiesUtil(String fileName) { readProperties(fileName); }
93b99173-59cd-41cb-8743-15a7279df42b
private void readProperties(String fileName) { try { props = new Properties(); String path = PropertiesUtil.class.getClassLoader().getResource("").toURI().getPath(); // InputStream fis = getClass().getResourceAsStream(fileName); InputStream fis = new FileInputStream(new File(path + fileName)); props.load(fis); // uri = this.getClass().getResource("dbConfig.properties").toURI(); } catch (Exception e) { e.printStackTrace(); } }
94ba44f3-306f-4a21-bea3-ee4227fd8b4d
public String getProperty(String key) { return props.getProperty(key); }
3e3d5f76-3b5b-4077-9e0d-aa1f9be0a0bb
public Map<Object, Object> getAllProperty() { Map<Object, Object> map = new HashMap<Object, Object>(); Enumeration enu = props.propertyNames(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); String value = props.getProperty(key); map.put(key, value); } return map; }
0b6b1079-4bbe-409a-afdc-249ec6ffc038
public void printProperties() { props.list(System.out); }
d4e98cd4-d55c-4f1c-9950-3283aab68a18
public String getDbURL() { return props.getProperty("server.db.url"); }
2f1cfe50-f6b5-42b7-baef-633c1255e913
public String getDbUserName() { return props.getProperty("server.db.username"); }
2569922c-70d7-498b-b26b-a7b70d2d0a9e
public String getDbPassword() { return props.getProperty("server.db.password"); }
a73a7011-4c94-43b0-ad03-29e6b5cc5125
public int getDbMinPoolSize() { return Integer.valueOf(props.getProperty("server.db.minPoolSize")); }
de45b9d1-f673-40f3-8654-1a705f9de5c5
public int getDbMaxPoolSize() { return Integer.valueOf(props.getProperty("server.db.maxPoolSize")); }
831d0138-9641-43e1-8d79-3e7c8a53283b
public long getDbConnMinLiveTime() { return Integer.valueOf(props .getProperty("server.db.connLiveTimeMillis")); }
422105f1-767f-4a08-aaf8-3731027c62e1
public static String getMD5String(String s) { return getMD5String(s.getBytes()); }
e705b901-79b1-44ba-86fe-a44dd9777731
public static boolean checkPassword(String password, String md5PwdStr) { String s = getMD5String(password); return s.equals(md5PwdStr); }
c2d5a71f-2682-4887-98da-7c082e64a9c3
public static String getFileMD5String(File file) throws IOException { InputStream fis; fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int numRead = 0; while ((numRead = fis.read(buffer)) > 0) { messagedigest.update(buffer, 0, numRead); } fis.close(); return bufferToHex(messagedigest.digest()); }
4b5f3224-5f2d-4d96-9caa-bd64dd3ad16d
@Deprecated public static String getFileMD5String_old(File file) throws IOException { FileChannel ch = new FileInputStream(file).getChannel(); MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); messagedigest.update(byteBuffer); return bufferToHex(messagedigest.digest()); }
e929b177-7f71-431e-a8cc-192caaef5b65
public static String getMD5String(byte[] bytes) { messagedigest.update(bytes); return bufferToHex(messagedigest.digest()); }
0fbbcba7-1e1c-4ce7-90e5-8aae19fea582
private static String bufferToHex(byte bytes[]) { return bufferToHex(bytes, 0, bytes.length); }
592a745a-2105-40f2-82b1-fe2534b7b609
private static String bufferToHex(byte bytes[], int m, int n) { StringBuffer stringbuffer = new StringBuffer(2 * n); int k = m + n; for (int l = m; l < k; l++) { appendHexPair(bytes[l], stringbuffer); } return stringbuffer.toString(); }
bc2ecc58-e252-47d2-baea-75b4403b554b
private static void appendHexPair(byte bt, StringBuffer stringbuffer) { char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同 char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换 stringbuffer.append(c0); stringbuffer.append(c1); }
37c2548f-df8b-4516-95a5-8c00acdd6b0d
public static void main(String[] args) throws IOException { long begin = System.currentTimeMillis(); File file = new File("C:/12345.txt"); String md5 = getFileMD5String(file); // String md5 = getMD5String("a"); long end = System.currentTimeMillis(); System.out.println("md5:" + md5 + " time:" + ((end - begin) / 1000) + "s"); }
8e03ef46-35ac-49ce-bb3f-5e3aa1015bac
public static void logMsg(String msg) { Logger.getLogger("server.messages").info(msg); }
df491b39-f32d-4fc7-b94a-f844e6da0d37
public static void logServerErr(String msg) { Logger.getLogger("server.error").error(msg); }
c26fd7b6-4980-4ffa-a100-29f49c2123cd
public static void logServerErr(Throwable t) { Logger.getLogger("server.error").error(t.getMessage(), t); }
e9f86228-dcc2-4514-a2e3-6f1771ec259f
protected byte[] encrypt(RSAPublicKey publicKey, byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { if (publicKey != null) { // Cipher负责完成加密或解密工作,基于RSA Cipher cipher = Cipher.getInstance("RSA"); // 根据公钥,对Cipher对象进行初始化 cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] resultBytes = cipher.doFinal(srcBytes); return resultBytes; } return null; }
f6dd0602-91ed-4edd-9573-1f400861aac4
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] srcBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { if (privateKey != null) { // Cipher负责完成加密或解密工作,基于RSA Cipher cipher = Cipher.getInstance("RSA"); // 根据公钥,对Cipher对象进行初始化 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] resultBytes = cipher.doFinal(srcBytes); return resultBytes; } return null; }
165446ca-35d2-4889-8b26-792b0e103836
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { RSA rsa = new RSA(); String msg = "郭XX-精品相声"; // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); // 初始化密钥对生成器,密钥大小为1024位 keyPairGen.initialize(1024); // 生成一个密钥对,保存在keyPair中 KeyPair keyPair = keyPairGen.generateKeyPair(); // 得到私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 用公钥加密 byte[] srcBytes = msg.getBytes(); byte[] resultBytes = rsa.encrypt(publicKey, srcBytes); // 用私钥解密 byte[] decBytes = rsa.decrypt(privateKey, resultBytes); System.out.println("明文是:" + msg); System.out.println("加密后是:" + new String(resultBytes) + " Length: " + resultBytes.length); System.out.println("解密后是:" + new String(decBytes) + " Length: " + decBytes.length); }
f0a155c3-b646-4d03-b17f-595e6764417d
public static void main(String[] args) throws Exception { /* * 加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定 */ String cKey = "1l1l1lll11lll1l1"; // 需要加密的字串 String cSrc = "我多么不舍朋友爱的那么苦痛;只有点遗憾难过"; // 加密 long lStart = System.currentTimeMillis(); String enString = AES.Encrypt(cSrc, cKey); System.out.println("加密后的字串是:" + enString + " , Length: "+ enString.length()); long lUseTime = System.currentTimeMillis() - lStart; System.out.println("加密耗时:" + lUseTime + "毫秒"); // 解密 lStart = System.currentTimeMillis(); String DeString = AES.Decrypt(enString, cKey); System.out.println("解密后的字串是:" + DeString); lUseTime = System.currentTimeMillis() - lStart; System.out.println("解密耗时:" + lUseTime + "毫秒"); }
b0affae8-82bb-4e62-bd74-8b03eeec17fc
public static String Decrypt(String sSrc, String sKey) throws Exception { try { // 判断Key是否正确 if (sKey == null) { System.out.print("Key为空null"); return null; } // 判断Key是否为16位 if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] encrypted1 = hex2byte(sSrc); try { byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } }
06a85d79-0bf4-4fa2-90a1-9863f096097e
public static String Encrypt(String sSrc, String sKey) throws Exception { if (sKey == null) { System.out.print("Key为空null"); return null; } // 判断Key是否为16位 if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes()); return byte2hex(encrypted).toLowerCase(); }
63605b48-e833-4ec2-bd60-8a5327f514e9
public static byte[] hex2byte(String strhex) { if (strhex == null) { return null; } int l = strhex.length(); if (l % 2 == 1) { return null; } byte[] b = new byte[l / 2]; for (int i = 0; i != l / 2; i++) { b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16); } return b; }
1f5bd55e-67bd-4c75-9424-20122fb2ee21
public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) { hs = hs + "0" + stmp; } else { hs = hs + stmp; } } return hs.toUpperCase(); }
19a6f141-e78c-4789-914b-28407bb8895a
public DashboardServlet() { super(); }
63dc06b6-cbd6-4217-946a-9ddc40d279d8
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
6b3d065b-3bd8-4a65-b8b2-88573149e17f
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO 增加验证,验证msg是否符合消息格式 String message = request.getParameter("msg"); LoggerUtil.logMsg(message); String result = SongHandler.handler(message); response.getWriter().write(result); }
1db8f652-d151-48a8-b13b-a9f1c3c76469
public SecurityFilter() { // TODO Auto-generated constructor stub }
0c397f4a-aee4-468c-8fe9-29f553a928da
public void destroy() { // TODO Auto-generated method stub }
ca8f8cc9-2b2f-48f1-8346-17632c46e058
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here LoggerUtil.logMsg("------------SecurityFilter start----------------"); // pass the request along the filter chain chain.doFilter(request, response); }
f2060b51-b5fe-4e58-92ba-4b8794a80d92
public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub }
a6643f89-631d-4de5-a1c2-fa3992857231
public EncodingFilter() { // TODO Auto-generated constructor stub }
6ab8b0bc-861c-4501-ae25-5c7778909dab
public void destroy() { // TODO Auto-generated method stub }
c7233742-9189-4b4f-bc11-f5b31916ab37
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here request.setCharacterEncoding("UTF-8"); // pass the request along the filter chain chain.doFilter(request, response); }
bcb5e228-66e1-461b-86ed-ad4fc3b42d5e
public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub }
cd145913-f872-47ee-b7bf-0e8fa8039a21
public static String handler(String message) { String result = ""; String category; String param; String command; int code; String msg = message.trim(); if (StringUtils.isEmpty(msg)) { return result; } else { LoggerUtil.logMsg(" Message: " + message); } category = msg.substring(0, 1).toLowerCase(); command = msg.substring(0, 3); code = Integer.valueOf(msg.substring(1, 3)); param = msg.substring(3); switch (category) { case AUTH: result = AuthTask.execute(code, param); break; default: break; } return command + result; }
559db3b7-91c0-4f90-bb94-4ebdd4ed0b64
public static String execute(int code, String param) { switch (code) { case USER: updateUser(param); break; default: break; } return "{\"ret\":1}"; }
1adfe589-abaf-488b-8b69-e18c14c26b4f
private static void updateUser(String param) { AccountDao.replaceUser(param); }
79337b18-ecb3-4c0a-b551-2f386a45eb79
private DataSourceFactory() throws SQLException { dataSource = new DruidDataSource(); PropertiesUtil config = new PropertiesUtil("dbConfig.properties"); dataSource.setUrl(config.getDbURL()); dataSource.setUsername(config.getDbUserName()); dataSource.setPassword(config.getDbPassword()); dataSource.setTestWhileIdle(true); dataSource.setMinIdle(config.getDbMinPoolSize()); dataSource.setMaxActive(config.getDbMaxPoolSize()); dataSource.setTimeBetweenEvictionRunsMillis(config.getDbConnMinLiveTime()); dataSource.setFilters("druidLog,log4j"); dataSource.setRemoveAbandoned(true); dataSource.setRemoveAbandonedTimeout(60); dataSource.setLogAbandoned(true); //五分钟输出一次状态到日志中 // dataSource.setConnectionProperties("druid.timeBetweenLogStatsMillis=900000"); // dataSource.setConnectionProperties("druid.stat.loggerName=druidLog"); // dataSource.setConnectionProperties("druid.stat.mergeSql=true"); // be advice: validation query cant work in Oracle. dataSource.setValidationQuery("select 'song'"); dataSource.init(); }
47a7dea7-a3bb-4b01-859e-c32775c20c1b
public static DataSourceFactory initFactory() throws SQLException { if (null == factory) { factory = new DataSourceFactory(); } return factory; }
916f28d5-26bd-45bb-b4ce-2906577bfb58
public static DataSourceFactory getInstance() throws SQLException { if (null == factory) { factory = new DataSourceFactory(); } return factory; }
ff00e94f-e36b-450b-8b08-f0ad8013bd2d
public DruidPooledConnection getConn() throws SQLException { return dataSource.getConnection(); }
9e7384be-8189-4f75-a7ca-a93d818d9bf7
public int getActiveCount() { return dataSource.getActiveCount(); }
36e5a405-335b-4d69-815e-7a8d59153709
public String getUid() { return uid; }
871a0184-53a4-4ad6-bb9c-4a4a026b1afd
public void setUid(String uid) { this.uid = uid; }
3d200cfa-bbe1-4f65-a260-b592e4faccad
public int getAccountType() { return accountType; }
1e17d020-224e-4fa0-8757-fb1f967ac6f4
public void setAccountType(int accountType) { this.accountType = accountType; }
9b83c889-1782-40b4-af22-ff971fdda252
public int getDeviceType() { return deviceType; }
df49af54-255d-4b78-9abe-7e00217c243b
public void setDeviceType(int deviceType) { this.deviceType = deviceType; }
5dafe71f-9194-465b-8b27-896ca1db58c5
@Override public String toString() { return "Account [uid=" + uid + ", accountType=" + accountType + ", deviceType=" + deviceType + "]"; }
a74db394-6c15-4132-a42d-fe0da0fc9d57
public static String replaceUser(String msg) { JSONObject req = JSON.parseObject(msg); JSONObject result = new JSONObject(); PreparedStatement stmt = null; DruidPooledConnection conn = null; try { conn = DataSourceFactory.getInstance().getConn(); conn.setAutoCommit(false); stmt = conn .prepareStatement( "replace into account (uid, accountType, deviceType, lastOnlineTime) values (?,?,?,?)", Statement.RETURN_GENERATED_KEYS); stmt.setString(1, req.getString("uid")); stmt.setInt(2, req.getIntValue("accountType")); stmt.setInt(3, req.getIntValue("deviceType")); stmt.setTimestamp(4, new Timestamp(System.currentTimeMillis())); int r = stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); if (r == 1 && rs.next()) { result.put("sid", rs.getInt(1)); } rs.close(); conn.commit(); conn.setAutoCommit(true); } catch (Exception ex) { ex.printStackTrace(); LoggerUtil.logServerErr(ex); } finally { try { if (null != stmt) { stmt.close(); } if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } LoggerUtil.logMsg(result.toString()); return result.toString(); }
3f60fd96-952e-40f7-8cf9-8cfb83fd29a3
public Hello(){}
ef54972f-788d-48c5-9fda-d2289585aaa9
public void printHello(){ System.out.println(s); }
e8c502a6-2cac-4084-8abc-1ae44fb71673
public static int find(String target,String pattern){ if(isEmpty(target)||isEmpty(pattern)) return -1; if(target.length()<pattern.length()) return -1; patChars = build(pattern); //----------------------TEST CODE START------------------------- System.out.print("pattern chars:\n"); for(int i=0;i<patChars.length;i++){ System.out.print(patChars[i]+" "); } System.out.print("\n"); for(int i=0;i<patChars.length;i++){ System.out.print(getPosition(patChars[i])+" "); } System.out.print("\n"); //----------------------TEST CODE END------------------------- int[][] dfa =new int[patChars.length][pattern.length()]; int j=0; int x=0; for(int i=0;i<patChars.length;i++){ dfa[getPosition(pattern.charAt(i))][j] = 0; } for(j=0;j<pattern.length();++j){ for(int i=0;i<patChars.length;i++){ dfa[getPosition(pattern.charAt(i))][j] = dfa[getPosition(pattern.charAt(i))][x]; } dfa[getPosition(pattern.charAt(j))][j]=j+1; x=dfa[getPosition(pattern.charAt(j))][x]; } //----------------------TEST CODE START------------------------- System.out.print(" "); for(j=0;j<pattern.length();j++){ System.out.print(pattern.charAt(j) +" "); } System.out.print("\n"); for(int i=0;i<patChars.length;i++){ System.out.print(patChars[i]+" "); for(j=0;j<pattern.length();j++){ System.out.print(dfa[i][j]+" "); } System.out.print("\n"); } //----------------------TEST CODE END------------------------- int state = 0; for(int i=0;i<target.length();i++){ char ch = target.charAt(i); int p = getPosition(ch); if(p==-1) state = 0; else state = dfa[p][state]; System.out.print(ch+":"+state); System.out.print("\n"); if(state == pattern.length()) return i-state+1; } return -1; }
e0952a60-b7f3-4b5a-8020-c078d76b6b97
private static int getPosition(char ch){ int length = patChars.length; int start = 0; int end = length-1; int pos = (start+end)/2; while(start!=end){ if(ch>patChars[pos]){ start = pos+1; } else { end = pos; } pos = (start+end)/2; } if(patChars[pos]==ch)return pos; return -1; }
9eaa5d39-336a-413b-a04b-160b4040b9ef
private static char[] build(String pattern){ if(isEmpty(pattern))return null; char[] tmp = new char[pattern.length()]; int length=0; for(int i=0;i<pattern.length();i++){ if(insert(tmp,pattern.charAt(i),length)) length++; } char[] result = new char[length]; for(int i=0;i<length;i++){ result[i] = tmp[i]; } return result; }
006ec5e2-07a9-4871-8970-2218f2db598b
private static boolean insert(char[] tmp, char ch,int length) { if(length==0){ tmp[0] = ch; return true; } int start = 0; int end = length-1; int pos = (start+end)/2; while(start!=end){ if(ch>tmp[pos]){ start = pos+1; } else { end = pos; } pos = (start+end)/2; } if(tmp[pos]==ch)return false; if(ch>tmp[start]){ insertPos(tmp,ch,start+1); } else { insertPos(tmp,ch,start); } return true; }
e59a57ed-c348-4fdc-88e0-cbad55f3f852
private static void insertPos(char[] tmp,char ch,int pos){ int n=tmp.length; for(int i=n-1;i>pos;--i){ tmp[i] = tmp[i-1]; } tmp[pos]=ch; }
42c2422c-bfa0-4972-80e9-0888bf6b57bf
private static boolean isEmpty(String s){ if(s==null||s.length()==0){ return true; } return false; }
77722623-cde4-4dbb-83ef-50bbade457ba
public static int find(String target,String pattern){ if(isEmpty(target)||isEmpty(pattern)) return -1; if(target.length()<pattern.length()) return -1; patChars = build(pattern); right = new int[patChars.length]; for(int i=0;i<pattern.length();i++){ right[getPosition(pattern.charAt(i))]=i; } int N = target.length(); int M = pattern.length(); int skip=0; for(int i=0;i<=N-M;i+=skip){ skip=0; for(int j=M-1;j>=0;j--){ if(pattern.charAt(j)!=target.charAt(i+j)){ int p = getPosition(target.charAt(i+j)); if(p==-1)skip = j-p; else skip = j-right[p]; if(skip<1)skip=1; break; } } if(skip==0)return i; } return -1; }
7e53e2e4-7fa8-48f1-be0b-87a8ab27f546
private static int getPosition(char ch){ int length = patChars.length; int start = 0; int end = length-1; int pos = (start+end)/2; while(start!=end){ if(ch>patChars[pos]){ start = pos+1; } else { end = pos; } pos = (start+end)/2; } if(patChars[pos]==ch)return pos; return -1; }
3ace93cd-0ef9-45c0-a05f-4cd248c02122
private static char[] build(String pattern){ if(isEmpty(pattern))return null; char[] tmp = new char[pattern.length()]; int length=0; for(int i=0;i<pattern.length();i++){ if(insert(tmp,pattern.charAt(i),length)) length++; } char[] result = new char[length]; for(int i=0;i<length;i++){ result[i] = tmp[i]; } return result; }
769fc975-616b-4939-aedb-d9a10b5ba973
private static boolean insert(char[] tmp, char ch,int length) { if(length==0){ tmp[0] = ch; return true; } int start = 0; int end = length-1; int pos = (start+end)/2; while(start!=end){ if(ch>tmp[pos]){ start = pos+1; } else { end = pos; } pos = (start+end)/2; } if(tmp[pos]==ch)return false; if(ch>tmp[start]){ insertPos(tmp,ch,start+1); } else { insertPos(tmp,ch,start); } return true; }
4a902685-ab61-4b40-afe0-ebeec6d616a4
private static void insertPos(char[] tmp,char ch,int pos){ int n=tmp.length; for(int i=n-1;i>pos;--i){ tmp[i] = tmp[i-1]; } tmp[pos]=ch; }
a299cde9-052d-486b-be12-1d7fa226cb73
private static boolean isEmpty(String s){ if(s==null||s.length()==0){ return true; } return false; }
ae027c1b-30a1-4075-8dc0-5482f51cb78d
public static String[] sort(String[] a){ return sort(a,0,a.length,0); }
e364e6f9-3312-4b4e-bfb4-52927e8910ca
private static String[] sort(String[] a,int start,int end,int pos){ int N = end - start; if(N==0)return null; String[] aux = new String[N]; int[] count = new int[R+2]; int[] count_r = new int[R+2]; for(int i=start;i<end;i++){ count[charAt(a[i],pos)+2]++; count_r[charAt(a[i],pos)+2]++; } for(int r=0;r<R;r++){ count[r+1]+=count[r]; //count_r[r]=count[r]; } //count_r[R]=count[R]; for(int i=start;i<end;i++){ aux[count[charAt(a[i],pos)+1]]=a[i]; count[charAt(a[i],pos)+1]++; } for(int i=start;i<end;i++){ a[i]=aux[i-start]; } for(int r=2;r<R+2;r++){ if(count_r[r]==0)continue; int l = count_r[r]; char ch = (char)r; System.out.println(ch+":"+l); sort(a,start,start+l,pos+1); start+=l; } return a; }
56a13005-caa7-4b73-8b59-979731d07b0c
public static int charAt(String s ,int index){ try{ return s.charAt(index); } catch (IndexOutOfBoundsException e){ return -1; } }
c288bd87-6ad3-442f-8c26-499051c4438d
public static void main(String[] args){ Hello h = new Hello(); h.printHello(); char c = 0; System.out.println(c); String[] a = new String[]{"1qwsdf","opk222ju","jfiooo","opfeafewikj","effefaefsa","01213efae","a","456fawkgfp"}; System.out.println("before sort"); printArray(a); Quick3string.sort(a); System.out.println("after sort"); printArray(a); }
93542c3d-ff2f-4d53-a93c-3638102359f6
public static void printArray(String[] a){ int n = a.length; for(int i=0;i<n;i++){ System.out.println(a[i]); } }
f22a1b58-6cde-47df-9251-13ac4cb06f44
private static int charAt(String s,int d){ try{ int ret = (int)s.charAt(d); return ret; } catch(IndexOutOfBoundsException e){ return -1; } }
98329bcf-b711-4703-bdb5-0565566f6986
public static void sort(String[] a){ System.out.println("-------------------start sort----------------------"); sort(a,0,a.length-1,0); System.out.println("-------------------end sort----------------------"); }
d1830f8f-8ced-4ee9-a380-82f0f7d3a8e7
public static void sort(String[]a, int start,int end,int pos){ System.out.println("-------------------start----------------------"); System.out.println("start="+start); System.out.println("end="+end); printArray(a,start,end); if(start>=end)return; int ch = charAt(a[start],pos); int l = start; int r = end; int i = l+1; System.out.println("i="+i); System.out.println("r="+r); while(i<=r){ int v = charAt(a[i],pos); System.out.println("ch="+ch); System.out.println("v="+v); if(v<ch){ exch(a,i++,l++); } else if(v>ch){ exch(a,i,r--); } else { i++; } } System.out.println("-------------------finish----------------------"); sort(a,start,l-1,pos); if(ch>0) sort(a,l,r,pos+1); sort(a,r+1,end,pos); }
3e81d7ef-0d0d-4288-84c2-9c8fdf3c22ca
public static void exch(String a[],int i,int j){ if(a==null)return; if(a.length<i||a.length<j)return; System.out.println("exchange:"+a[i]+"<->"+a[j]); String tmp = a[i]; a[i]=a[j]; a[j]=tmp; }
0023eea2-13fc-4f28-9b9f-261981749aaa
public static void printArray(String[] a,int start,int end){ int n = a.length; for(int i=0;i<=end;i++){ System.out.println(a[i]); } }
891d186b-8ee8-4edc-86f0-453a84369adb
public static int find(String s, String p){ int result = -1; int M = p.length(); int[]next = new int[M]; for(int i=0;i<M;i++){ next[i] = PrefixSuffixMaxMatch(s.substring(0, i+1)); } int i; for(i=0;i<s.length();){ int j; for(j=0;j<M;){ if(p.charAt(j)==s.charAt(i)){ ++i;++j; } else if(j==0){ ++i; } else { j=next[j]; } } if(j==M) return i-M; } return result; }
59ac298a-8174-4d2b-96cb-6267cf4e9a8d
private static int PrefixSuffixMaxMatch(String s){ int n = s.length(); if(n<=1)return 0; String[] prefix = new String[n-1]; String[] suffix = new String[n-1]; for(int i=0;i<n-1;i++){ prefix[i] = s.substring(0,i+1); suffix[i] = s.substring(n-i-1); if(prefix[i].compareTo(suffix[i])==0){ return i+1; } } return 0; }
c47e3bc8-1bc2-46fd-8186-5353fd4ed653
public static String[] sort(String[] a,int W){ int N = a.length; int R = 256; String[] aux = new String[N]; for(int d = W-1;d>=0;d--){ int[] count = new int[R+1]; for(int i=0;i<N;i++){ count[a[i].charAt(d)+1]++; } for(int i=0;i<R;i++) count[i+1]+=count[i]; for(int i=0;i<N;i++) aux[count[a[i].charAt(d)]++]=a[i]; for(int i=0;i<N;i++) a[i]=aux[i]; } return aux; }
40f3dcbe-738d-4011-8f74-99a55cec10f3
public static void print(Object... args) { for (Object x: args) { System.out.print(x); } System.out.println(); }
ef39bc65-d448-4341-8d3f-b4a8116280c8
public static void main(String[] args) throws ParserException, IOException { if (args.length != 1) { print("Usage:"); print(" bestpl [file]"); } File file = new File(args[0]); Parser parser = new Parser(new Lexer(new FileReader(file))); Interpreter interpreter = new DefaultInterpreter(); SExpression sexpr; while ((sexpr = parser.parse()) != null) { interpreter.interpret(sexpr); } }
80b543fa-55c1-49b3-8cda-064521708bb7
public SExpression(String op, List<SExpression> subexprs) { this.op = op; this.subexprs = Collections.unmodifiableList(new ArrayList<>(subexprs)); }
3c3ffe13-468c-4c07-9724-af30875de95e
public String toString() { if (subexprs.size() > 0) { String s = op; for (SExpression sexpr: subexprs) { s += " " + sexpr.toString(); } return "(" + s + ")"; } else return op; }
2e6c8aca-c944-4ad9-adfc-d19857a6f3d1
public Parser(Lexer lexer) { this.lexer = lexer; }
4a79a5af-825e-427d-b934-0fa7ca327b1c
public SExpression parse() throws ParserException { switch (lexer.curr().t) { case SYNCON: { require('('); String op = lexer.curr().s; require(Lexer.Token.Type.IDENTIFIER); List<SExpression> ls = new ArrayList<SExpression>(); while (is('(') || is(Lexer.Token.Type.IDENTIFIER)) { ls.add(parse()); } require(')'); return new SExpression(op, ls); } case IDENTIFIER: { String op = lexer.curr().s; require(Lexer.Token.Type.IDENTIFIER); return new SExpression(op, Collections.<SExpression>emptyList()); } case EOF: return null; // null is totes okay default: throw new JavaException(); } }
f1dca933-938b-48a3-b019-de884ca2863e
private void require(char c) throws ParserException { if (!is(c)) { throw new ParserException(); } try { lexer.readtok(); } catch (IOException e) { throw new ParserException(); } }
2f4d746b-dc5f-4422-afe0-3f1404d0d9cc
private boolean is(char c) { return lexer.curr().t == Lexer.Token.Type.SYNCON && lexer.curr().s.equals(c + ""); }