hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
b194aad582d8be8e2d34d433272049e85f7ed438
13,589
package com.theteam.bpmn.engine.enode; import com.theteam.snodes.SNode; import com.theteam.snodes.STaskNode; import com.theteam.taskdata.STaskData; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONObject; import java.util.ArrayList; import java.util.UUID; import javax.observer.Subscription; import javax.observer.ValueChangedEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; //import javax.xml.namespace.QName; //import javax.xml.ws.Service; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.theteam.bpmn.engine.Elist; import com.theteam.bpmn.engine.Workflow; import com.theteam.bpmn.engine.io.EVariable; import com.theteam.bpmn.engine.scan.Scan; import com.theteam.bpmn.engine.ws.WS; public class EServiceTask extends ENode { private STaskNode sTask; private boolean in; private boolean out; Subscription taskSubscription; Subscription messageSubscription; String workflowName; String instanceId; String taskId; public EServiceTask(SNode sNode, Elist list) { this.sNode = sNode; this.list = list; } @Override public void run(Elist l, String id) { sTask = (STaskNode) sNode; System.out.println("\nService_task Node Running"); workflowName = l.sNodes.getName(); instanceId = id; taskId = sTask.getNId(); ArrayList<String> processes = Workflow.processesRun.get(instanceId); if(processes == null) { ArrayList<String> tempList = new ArrayList<>(); tempList.add(sNode.getNId()); Workflow.processesRun.put(instanceId, tempList); } else { processes.add(sNode.getNId()); } JsonObject jsonEle1 = new JsonObject(); jsonEle1.addProperty("workflowName", workflowName); jsonEle1.addProperty("instanceID", instanceId); JsonArray jArray = new JsonArray(); for (String var : Workflow.processesRun.get(instanceId)) { JsonObject jsonEle2 = new JsonObject(); jsonEle2.addProperty("processID", var); jArray.add(jsonEle2); } jsonEle1.add("processes", jArray); Workflow.workflowObserver.updateVal(jsonEle1.toString()); //String temp = ""; if(sTask.getInput() != null) { System.out.println("\nThis node has input"); System.out.println(sTask.getInput()); in = true; } else { System.out.println("\nThis node doesn't have input"); in = false; } if(sTask.getOutput() != null) { System.out.println("\nThis node has output\n"); out = true; } else { System.out.println("\nThis node doesn't have output\n"); out = false; } // // // // // Start /* if(sTask.getServiceType().equals("soap")) { System.out.println("Execute soap service to link http://localhost:8080/soap_server/ws?wsdl"); try { URL url = new URL("http://localhost:8080/soap_server/ws?wsdl"); //1st argument service URI, refer to wsdl document above //2nd argument is service name, refer to wsdl document above QName qname = new QName("http://ws.engine.bpmn.theteam.com/", "WSImplService"); Service service = Service.create(url, qname); WS hello = service.getPort(WS.class); if(sTask.getSoapFunc().equals("getHello")) { System.out.println("Execute function getHello"); temp = hello.getHello("the-team"); System.out.println(temp); } else if(sTask.getSoapFunc().equals("getResponseWithName")) { System.out.println("Execute function getHellogetResponseWithName"); temp = hello.getResponseWithName("the-team"); System.out.println(temp); } } catch(Exception e) { } } */ if(sTask.getTaskType().equals("APITask")) { System.out.println("\nExecute rest service to link " + sTask.getRestLink()); if(sTask.getServiceType().equals("get")) { try { // http://localhost:8080/RESTfulExample/json/product/get URL url = new URL(sTask.getRestLink()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String temp = ""; String output; // System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); temp += output; } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if(sTask.getServiceType().equals("post")) { try { String a = ""; CloseableHttpClient client = HttpClients.createDefault(); //HttpPost post = new HttpPost("https://postman-echo.com/post"); HttpPost post = new HttpPost(sTask.getRestLink()); EVariable e = list.getVariable(sTask.getInput()); Scan s = new Scan(e.getValue(), l); String j = s.getFinalString(); System.out.println("\n JJJJSONS"); //System.out.println(o.getValue()); System.out.println(j); JSONObject orgJson = new JSONObject(j); String so = e.getValue(); JsonObject payload = new JsonObject(); payload.addProperty("customer_id", UUID.randomUUID().toString()); payload.addProperty("name", so); payload.addProperty("phone_number", 0); payload.addProperty("email", "1234"); payload.addProperty("dateOfBirth", "1999-06-02"); payload.addProperty("gender", "1234"); payload.addProperty("loyality_points", 0); payload.addProperty("type", 0); payload.addProperty("company", "1234"); payload.addProperty("company_email", "1234"); payload.addProperty("is_lead", true); post.setEntity(new StringEntity(orgJson.toString())); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); CloseableHttpResponse response = client.execute(post); System.out.println(response.getStatusLine().getStatusCode()); BufferedReader br = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output; // System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { //System.out.println(output); a += output; } System.out.println(a); client.close(); } catch (Exception e) { e.printStackTrace(); } } for(ENode n : l.eNodes) { if(n.getSNode().getNId().equals(getSNode().getNextNode())) { n.run(l, instanceId); return; } } } else if(sTask.getTaskType().equals("userTask")) { JsonObject ob = new JsonObject(); ob.addProperty("type", "userTask"); ob.addProperty("workflowName", workflowName); ob.addProperty("instanceID", instanceId); ob.addProperty("taskID", sTask.getNId()); ob.addProperty("taskName", sTask.getTaskName()); JsonArray obArr = new JsonArray(); for (STaskData var : sTask.getTaskDData().getData()) { JsonObject ob1 = new JsonObject(); ob1.addProperty("name", var.getName()); ob1.addProperty("type", var.getVal()); obArr.add(ob1); } ob.add("taskParam", obArr); Workflow.businessTasks.add(ob); taskSubscription = Workflow.serverObserver.onChanged(e -> completeTask(e)); } else if(sTask.getTaskType().equals("externalTask")) { JsonObject ob = new JsonObject(); ob.addProperty("type", "externalTask"); ob.addProperty("workflowName", workflowName); ob.addProperty("instanceID", instanceId); ob.addProperty("taskID", sTask.getNId()); ob.addProperty("taskName", sTask.getTaskName()); JsonArray obArr = new JsonArray(); JsonObject ob1 = new JsonObject(); for (STaskData var : sTask.getTaskDData().getData()) { ob1.addProperty(var.getName(), var.getVal()); } obArr.add(ob1); ob.add("taskParam", obArr); Workflow.businessTasks.add(ob); taskSubscription = Workflow.serverObserver.onChanged(e -> completeTask(e)); } else if(sTask.getTaskType().equals("message")) { JsonObject ob1 = new JsonObject(); ob1.addProperty("message", sTask.getMessageOut()); ob1.addProperty("data", sTask.getMessageOut()); Workflow.messageObserver.updateVal(ob1.toString()); messageSubscription = Workflow.messageObserver.onChanged(e -> completeMessage(e)); } } public void completeTask(ValueChangedEvent<? extends String> e) { JSONObject orgJson = new JSONObject(e.value()); String workflowName = orgJson.getString("workflowName"); String instanceId = orgJson.getString("instanceID"); String taskId = orgJson.getString("taskID"); String type = orgJson.getString("type"); if( this.workflowName.equals(workflowName) && this.instanceId.equals(instanceId) && this.taskId.equals(taskId) ) { if(type.equals("externalTask")) { } else if(type.equals("userTask")) { } taskSubscription.unsubscribe(); if(sTask.getMessageOut() != null) { JsonObject ob1 = new JsonObject(); ob1.addProperty("message", sTask.getMessageOut()); ob1.addProperty("data", sTask.getMessageOut()); Workflow.messageObserver.updateVal(ob1.toString()); messageSubscription = Workflow.messageObserver.onChanged(e -> completeMessage(e)); } else { // add to variable output - continue tasks } } } public void completeMessage(ValueChangedEvent<? extends String> e) { JSONObject orgJson = new JSONObject(e.value()); String message = orgJson.getString("message"); String data = orgJson.getString("data"); if(message.equals(sTask.getMessageIn())) { if(sTask.getOutput() != null) { EVariable o = list.getVariable(sTask.getOutput()); o.setValue(data); } messageSubscription.unsubscribe(); for(ENode n : list.eNodes) { if(n.getSNode().getNId().equals(getSNode().getNextNode())) { n.run(list, instanceId); return; } } } } }
29.541304
107
0.513872
3b8bc18a4411d84e34e32439ed73da1fb4eeb8d2
3,652
// ============================================================================ // // Copyright (C) 2006-2016 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dq.dbms; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.talend.utils.ProductVersion; import orgomg.cwm.objectmodel.core.Expression; /** * created by xqliu on Aug 7, 2013 Detailled comment * */ public class VerticaDbmsLanguage extends DbmsLanguage { public VerticaDbmsLanguage() { super(DbmsLanguage.VERTICA); } public VerticaDbmsLanguage(String dbmsType) { super(dbmsType); } public VerticaDbmsLanguage(String dbmsType, ProductVersion dbVersion) { super(dbmsType, dbVersion); } /* * (non-Javadoc) * * @see org.talend.dq.dbms.DbmsLanguage#createStatement(java.sql.Connection) */ @Override public Statement createStatement(Connection connection) throws SQLException { return connection.createStatement(); } @Override public String regexLike(String element, String regex) { return surroundWithSpaces(getRegularExpressionFunction() + "(TO_CHAR(" + element + ") , " + regex + " )"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @Override public String regexNotLike(String element, String regex) { return surroundWithSpaces(this.not() + getRegularExpressionFunction() + "(TO_CHAR(" + element + ") , " + regex + " )"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /* * (non-Javadoc) * * @see org.talend.dq.dbms.DbmsLanguage#getRegularExpressionFunction() */ @Override public String getRegularExpressionFunction() { return "REGEXP_LIKE"; //$NON-NLS-1$ } /* * (non-Javadoc) * * @see org.talend.dq.dbms.DbmsLanguage#getRegularExpressionFunction() */ @Override public String extractRegularExpressionFunction(Expression expression, String regex) { return getRegularExpressionFunction(); } @Override protected String getPatternFinderFunction(String expression, String charsToReplace, String replacementChars) { assert charsToReplace != null && replacementChars != null && charsToReplace.length() == replacementChars.length(); return translateUsingPattern(expression, charsToReplace, replacementChars); } /* * (non-Javadoc) * * @see org.talend.dq.dbms.DbmsLanguage#getInvalidClauseBenFord(java.lang.String) */ @Override public String getInvalidClauseBenFord(String columnName) { return columnName + " is null or " + "not regexp_like(to_char(" + columnName + "),'^[[:digit:]]')";//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } /* * (non-Javadoc) * * @see org.talend.dq.dbms.DbmsLanguage#getColumnNameInQueryClause(java.lang.String) */ @Override public String castColumnNameToChar(String columnName) { return "to_char(" + columnName + ")"; //$NON-NLS-1$//$NON-NLS-2$ } /* * (non-Javadoc) * * @see org.talend.dq.dbms.DbmsLanguage#getRandomQuery(java.lang.String) */ @Override public String getRandomQuery(String query) { return query + orderBy() + "RANDOM() "; //$NON-NLS-1$ } }
31.482759
169
0.630613
bf4919ce220744c6fda82d40aebb6977a908a590
2,482
package com.microtracing.logagent.injectors; import com.microtracing.logagent.LogTraceConfig; import com.microtracing.logagent.MethodInjector; public class ExceptionInjector implements MethodInjector{ private final static String[][] methodVariables = new String[0][0]; private final static String methodProcessStart = ""; private final static String methodProcessReturn = ""; private final static String methodProcessException = " { \n" + " StackTraceElement[] _$trace = _$e.getStackTrace(); \n" + " StringBuffer _sb = new StringBuffer(); \n" + " _sb.append(\"PROCESS_EXCEPTION %1$s.%2$s\"); " + " for(int i=0; i<_$trace.length; i++){ \n" + " if(\"%1$s\".equals(_$trace[i].getClassName()) && \"%2$s\".equals(_$trace[i].getMethodName())){ \n" + " _sb.append(\"(\").append(_$trace[i].getFileName()).append(\":\").append(_$trace[i].getLineNumber());" + " if(i>0){ \n" + " _sb.append(\" root \").append(_$trace[0].getFileName()).append(\":\").append(_$trace[0].getLineNumber());" + " } \n" + " _sb.append(\") \"); \n" + " break; \n" + " } \n" + " } \n" + " _sb.append(_$e.toString()); \n" + " _$logger.warn(_sb.toString()); \n" + " throw _$e; \n" + " } \n"; private final static String methodProcessFinally = ""; private LogTraceConfig config; public ExceptionInjector(LogTraceConfig config){ this.config = config; } @Override public String[][] getMethodVariables(String className, String methodName){ return methodVariables; } @Override public String getMethodProcessStart(String className, String methodName){ return methodProcessStart; } @Override public String getMethodProcessReturn(String className, String methodName){ return methodProcessReturn; } @Override public String getMethodProcessException(String className, String methodName){ return String.format(methodProcessException, className, methodName); } @Override public String getMethodProcessFinally(String className, String methodName){ return methodProcessFinally; } @Override public boolean isNeedProcessInject(String className, String methodName){ return config.isEnableExceptionLog() && config.isNeedInject(className) ;//&& config.isNeedProcessInject(className, methodName); } public boolean isNeedInject(String className){ return config.isEnableExceptionLog() && config.isNeedInject(className); } }
34
129
0.67365
cb997d230bd4e5030658df7ff9dc9920d832229a
1,533
package TestObjects; import java.util.Arrays; public class AllArraysObject { int[] a; Integer[] b; float[] c; Float[] d; double[] e; Double[] f; long[] g; Long[] h; boolean[] k; Boolean[] j; byte[] l; Byte[] m; String[] n; NestedTestObject[] a1; public AllArraysObject(){ a = new int[]{1,2,3}; b = new Integer[]{1,2,3}; c = new float[]{1,2,3}; d = new Float[]{1f,2f,3f}; e = new double[]{1,2,3}; f = new Double[]{1d,2d,4d}; g = new long[]{1,2,3}; h = new Long[]{1L, 2L, 3L}; k = new boolean[]{true,false,true}; j = new Boolean[]{true,false,true}; l = new byte[]{1,2,3}; m = new Byte[]{1,2,3}; n = new String[]{"hi","bye","apple"}; a1 = new NestedTestObject[]{new NestedTestObject(),new NestedTestObject(),new NestedTestObject()}; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AllArraysObject)) return false; AllArraysObject that = (AllArraysObject) o; return Arrays.equals(a, that.a) && Arrays.equals(b, that.b) && Arrays.equals(c, that.c) && Arrays.equals(d, that.d) && Arrays.equals(e, that.e) && Arrays.equals(f, that.f) && Arrays.equals(g, that.g) && Arrays.equals(h, that.h) && Arrays.equals(k, that.k) && Arrays.equals(j, that.j) && Arrays.equals(l, that.l) && Arrays.equals(m, that.m) && Arrays.equals(n, that.n) && Arrays.equals(a1, that.a1); } }
28.924528
406
0.54925
a32dfd7ce63a6ebe1c91f37bb0e827e94e001625
6,245
/* * Copyright 2008-2019 Async-IO.org * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.websocket; import org.atmosphere.cpr.AtmosphereConfig; import org.atmosphere.cpr.AtmosphereRequest; import org.atmosphere.cpr.AtmosphereResponse; import org.atmosphere.cpr.Broadcaster; import org.atmosphere.util.SimpleBroadcaster; import org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.io.Reader; /** * Atmosphere's WebSocket Support implementation. The default behavior is implemented in {@link DefaultWebSocketProcessor}. * This class is targeted at framework developer as it requires Atmosphere's internal knowledge. * <br/> * This class can also be used to implement the JSR 345 recommendation. * * @author Jeanfrancois Arcand */ public interface WebSocketProcessor { /** * Configure, or post construct a WebSocketProcessor * @param config an {@link org.atmosphere.cpr.AtmosphereConfig} * @return this */ WebSocketProcessor configure(AtmosphereConfig config); /** * Determine if the WebSocket's handshake data can be processed, or if the request be cancelled. Since it's container * related native API, the {@link HttpServletRequest} might be null, so implementation must check for null. * * @param request {@link HttpServletRequest} * @return true if the processing can continue, false if not. */ boolean handshake(HttpServletRequest request); /** * Register a {@link WebSocketHandler} * * @param path the URI mapping the WebSocketHandler * @param webSockethandler an instance of {@link org.atmosphere.websocket.WebSocketProcessor.WebSocketHandlerProxy} * @return this */ WebSocketProcessor registerWebSocketHandler(String path, WebSocketHandlerProxy webSockethandler); /** * Invoked when a WebSocket gets opened by the underlying container * * @param request * @throws IOException */ void open(WebSocket webSocket, AtmosphereRequest request, AtmosphereResponse response) throws IOException; /** * Invoked when a WebSocket message gets received from the underlying container * * @param webSocketMessage */ void invokeWebSocketProtocol(WebSocket webSocket, String webSocketMessage); /** * Invoked when a WebSocket message gets received from the underlying container * * @param data */ void invokeWebSocketProtocol(WebSocket webSocket, byte[] data, int offset, int length); /** * Invoked when a WebSocket message gets received from the underlying container * * @param stream */ void invokeWebSocketProtocol(WebSocket webSocket, InputStream stream); /** * Invoked when a WebSocket message gets received from the underlying container * * @param reader */ void invokeWebSocketProtocol(WebSocket webSocket, Reader reader) throws IOException; /** * Invked when the WebServer is closing the native WebSocket * * @param closeCode */ public void close(WebSocket webSocket, int closeCode); /** * Notify all {@link WebSocketEventListener} * * @param webSocketEvent */ void notifyListener(WebSocket webSocket, WebSocketEvent webSocketEvent); /** * Destroy all resources associated with this class. */ void destroy(); /** * An exception that can be used to flag problems with the WebSocket processing. */ public final static class WebSocketException extends Exception { private final AtmosphereResponse r; public WebSocketException(String s, AtmosphereResponse r) { super(s); this.r = r; } public WebSocketException(Throwable throwable, AtmosphereResponse r) { super(throwable); this.r = r; } public AtmosphereResponse response() { return r; } } public final static class WebSocketHandlerProxy implements WebSocketHandler { final Class<? extends Broadcaster> broadcasterClazz; final WebSocketHandler proxied; private String path; public WebSocketHandlerProxy(Class<? extends Broadcaster> broadcasterClazz, WebSocketHandler proxied) { this.broadcasterClazz = broadcasterClazz; this.proxied = proxied; } public WebSocketHandlerProxy(WebSocketHandler proxied) { this.broadcasterClazz = SimpleBroadcaster.class; this.proxied = proxied; } public String path() { return path; } public WebSocketHandlerProxy path(String path) { this.path = path; return this; } public WebSocketHandler proxied(){ return proxied; } @Override public void onByteMessage(WebSocket webSocket, byte[] data, int offset, int length) throws IOException { proxied.onByteMessage(webSocket,data,offset,length); } @Override public void onTextMessage(WebSocket webSocket, String data) throws IOException { proxied.onTextMessage(webSocket, data); } @Override public void onOpen(WebSocket webSocket) throws IOException { proxied.onOpen(webSocket); } @Override public void onClose(WebSocket webSocket) { proxied.onClose(webSocket); } @Override public void onError(WebSocket webSocket, WebSocketException t) { proxied.onError(webSocket,t); } } }
31.540404
123
0.679424
ddef9916236522d9f007d2857ce06957b4f25546
7,074
package com.fengwenyi.erwinchatroom.utils; import com.fengwenyi.api.result.ResponseTemplate; import com.fengwenyi.erwinchatroom.bo.MsgBo; import com.fengwenyi.erwinchatroom.domain.UserChatRoomModel; import com.fengwenyi.erwinchatroom.enums.FromTypeEnum; import com.fengwenyi.erwinchatroom.enums.MsgTypeEnum; import com.fengwenyi.erwinchatroom.vo.response.ResponseVo; import com.fengwenyi.erwinchatroom.vo.response.UserResponseVo; import com.fengwenyi.javalib.convert.DateTimeUtils; import com.fengwenyi.javalib.convert.JsonUtils; import org.springframework.util.CollectionUtils; import javax.websocket.Session; import java.io.IOException; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * @author <a href="https://www.fengwenyi.com">Erwin Feng</a> * @since 2021-08-15 */ public class MsgUtils { public static void sendUserError(Session session, String msg) { send(session, ResponseTemplate.fail(msg)); } public static void sendAll(String uid, String message) { UserChatRoomModel sender = UserChatRoomUtils.queryByUid(uid); sendAll( new MsgBo() .setMsgTypeEnum(MsgTypeEnum.CHAT) .setMessage(message) .setFromTypeEnum(FromTypeEnum.USER) .setSender(sender) .setReceiver(null) .setTimestamp(System.currentTimeMillis() / 1000) .setTimeStr(DateTimeUtils.format(LocalDateTime.now(), "HH:mm"))); } public static void sendBroadcast(String message) { sendAll( new MsgBo() .setMsgTypeEnum(MsgTypeEnum.BROADCAST) .setMessage(message) .setFromTypeEnum(FromTypeEnum.SYSTEM) .setSender(null) .setReceiver(null)); } public static void sendConn(String message) { sendAll( new MsgBo() .setMsgTypeEnum(MsgTypeEnum.CONN) .setMessage(message) .setFromTypeEnum(FromTypeEnum.SYSTEM) .setSender(null) .setReceiver(null)); } public static void sendUserOnLineUserList(UserChatRoomModel userChatRoomModel) { sendUser(userChatRoomModel, new MsgBo() .setMsgTypeEnum(MsgTypeEnum.ONLINE_USER_LIST) //.setMessage(message) .setFromTypeEnum(FromTypeEnum.SYSTEM) .setSender(null) .setReceiver(null) .setOnlineUserList(UserChatRoomUtils.queryAll())); } public static void sendAllUserUpLine(UserChatRoomModel userChatRoomModel) { sendAll(new MsgBo() .setMsgTypeEnum(MsgTypeEnum.USER_UP_LINE) //.setMessage(message) .setFromTypeEnum(FromTypeEnum.SYSTEM) .setSender(null) .setReceiver(null) .setUserUpLine(userChatRoomModel)); } private static void sendAll(MsgBo bo) { List<UserChatRoomModel> userChatRoomModelList = UserChatRoomUtils.queryAll(); UserChatRoomModel senderModel = bo.getSender(); UserChatRoomModel userUpLineModel = bo.getUserUpLine(); UserResponseVo userUpLine = new UserResponseVo(); if (Objects.nonNull(bo.getUserUpLine())) { userUpLine.setUid(userUpLineModel.getUid()) .setNickname(userUpLineModel.getNickname()) .setTimeStr(DateTimeUtils.format(userUpLineModel.getTime(), "HH:mm:ss")); } for (UserChatRoomModel model : userChatRoomModelList) { UserResponseVo sender = new UserResponseVo(); if (Objects.nonNull(senderModel)) { sender .setUid(senderModel.getUid()) .setNickname(senderModel.getNickname()) .setTimeStr(DateTimeUtils.format(senderModel.getTime(), "HH:mm:ss")) ; } if (Objects.equals(bo.getMsgTypeEnum().getCode(), MsgTypeEnum.USER_UP_LINE.getCode()) && model.getUid().equals(userUpLine.getUid())) { continue; } ResponseTemplate<ResponseVo> result = ResponseTemplate.success( new ResponseVo() .setFromType(bo.getFromTypeEnum().getCode()) .setSender(sender) .setMsgType(bo.getMsgTypeEnum().getCode()) .setMessage(bo.getMessage()) .setTimestamp(bo.getTimestamp()) .setTimeStr(bo.getTimeStr()) .setSelf(model.getUid().equals(sender.getUid())) .setUserUpLine(userUpLine)); send(model.getSession(), result); } } private static void sendUser(UserChatRoomModel userChatRoomModel, MsgBo bo) { UserChatRoomModel senderModel = bo.getSender(); List<UserResponseVo> onlineUserList = CollectionUtils.isEmpty(bo.getOnlineUserList()) ? null : bo.getOnlineUserList().stream() .map(model -> new UserResponseVo() .setUid(model.getUid()) .setNickname(model.getNickname()) .setTimeStr(DateTimeUtils.format(model.getTime(), "HH:mm:ss"))) .collect(Collectors.toList()); UserResponseVo sender = new UserResponseVo(); if (Objects.nonNull(senderModel)) { sender .setUid(senderModel.getUid()) .setNickname(senderModel.getNickname()) .setTimeStr(DateTimeUtils.format(senderModel.getTime(), "HH:mm:ss")) ; } ResponseTemplate<ResponseVo> result = ResponseTemplate.success( new ResponseVo() .setFromType(bo.getFromTypeEnum().getCode()) .setSender(sender) .setMsgType(bo.getMsgTypeEnum().getCode()) .setMessage(bo.getMessage()) .setTimestamp(bo.getTimestamp()) .setTimeStr(bo.getTimeStr()) .setSelf(userChatRoomModel.getUid().equals(sender.getUid())) .setOnlineUserList(onlineUserList)); send(userChatRoomModel.getSession(), result); } private static <T> void send(Session session, ResponseTemplate<T> result) { try { session.getBasicRemote().sendText(JsonUtils.convertString(result)); } catch (IOException e) { e.printStackTrace(); } } }
43.398773
103
0.562058
483823fe6a0761c28364ad824602cce7ae6660c7
3,676
package apache_httpcomponents.asyncclient; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.reactor.ConnectingIOReactor; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.concurrent.TimeUnit; /** * Created with IntelliJ IDEA. * Description: * User: Defias * Date: 2018-06 * * AsynHttpClient */ public class AsynHttpClientDemo2 { public static void main(String[] args){ RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(50000) //连接超时,连接建立时间,三次握手完成时间 .setSocketTimeout(50000) //请求超时,数据传输过程中数据包之间间隔的最大时间 .setConnectionRequestTimeout(1000) //请求超时,数据传输过程中数据包之间间隔的最大时间 .build(); //配置io线程 IOReactorConfig ioReactorConfig = IOReactorConfig.custom() .setIoThreadCount(Runtime.getRuntime().availableProcessors()) .setSoKeepAlive(true) .build(); //设置连接池大小 ConnectingIOReactor ioReactor = null; try { ioReactor = new DefaultConnectingIOReactor(ioReactorConfig); } catch (IOReactorException e) { e.printStackTrace(); } PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor); connManager.setMaxTotal(100); //连接池中最大连接数 connManager.setDefaultMaxPerRoute(100); //分配给同一个route(路由)最大的并发连接数 final CloseableHttpAsyncClient client = HttpAsyncClients.custom(). setConnectionManager(connManager) .setDefaultRequestConfig(requestConfig) .build(); //构造请求 String url = "http://127.0.0.1:9200/_bulk"; HttpPost httpPost = new HttpPost(url); StringEntity entity = null; try { String a = "{ \"index\": { \"_index\": \"test\", \"_type\": \"test\"} }\n" + "{\"name\": \"上海\",\"age\":33}\n"; entity = new StringEntity(a); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpPost.setEntity(entity); //start client.start(); //异步请求 client.execute(httpPost, new Back()); while(true){ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Back implements FutureCallback<HttpResponse> { private long start = System.currentTimeMillis(); Back() { } public void completed(HttpResponse httpResponse) { try { System.out.println("cost is:"+(System.currentTimeMillis()-start)+":"+ EntityUtils.toString(httpResponse.getEntity())); } catch (IOException e) { e.printStackTrace(); } } public void failed(Exception e) { System.err.println(" cost is:"+(System.currentTimeMillis()-start)+":"+e); } public void cancelled() { } } }
32.821429
134
0.635745
231e852248faa0d6f8124cea79433435086e7b92
8,476
/* * Copyright (C) 2019 The Android Open Source Project * * 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. */ import dalvik.system.InMemoryDexClassLoader; import java.lang.reflect.Method; import java.io.File; import java.nio.ByteBuffer; import java.util.Base64; public class Main { public static void main(String[] args) throws Exception { System.loadLibrary(args[0]); // Feature only enabled for target SDK version Q and later. setTargetSdkVersion(/* Q */ 29); if (isDebuggable()) { // Background verification is disabled in debuggable mode. This test makes // no sense then. return; } if (!hasOatFile()) { // We only generate vdex files if the oat directories are created. return; } setProcessDataDir(DEX_LOCATION); final int maxCacheSize = getVdexCacheSize(); final int numDexFiles = DEX_BYTES_CHECKSUMS.length; if (numDexFiles <= maxCacheSize) { throw new IllegalStateException("Not enough dex files to test cache eviction"); } // Simply load each dex file one by one. check(0, getCurrentCacheSize(), "There should be no vdex files in the beginning"); for (int i = 0; i < numDexFiles; ++i) { ClassLoader loader = loadDex(i); waitForVerifier(); check(true, hasVdexFile(loader), "Loading dex file should have produced a vdex"); check(Math.min(i + 1, maxCacheSize), getCurrentCacheSize(), "Unexpected number of cache entries"); } // More complicated pattern where some dex files get reused. for (int s = 1; s < numDexFiles; ++s) { for (int i = 0; i < maxCacheSize; ++i) { ClassLoader loader = loadDex(i); waitForVerifier(); check(true, hasVdexFile(loader), "Loading dex file should have produced a vdex"); check(maxCacheSize, getCurrentCacheSize(), "Unexpected number of cache entries"); } } } private static native boolean isDebuggable(); private static native boolean hasOatFile(); private static native int setTargetSdkVersion(int version); private static native void setProcessDataDir(String path); private static native void waitForVerifier(); private static native boolean hasVdexFile(ClassLoader loader); private static native int getVdexCacheSize(); private static native boolean isAnonymousVdexBasename(String basename); private static <T> void check(T expected, T actual, String message) { if (!expected.equals(actual)) { System.err.println("ERROR: " + message + " (expected=" + expected.toString() + ", actual=" + actual.toString() + ")"); } } private static int getCurrentCacheSize() { int count = 0; File folder = new File(DEX_LOCATION, "oat"); File[] subfolders = folder.listFiles(); if (subfolders.length != 1) { throw new IllegalStateException("Expect only one subfolder - isa"); } folder = subfolders[0]; for (File f : folder.listFiles()) { if (f.isFile() && isAnonymousVdexBasename(f.getName())) { count++; } } return count; } private static byte[] createDex(int index) { if (index >= 100) { throw new IllegalArgumentException("Not more than two decimals"); } // Clone the base dex file. This is the dex file for index 0 (class ID "01"). byte[] dex = DEX_BYTES_BASE.clone(); // Overwrite the checksum and sha1 signature. System.arraycopy(DEX_BYTES_CHECKSUMS[index], 0, dex, DEX_BYTES_CHECKSUM_OFFSET, DEX_BYTES_CHECKSUM_SIZE); // Check that the class ID offsets match expectations - they should contains "01". if (dex[DEX_BYTES_CLASS_ID_OFFSET1 + 0] != 0x30 || dex[DEX_BYTES_CLASS_ID_OFFSET1 + 1] != 0x31 || dex[DEX_BYTES_CLASS_ID_OFFSET2 + 0] != 0x30 || dex[DEX_BYTES_CLASS_ID_OFFSET2 + 1] != 0x31) { throw new IllegalStateException("Wrong class name values"); } // Overwrite class ID. byte str_id1 = (byte) (0x30 + ((index + 1) / 10)); byte str_id2 = (byte) (0x30 + ((index + 1) % 10)); dex[DEX_BYTES_CLASS_ID_OFFSET1 + 0] = str_id1; dex[DEX_BYTES_CLASS_ID_OFFSET1 + 1] = str_id2; dex[DEX_BYTES_CLASS_ID_OFFSET2 + 0] = str_id1; dex[DEX_BYTES_CLASS_ID_OFFSET2 + 1] = str_id2; return dex; } private static ClassLoader loadDex(int index) { return new InMemoryDexClassLoader(ByteBuffer.wrap(createDex(index)), /*parent*/ null); } private static final String DEX_LOCATION = System.getenv("DEX_LOCATION"); private static final int DEX_BYTES_CLASS_ID_OFFSET1 = 0xfd; private static final int DEX_BYTES_CLASS_ID_OFFSET2 = 0x11d; private static final int DEX_BYTES_CHECKSUM_OFFSET = 8; private static final int DEX_BYTES_CHECKSUM_SIZE = 24; // Dex file for: "public class MyClass01 {}". private static final byte[] DEX_BYTES_BASE = Base64.getDecoder().decode( "ZGV4CjAzNQBHVjDjQ9WQ2TSezZ0exFH00hvlJrenqvNEAgAAcAAAAHhWNBIAAAAAAAAAALABAAAG" + "AAAAcAAAAAMAAACIAAAAAQAAAJQAAAAAAAAAAAAAAAIAAACgAAAAAQAAALAAAAB0AQAA0AAAAOwA" + "AAD0AAAAAQEAABUBAAAlAQAAKAEAAAEAAAACAAAABAAAAAQAAAACAAAAAAAAAAAAAAAAAAAAAQAA" + "AAAAAAAAAAAAAQAAAAEAAAAAAAAAAwAAAAAAAACfAQAAAAAAAAEAAQABAAAA6AAAAAQAAABwEAEA" + "AAAOAAEADgAGPGluaXQ+AAtMTXlDbGFzczAxOwASTGphdmEvbGFuZy9PYmplY3Q7AA5NeUNsYXNz" + "MDEuamF2YQABVgB1fn5EOHsiY29tcGlsYXRpb24tbW9kZSI6ImRlYnVnIiwibWluLWFwaSI6MSwi" + "c2hhLTEiOiI4ZjI5NTlkMDExNmMyYjdmZTZlMDUxNWQ3MTQxZTRmMGY0ZTczYzBiIiwidmVyc2lv" + "biI6IjEuNS41LWRldiJ9AAAAAQAAgYAE0AEAAAAAAAAADAAAAAAAAAABAAAAAAAAAAEAAAAGAAAA" + "cAAAAAIAAAADAAAAiAAAAAMAAAABAAAAlAAAAAUAAAACAAAAoAAAAAYAAAABAAAAsAAAAAEgAAAB" + "AAAA0AAAAAMgAAABAAAA6AAAAAIgAAAGAAAA7AAAAAAgAAABAAAAnwEAAAMQAAABAAAArAEAAAAQ" + "AAABAAAAsAEAAA=="); // Checksum/SHA1 signature diff for classes MyClass01 - MyClassXX. // This is just a convenient way of storing many similar dex files. private static final byte[][] DEX_BYTES_CHECKSUMS = new byte[][] { Base64.getDecoder().decode("R1Yw40PVkNk0ns2dHsRR9NIb5Sa3p6rz"), Base64.getDecoder().decode("i1V1U3C8nexVk4uw185lXZd9kzd82iaA"), Base64.getDecoder().decode("tFPbVPdpzuoDWqH71Ak5HpltBHg0frMU"), Base64.getDecoder().decode("eFSc7dENiK8nxviKBmd/O2s7h/NAj+l/"), Base64.getDecoder().decode("DlUfNQ3cuVrCHRyw/cOFhqEe+0r6wlUP"), Base64.getDecoder().decode("KVaBmdG8Y8kx8ltEPXWyi9OCdL14yeiW"), Base64.getDecoder().decode("K1bioDTHtPwmrPXkvZ0XYCiripH6KsC2"), Base64.getDecoder().decode("oVHctdpHG3YTNeQlVCshTkFKVra9TG4k"), Base64.getDecoder().decode("eVWMFHRY+w4lpn9Uo9jn+eNAmaRK4HEw"), Base64.getDecoder().decode("/lW3Q3U4ot5A2qkhiv4Aj+s8zv7984MA"), Base64.getDecoder().decode("BFRB+4HwRbuD164DB3sVy28dc+Ea5YVQ"), Base64.getDecoder().decode("klQBLEXyr0cviHDHlqFyWPGKaQQnqMiD"), Base64.getDecoder().decode("jlTcJAkpnbDI/E4msuvMyWqKxNMTN0YU"), Base64.getDecoder().decode("vlUOrp4aN0PxcaqQrQmm597P+Ymu5Adt"), Base64.getDecoder().decode("HlXyT1GoJk1m33O8OMaYxqy3K1Byyf1S"), Base64.getDecoder().decode("d1O5toIKjTXNZkgP3p9RiiafhuKw4gUH"), Base64.getDecoder().decode("11RsuG9UrFHPipOj9zjuGU9obctMJbq6"), Base64.getDecoder().decode("dlSW5egObqheoHSRthlR2c2jVKLGQ3QL"), Base64.getDecoder().decode("ulMgQEhC0XMhmKxHtgdURY6B6JEqNb3E"), Base64.getDecoder().decode("YFV08vrcs49xYr1OBhrza5H8Ha86FODz"), Base64.getDecoder().decode("jFKPxTFd3kn6K0p6n8YEPgm0hiozXW1p"), Base64.getDecoder().decode("LlUZdlCXwAn4qksYL6Urw+bZC/fYuJ1T"), Base64.getDecoder().decode("K1SuRt9xZX5lAVtbpMauOWLVXs2KooUA"), Base64.getDecoder().decode("2FJAWIk0JS9EdvkgHjquLL9qdcLeHaRJ"), Base64.getDecoder().decode("YVResABr9IvZLV8eeIhM3TXfGC+Y6/x1"), Base64.getDecoder().decode("UVTrkVGIh8u7FBHgcbS9flI0CY5g2E3m"), Base64.getDecoder().decode("oVIu6RsrT6HgnbPzNGiYZSpKS0cqNi+a"), Base64.getDecoder().decode("2FR/slWq9YC6kJRDEw21RVGmJhr3/uKZ"), Base64.getDecoder().decode("CFbaSi70ZVaumL7zsXWlD/ernHxCZPx6"), Base64.getDecoder().decode("7FTY+T1/qevWQM6Yoe+OwNcUdgcCUomJ"), }; }
43.917098
90
0.729943
fc1b5c858bea700eb07760e9efbc465f10a552b9
1,286
package com.atguigu.gmall.pms; import com.atguigu.gmall.pms.mapper.SkuMapper; import com.atguigu.gmall.pms.service.SkuAttrValueService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class GmallPmsApplicationTests { @Autowired private SkuMapper skuMapper; @Autowired private SkuAttrValueService attrValueService; @Test void contextLoads() { // // 查询出spu下所有的sku // List<SkuEntity> skuEntities = this.skuMapper.selectList(new QueryWrapper<SkuEntity>().eq("spu_Id", 41)); // // 搜索所有的skuId // List<Long> skuIds = skuEntities.stream().map(SkuEntity::getId).collect(Collectors.toList()); // // 查询sku对应的销售属性 // List<SkuAttrValueEntity> skuAttrValueEntities = this.attrValueService.list(new QueryWrapper<SkuAttrValueEntity>().in("sku_id", skuIds).orderByAsc("attr_id")); // // 以attrId分组: attrId-Key List<SkuAttrValueEntity>-value // Map<Object, List<SkuAttrValueEntity>> map = skuAttrValueEntities.stream().collect(Collectors.groupingBy(t ->t.getAttrId())); // System.out.println(map); System.out.println(this.attrValueService.querySaleAttrsBySpuId(41l)); } }
38.969697
168
0.728616
0dbb8f92ed7a257c5450faa753ad0023c5e02006
1,073
import java.util.List; import java.util.ArrayList; public class Vertex { final private String id; final private String name; private List<Edge> _edges; public Vertex(String id, String name) { this.id = id; this.name = name; _edges = new ArrayList<Edge>(); } public String getId() { return id; } public String getName() { return name; } public void addEdge(Edge pEdge) { _edges.add(pEdge); } public List<Edge> getEdges() { return _edges; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vertex other = (Vertex) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return name; } }
21.039216
43
0.521901
6bc18fd822e51988642b7889ac22fc08b9e59e7f
4,972
package io.cucumber.java8; import io.cucumber.core.backend.Backend; import io.cucumber.core.backend.Container; import io.cucumber.core.backend.DataTableTypeDefinition; import io.cucumber.core.backend.DefaultDataTableCellTransformerDefinition; import io.cucumber.core.backend.DefaultDataTableEntryTransformerDefinition; import io.cucumber.core.backend.DefaultParameterTransformerDefinition; import io.cucumber.core.backend.DocStringTypeDefinition; import io.cucumber.core.backend.Glue; import io.cucumber.core.backend.HookDefinition; import io.cucumber.core.backend.Lookup; import io.cucumber.core.backend.ParameterTypeDefinition; import io.cucumber.core.backend.Snippet; import io.cucumber.core.backend.StepDefinition; import io.cucumber.core.resource.ClasspathScanner; import io.cucumber.core.resource.ClasspathSupport; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Supplier; final class Java8Backend implements Backend { private final Lookup lookup; private final Container container; private final ClasspathScanner classFinder; private final List<Class<? extends LambdaGlue>> lambdaGlueClasses = new ArrayList<>(); private Glue glue; Java8Backend(Lookup lookup, Container container, Supplier<ClassLoader> classLoaderProvider) { this.container = container; this.lookup = lookup; this.classFinder = new ClasspathScanner(classLoaderProvider); } @Override public void loadGlue(Glue glue, List<URI> gluePaths) { this.glue = glue; // Scan for Java8 style glue (lambdas) gluePaths.stream() .filter(gluePath -> ClasspathSupport.CLASSPATH_SCHEME.equals(gluePath.getScheme())) .map(ClasspathSupport::packageName) .map(basePackageName -> classFinder.scanForSubClassesInPackage(basePackageName, LambdaGlue.class)) .flatMap(Collection::stream) .filter(glueClass -> !glueClass.isInterface()) .filter(glueClass -> glueClass.getConstructors().length > 0) .forEach(glueClass -> { container.addClass(glueClass); lambdaGlueClasses.add(glueClass); }); } @Override public void buildWorld() { // Instantiate all the stepdef classes for java8 - the stepdef will be initialised // in the constructor. LambdaGlueRegistry.INSTANCE.set(new GlueAdaptor(glue)); for (Class<? extends LambdaGlue> lambdaGlueClass : lambdaGlueClasses) { lookup.getInstance(lambdaGlueClass); } } @Override public void disposeWorld() { LambdaGlueRegistry.INSTANCE.remove(); } @Override public Snippet getSnippet() { return new Java8Snippet(); } private static final class GlueAdaptor implements LambdaGlueRegistry { private final Glue glue; private GlueAdaptor(Glue glue) { this.glue = glue; } @Override public void addStepDefinition(StepDefinition stepDefinition) { glue.addStepDefinition(stepDefinition); } @Override public void addBeforeStepHookDefinition(HookDefinition beforeStepHook) { glue.addBeforeStepHook(beforeStepHook); } @Override public void addAfterStepHookDefinition(HookDefinition afterStepHook) { glue.addAfterStepHook(afterStepHook); } @Override public void addBeforeHookDefinition(HookDefinition beforeHook) { glue.addBeforeHook(beforeHook); } @Override public void addAfterHookDefinition(HookDefinition afterHook) { glue.addAfterHook(afterHook); } @Override public void addDocStringType(DocStringTypeDefinition docStringType) { glue.addDocStringType(docStringType); } @Override public void addDataTableType(DataTableTypeDefinition dataTableType) { glue.addDataTableType(dataTableType); } @Override public void addParameterType(ParameterTypeDefinition parameterType) { glue.addParameterType(parameterType); } @Override public void addDefaultParameterTransformer(DefaultParameterTransformerDefinition defaultParameterTransformer) { glue.addDefaultParameterTransformer(defaultParameterTransformer); } @Override public void addDefaultDataTableCellTransformer(DefaultDataTableCellTransformerDefinition defaultDataTableCellTransformer) { glue.addDefaultDataTableCellTransformer(defaultDataTableCellTransformer); } @Override public void addDefaultDataTableEntryTransformer(DefaultDataTableEntryTransformerDefinition defaultDataTableEntryTransformer) { glue.addDefaultDataTableEntryTransformer(defaultDataTableEntryTransformer); } } }
33.594595
134
0.706758
46999eac78c309513f9e2d087709c3983ce40a1d
2,496
/* * MIT License - Copyright (c) 2018 Francielle da Silva Nunes, Luís Fernando Ávila * Criada em 25 ago 2018 */ package br.com.iftm.lfa.controller; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; /** * Classe criada para resolução do exercício correspondente a letra H A * linguagem inicia-se com 0 e a soma de todos os seus dígitos é par Ou * inicia-se com 1 e a soma de todos os seus dígitos é ímpar * * @author Francielle da Silva Nunes */ public class H { public H(char[] cadeia) { List<Character> digitos = new ArrayList<Character>(); for (int i = 0; i <= 9; i++) { digitos.add((char) (i + '0')); } List<Character> pares = new ArrayList<Character>(); for (int i = 0; i < 9; i += 2) { pares.add((char) (i + '0')); } List<Character> impares = new ArrayList<Character>(); for (int i = 1; i <= 9; i += 2) { impares.add((char) (i + '0')); } Boolean erro = false; int Q = 1; if (cadeia.equals("")) { erro = true; } else { for (char c : cadeia) { switch (Q) { case 1: if (c == '0' || c == '1') { Q = 2; } else { erro = true; } break; case 2: if (pares.contains(c)) { Q = 2; } else if (impares.contains(c)) { Q = 3; } else { erro = true; } break; case 3: if (pares.contains(c)) { Q = 3; } else if (impares.contains(c)) { Q = 2; } else { erro = true; } break; case 4: erro = true; default: break; } } } if (erro || (Q != 2)) { JOptionPane.showMessageDialog(null, "Sentença não reconhecida"); } else { JOptionPane.showMessageDialog(null, "Sentença reconhecida"); } } }
29.714286
82
0.384215
94ef41d21cc93a5c4bdb3282987b320cff70f5a1
1,763
/* * All GTAS code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP). * * Please see LICENSE.txt for details. */ package gov.gtas.services.security; import static gov.gtas.constant.GtasSecurityConstants.PRIVILEGE_ADMIN; import gov.gtas.constant.GtasSecurityConstants; import gov.gtas.model.User; import java.util.List; import java.util.Set; import gov.gtas.model.UserGroup; import org.springframework.security.access.prepost.PreAuthorize; /** * The Interface UserService. */ public interface UserService { /** * Creates the User. * * @param userData * the user data * @return the user data */ @PreAuthorize(PRIVILEGE_ADMIN) UserData create(UserData user); /** * Delete. * * @param id * the user id */ @PreAuthorize(PRIVILEGE_ADMIN) void delete(String id); /** * Find all. * * @return the list */ @PreAuthorize(GtasSecurityConstants.PRIVILEGES_ADMIN_AND_VIEW_PASSENGER) List<UserData> findAll(); /** * Update the user. * * @param userData * the user data * @return the updated user data */ UserData update(UserData user); /** * Update the user. * * @param userData * the user data * @return the updated user data */ @PreAuthorize(PRIVILEGE_ADMIN) UserData updateByAdmin(UserData user); /** * Find by id. * * @param id * the id * @return the user data */ UserData findById(String id); /** * Fetch user. * * @param userId * the user id * @return the user */ User fetchUser(final String userId); Set<UserGroup> fetchUserGroups(final String userId); boolean isAdminUser(String userId); boolean treatAsOneDay(String userId); }
18.364583
120
0.66591
1001d3f682341f0e70ef0027d64f6b514c1cb330
2,595
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.main; import java.util.concurrent.TimeUnit; /** * Graceful shutdown when using Camel Main. */ public interface MainShutdownStrategy { /** * Event listener when shutting down. */ interface ShutdownEventListener { /** * Callback on shutdown */ void onShutdown(); } /** * Adds a shutdown listener * * @param listener the listener */ void addShutdownListener(ShutdownEventListener listener); /** * Returns true if the application is allowed to run. * * @return true if the application is allowed to run. */ boolean isRunAllowed(); /** * Return true if the shutdown has been initiated by the caller. * * @return true if the shutdown has been initiated by the caller. */ boolean shutdown(); /** * Waiting for Camel Main to complete. */ void await() throws InterruptedException; /** * Waiting for Camel Main to complete (with timeout). * * @param timeout the maximum time to wait * @param unit the time unit of the {@code timeout} argument * @return true if Camel Main was completed before the timeout, false if timeout was triggered. */ boolean await(long timeout, TimeUnit unit) throws InterruptedException; /** * This is used for restarting await with timeout. */ void restartAwait(); int getExtraShutdownTimeout(); /** * Extra timeout in seconds to graceful shutdown Camel. * * When Camel is shutting down then Camel first shutdown all the routes (shutdownTimeout). Then additional services * is shutdown (extraShutdownTimeout). */ void setExtraShutdownTimeout(int extraShutdownTimeout); }
29.157303
119
0.674759
1ffeaf04ebccf19b4b1f2f5a059597b14542bab7
267
package com.greg.golf.repository; import com.greg.golf.entity.Cycle; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CycleRepository extends JpaRepository<Cycle, Long> { }
26.7
69
0.835206
4cb06bd2452721acd33807dc5aec5a7e831bdc53
1,298
/** * $Id: mxDomUtils.java,v 1.1 2012/11/15 13:26:39 gaudenz Exp $ * Copyright (c) 2007-2012, JGraph Ltd */ package com.mxgraph.util; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * Contains various DOM API helper methods for use with mxGraph. */ public class mxDomUtils { /** * Returns a new, empty DOM document. * * @return Returns a new DOM document. */ public static Document createDocument() { Document result = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); result = parser.newDocument(); } catch (Exception e) { System.out.println(e.getMessage()); } return result; } /** * Returns a document with a HTML node containing a HEAD and BODY node. */ public static Document createHtmlDocument() { Document document = createDocument(); Element root = document.createElement("html"); document.appendChild(root); Element head = document.createElement("head"); root.appendChild(head); Element body = document.createElement("body"); root.appendChild(body); return document; } }
22.77193
76
0.684129
e626b48bc3c3731bf6ac9a5450d672c19a1e45e6
801
/* * * * Copyright OpenSearch Contributors * * SPDX-License-Identifier: Apache-2.0 * */ package com.amazon.dataprepper.plugins.processor.drop; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; class DropEventProcessorConfigTest { private DropEventProcessorConfig config; @BeforeEach void setUp() { config = new DropEventProcessorConfig(); } @Test void getWhen() { assertThat(config.getDropWhen(), is(nullValue())); } @Test void getHandleFailedEventsOption() { assertThat(config.getHandleFailedEventsOption(), is(HandleFailedEventsOption.SKIP)); } }
22.885714
92
0.722846
de85cbe8dde903477a0b4bcc0e6d3cd9b163b42a
640
package com.pixelblur.DropGame.android; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.pixelblur.DropGame.MainClass; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); config.useAccelerometer = true; config.useCompass = true; initialize(new MainClass(), config); } }
32
81
0.764063
1494da436536f3187f8e17e161aa167b414d8051
3,623
/* * Serposcope - SEO rank checker https://serposcope.serphacker.com/ * * Copyright (c) 2016 SERP Hacker * @author Pierre Nogues <support@serphacker.com> * @license https://opensource.org/licenses/MIT MIT License */ package com.serphacker.serposcope.di; import com.serphacker.serposcope.models.base.Config; import com.serphacker.serposcope.scraper.captcha.solver.AntiCaptchaSolver; import com.serphacker.serposcope.scraper.captcha.solver.CaptchaSolver; import com.serphacker.serposcope.scraper.captcha.solver.DeathByCaptchaSolver; import com.serphacker.serposcope.scraper.captcha.solver.ImageTyperzSolver; import com.serphacker.serposcope.scraper.captcha.solver.TwoCaptchaSolver; import com.serphacker.serposcope.scraper.captcha.solver.FailoverCaptchaSolver; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CaptchaSolverFactoryImpl implements CaptchaSolverFactory { private static final Logger LOG = LoggerFactory.getLogger(CaptchaSolverFactoryImpl.class); @Override public CaptchaSolver get(Config config) { if(config == null){ return null; } List<CaptchaSolver> solvers = new ArrayList<>(); if (!StringUtils.isEmpty(config.getDbcUser()) && !StringUtils.isEmpty(config.getDbcPass())) { DeathByCaptchaSolver solver = new DeathByCaptchaSolver(config.getDbcUser(), config.getDbcPass()); if(init(solver)){ solvers.add(solver); } } if(!StringUtils.isEmpty(config.getAnticaptchaKey())){ AntiCaptchaSolver solver = new AntiCaptchaSolver(config.getAnticaptchaKey()); if(init(solver)){ solvers.add(solver); } } if(!StringUtils.isEmpty(config.getTwoCaptchaKey())){ TwoCaptchaSolver solver = new TwoCaptchaSolver(config.getTwoCaptchaKey()); if(init(solver)){ solvers.add(solver); } } if(!StringUtils.isEmpty(config.getImageTyperzKey())){ ImageTyperzSolver solver = new ImageTyperzSolver(config.getImageTyperzKey()); if(init(solver)){ solvers.add(solver); } } // if (!StringUtils.isEmpty(config.getDecaptcherUser()) && !StringUtils.isEmpty(config.getDecaptcherPass())) { // DecaptcherSolver solver = new DecaptcherSolver(config.getDecaptcherUser(), config.getDecaptcherPass()); // if(init(solver)){ // solvers.add(solver); // } // } if(solvers.isEmpty()){ return null; } Collections.shuffle(solvers); return new FailoverCaptchaSolver(solvers); } protected boolean init(CaptchaSolver solver){ if(!solver.init()){ LOG.warn("{} : failed to init()", solver.getFriendlyName()); return false; } if(!solver.testLogin()){ LOG.warn("{} : can't login in", solver.getFriendlyName()); return false; } LOG.debug("{} : remaining credit {}", solver.getFriendlyName(), solver.getCredit()); if(!solver.hasCredit()){ LOG.warn("{} : not enough credit", solver.getFriendlyName()); return false; } return true; } }
35.871287
117
0.610268
18c8cebc6a51b1e1d3876907f2fbed1b5558f31c
403
package com.eg.exam; /* 有一家农场,养了一群小动物。养的有鸡40只,羊10只,牛2头。 其中鸡全是母鸡,每只母鸡每个月有20天下蛋,每次下蛋1颗,其余时间休息。 每年2月份农夫会人工孵化鸡蛋剩余数的20%,其余鸡蛋全部出售,并且会出售或宰杀20%母鸡。 孵化出来的小鸡全是母鸡,小鸡一年之后开始下蛋。 羊群里面有8只母羊,2只公羊。每只母羊每年10月生产5只小羊,性别随机。 每年2月农夫出售20%羊,公羊母羊各一半(若为20%的羊数为奇数,多的那一头羊为公羊)。 小羊2年后开始生产,性别随机。 公牛和母牛各1头,每2年生产1只小牛。小牛2年会后开始生产,小牛的性别随机。 现在是2017年9月1日,请问10年后农产有多少只鸡,多少头养,多少头牛? 请问10年后动物的头和脚的数量各是多少。同时请注意闰年天数。 */ public class Test { }
19.190476
45
0.811414
6297320285c64e5e4d8aaa81b97c5c3aa17ae0ac
863
package com.haskforce.cabal.psi; import com.haskforce.cabal.CabalFileType; import com.haskforce.cabal.CabalIcons; import com.haskforce.cabal.CabalLanguage; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class CabalFile extends PsiFileBase { public CabalFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, CabalLanguage.INSTANCE); } @NotNull @Override public FileType getFileType() { return CabalFileType.INSTANCE; } @Override public String toString() { return "Cabal File"; } @Nullable @Override public Icon getIcon(int flags) { return CabalIcons.FILE; } }
23.972222
62
0.732329
f74c4d002f1f72daadc173ecc0a75536ddc7184f
235
package com.lego.goods.dao; import com.lego.goods.pojo.Pref; import tk.mybatis.mapper.common.Mapper; /**** * @Author:admin * @Description:Pref的Dao * @Date 2019/6/14 0:12 *****/ public interface PrefMapper extends Mapper<Pref> { }
19.583333
50
0.710638
89454433ae6b5d29e87bee1b5efa2771d16e8056
1,822
package builddb.cs4224c.document; import com.fasterxml.jackson.annotation.JsonInclude; public class OrderItemOrderLines { private int ol_number; private Timestamp ol_delivery_d; private double ol_amount; private int ol_supply_w_id; private int ol_quantity; private String ol_dist_info; private int ol_i_id; private String i_name; public int getOl_number() { return ol_number; } public void setOl_number(int ol_number) { this.ol_number = ol_number; } @JsonInclude(JsonInclude.Include.NON_NULL) public Timestamp getOl_delivery_d() { return ol_delivery_d; } public void setOl_delivery_d(Long ol_delivery_d_timestamp) { if (ol_delivery_d_timestamp != null) { this.ol_delivery_d = new Timestamp(ol_delivery_d_timestamp); } } public double getOl_amount() { return ol_amount; } public void setOl_amount(double ol_amount) { this.ol_amount = ol_amount; } public int getOl_supply_w_id() { return ol_supply_w_id; } public void setOl_supply_w_id(int ol_supply_w_id) { this.ol_supply_w_id = ol_supply_w_id; } public int getOl_quantity() { return ol_quantity; } public void setOl_quantity(int ol_quantity) { this.ol_quantity = ol_quantity; } public String getOl_dist_info() { return ol_dist_info; } public void setOl_dist_info(String ol_dist_info) { this.ol_dist_info = ol_dist_info; } public int getOl_i_id() { return ol_i_id; } public void setOl_i_id(int ol_i_id) { this.ol_i_id = ol_i_id; } public String getI_name() { return i_name; } public void setI_name(String i_name) { this.i_name = i_name; } }
21.690476
72
0.655324
edfaf56720c436bee06ea4e6331c003ef963f0a3
445
package com.hardik.spring; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import com.hardik.spring.config.AppConfig; /** * Application Main Class * */ public class App { public static void main(String[] args) { AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); context.close(); } }
23.421053
95
0.802247
163293c186601c2479202132dae04946be7008f2
246
package com.rbkmoney.analytics.listener.handler.dominant; import com.rbkmoney.damsel.domain_config.Operation; public interface DominantHandler { void handle(Operation operation, long versionId); boolean isHandle(Operation change); }
20.5
57
0.796748
8766d58b5bd24c2cb961b6f0e167b323a778ab70
205
package racingcar.domain.game; public abstract class GameResult { protected GameSet gameSet; protected GameResult(GameSet gameSet) { this.gameSet = gameSet; } abstract void showResult(); }
15.769231
41
0.736585
6b07a246ee579a2e3d1c888103fdea66fdbcda30
633
package org.keclipse.rcp; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; /** * List Label provider for the table viewer * * @author vibhu.pratap * */ public class ListLabelProvider extends LabelProvider implements ITableLabelProvider { /** * No Column Image by default */ @Override public Image getColumnImage(Object element, int columnIndex) { return null; } /** * Will be overriden for non availble Column */ @Override public String getColumnText(Object element, int columnIndex) { return "Unsupported"; } }
21.1
85
0.747235
92811ab3203639b7161ea6dc096b2bbc022dafd5
1,144
package com.andyadc.shopizer.search.services.workflow; import com.andyadc.shopizer.search.services.worker.DeleteObjectWorker; import com.andyadc.shopizer.search.services.worker.ExecutionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.List; @Component public class DeleteObjectWorkflow extends Workflow { private static final Logger log = LoggerFactory.getLogger(DeleteObjectWorkflow.class); private List deleteObjectWorkflow; public List getDeleteObjectWorkflow() { return deleteObjectWorkflow; } public void setDeleteObjectWorkflow(List deleteObjectWorkflow) { this.deleteObjectWorkflow = deleteObjectWorkflow; } public void deleteObject(String collection, String id) throws Exception { if (deleteObjectWorkflow != null) { ExecutionContext context = new ExecutionContext(); for (Object o : deleteObjectWorkflow) { DeleteObjectWorker iw = (DeleteObjectWorker) o; iw.deleteObject(super.getSearchClient(), collection, id, context); } } } }
27.238095
89
0.741259
a0fd4f892d4bec2a9b84f71a8fa27178d980269d
4,951
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jax.rs.shiro.authz.impl; import static javax.ws.rs.Priorities.AUTHORIZATION; import static javax.ws.rs.Priorities.USER; import static org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants.JAX_RS_APPLICATION_SERVICE_PROPERTIES; import static org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants.JAX_RS_NAME; import java.util.Map; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; import org.apache.shiro.web.jaxrs.ExceptionMapper; import org.apache.shiro.web.jaxrs.ShiroAnnotationFilterFeature; import org.apache.shiro.web.jaxrs.ShiroFeature; import org.apache.shiro.web.jaxrs.SubjectPrincipalRequestFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This type mirrors {@link ShiroFeature}, by registering an {@link ExceptionMapper}, * {@link SubjectPrincipalRequestFilter} and {@link ShiroAnnotationFilterFeature}. * * <p>We cannot use the {@link ShiroFeature} directly because several of the extension * types it registers are also used to enable authentication, and it is not allowed to * register the same extension twice. Also the ShiroFeature does not make correct use * of priorities when registering. This Feature therefore: * * <ul> * <li>Avoids duplicate registrations with extension types that are also used in authentication.</li> * <li>Uses priorities to indicate that these are authorization extensions</li> * </ul> * */ public class ShiroAuthorizationFeature implements Feature { private static final Logger _LOG = LoggerFactory.getLogger( ShiroAuthorizationFeature.class); @Override public boolean configure(FeatureContext fc) { Configuration configuration = fc.getConfiguration(); if(_LOG.isInfoEnabled()) { @SuppressWarnings("unchecked") Map<String, Object> applicationProps = (Map<String, Object>) configuration.getProperty(JAX_RS_APPLICATION_SERVICE_PROPERTIES); _LOG.info("Registering the Shiro Authorization feature with application {}", applicationProps.getOrDefault(JAX_RS_NAME, "<No Name found in application configuration>")); } Map<Class<?>, Integer> contracts = configuration.getContracts(ExceptionMapper.class); if(contracts.isEmpty()) { _LOG.debug("Registering the Shiro ExceptionMapper"); // Only register the ExceptionMapper if it isn't already registered fc.register(ExceptionMapper.class, AUTHORIZATION); } else if(AUTHORIZATION < contracts.getOrDefault(javax.ws.rs.ext.ExceptionMapper.class, USER)) { _LOG.debug("Updating the priority of the Shiro ExceptionMapper from {} to {}", contracts.getOrDefault(javax.ws.rs.ext.ExceptionMapper.class, USER), AUTHORIZATION); // Update the priority if it's registered too low contracts.put(javax.ws.rs.ext.ExceptionMapper.class, AUTHORIZATION); } contracts = configuration.getContracts(SubjectPrincipalRequestFilter.class); if(contracts.isEmpty()) { _LOG.debug("Registering the Shiro SubjectPrincipalRequestFilter"); // Only register the SubjectPrincipalRequestFilter if it isn't already registered fc.register(SubjectPrincipalRequestFilter.class, AUTHORIZATION); } else if(AUTHORIZATION < contracts.getOrDefault(ContainerRequestFilter.class, USER)) { _LOG.debug("Updating the priority of the Shiro SubjectPrincipalRequestFilter from {} to {}", contracts.getOrDefault(ContainerRequestFilter.class, USER), AUTHORIZATION); // Update the priority if it's registered too low contracts.put(ContainerRequestFilter.class, AUTHORIZATION); } _LOG.debug("Registering the Shiro ShiroAnnotationFilterFeature"); fc.register(ShiroAnnotationFilterFeature.class, Priorities.AUTHORIZATION); return true; } }
49.019802
138
0.726722
2ef8150ef0f89eaac5a28732eecebf4adff3a4c1
4,120
/* * Copyright 2015 Piotr Buda * * 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 me.piotrbuda.intellij.pony.syntax; import com.google.common.collect.Sets; import com.intellij.lexer.FlexAdapter; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import me.piotrbuda.intellij.pony.parser.PonyLexer; import me.piotrbuda.intellij.pony.parser.PonyParserDefinition; import me.piotrbuda.intellij.pony.psi.PonyTypes; import org.jetbrains.annotations.NotNull; import java.util.Set; import static com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey; import static me.piotrbuda.intellij.pony.parser.PonyParserDefinition.*; public class PonySyntaxHighlighter extends SyntaxHighlighterBase { public static final TextAttributesKey ILLEGAL = createTextAttributesKey("PONY_ILLEGAL", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE); public static final TextAttributesKey STRING = createTextAttributesKey("STRINGS", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey ID = createTextAttributesKey("ID", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey NUMBER = createTextAttributesKey("NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey KEYWORD = createTextAttributesKey("KEYWORD", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey ML_STRING =createTextAttributesKey("ML_STRING", DefaultLanguageHighlighterColors.DOC_COMMENT); public static final TextAttributesKey SL_COMMENT =createTextAttributesKey("SL_COMMENT_CONTENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey CAP =createTextAttributesKey("CAP", DefaultLanguageHighlighterColors.KEYWORD); private static final Set<IElementType> KEYWORDS = Sets.newHashSet(PONY_CLASS_DEF, PONY_USE, PONY_IF, PONY_AT, PONY_LET, PONY_VAR, PONY_METHOD, PONY_RETURN, PONY_BREAK, PONY_CONTINUE, PONY_ERROR, PONY_COMPILER, PONY_AS, PonyTypes.BINOP, PONY_THEN, PONY_ELSE, PONY_END, PONY_MATCH, PONY_WHILE, PONY_DO, PONY_REPEAT, PONY_UNTIL, PONY_FOR, PONY_IN, PONY_WITH, PONY_TRY, PONY_RECOVER, PONY_CONSUME, PONY_NOT, PONY_IDENTITYOF, PONY_WHERE, PONY_ELSEIF, PONY_OBJECT, PONY_LAMBDA); @NotNull @Override public Lexer getHighlightingLexer() { return new FlexAdapter(new PonyLexer()); } @NotNull @Override public TextAttributesKey[] getTokenHighlights(final IElementType tokenType) { if (tokenType == TokenType.BAD_CHARACTER) { return pack(ILLEGAL); } else if (tokenType == PonyTypes.STRING) { return pack(STRING); } else if (tokenType == PonyTypes.ID) { return pack(ID); } else if (KEYWORDS.contains(tokenType)) { return pack(KEYWORD); } else if (tokenType == PonyTypes.INT || tokenType == PonyTypes.FLOAT) { return pack(NUMBER); } else if (tokenType == PonyParserDefinition.ML_STRING || tokenType == PonyParserDefinition.ML_STRING_CONTENT) { return pack(ML_STRING); } else if(tokenType == PonyParserDefinition.LINE_COMMENT) { return pack(SL_COMMENT); } else if(tokenType == PonyTypes.CAP) { return pack(CAP); } return EMPTY; } }
50.864198
157
0.759466
fe324b6bdfcef534f68263a0c90a5c94eac205c7
2,958
package com.lsh.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; @Controller public class DownLoadController { private final static String utf8 ="utf-8"; @RequestMapping("/download") public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception { File file = new File("E:\\fileItem\\LearningNotes-master.zip"); response.setCharacterEncoding(utf8); InputStream is = null; OutputStream os = null; try{ //分片下载 http Range bytes=100-1000 bytes=100- long fSize = file.length(); response.setContentType("application/x-download"); String fileName = URLEncoder.encode(file.getName(),utf8); response.addHeader("Content-Disposition","attachment;filename=" + fileName); response.setHeader("Accept-Range","bytes"); response.setHeader("fSize",String.valueOf(fSize)); response.setHeader("fName",fileName); long pos = 0,last = fSize-1,sum = 0; if(null != request.getHeader("Range")){ response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String numRange = request.getHeader("Range").replaceAll("bytes=",""); String[] strRange = numRange.split("-"); if(strRange.length == 2){ pos = Long.parseLong(strRange[0].trim()); last = Long.parseLong(strRange[1].trim()); if(last > fSize-1){ last = fSize-1; } }else{ pos = Long.parseLong(numRange.replaceAll("-","").trim()); } } long rangeLenght = last - pos +1; String contentRange = new StringBuffer("bytes ").append(pos).append("-").append(last).append("/").append(fSize).toString(); response.setHeader("Content-Range",contentRange); response.setHeader("Content-Lenght",String.valueOf(rangeLenght)); os = new BufferedOutputStream(response.getOutputStream()); is = new BufferedInputStream(new FileInputStream(file)); is.skip(pos); byte[] buffer = new byte[1024]; int lenght = 0; while(sum < rangeLenght){ lenght = is.read(buffer,0,((rangeLenght-sum) <= buffer.length ? ((int)(rangeLenght-sum)) : buffer.length)); sum = sum+ lenght; os.write(buffer,0,lenght); } System.out.println("下载完成"); }finally { if(is != null){ is.close(); } if(os != null){ os.close(); } } } }
40.520548
135
0.568289
d3e88f749d6b9a4a10295a0cf07dacb11f5e774b
3,437
package brennus; import java.util.HashMap; import java.util.Map; import brennus.model.BoxingTypeConversion; import brennus.model.CastTypeConversion; import brennus.model.Field; import brennus.model.FieldAccessType; import brennus.model.FutureType; import brennus.model.LocalVariableAccessType; import brennus.model.Method; import brennus.model.Parameter; import brennus.model.ParameterAccessType; import brennus.model.PrimitiveType; import brennus.model.Type; import brennus.model.TypeConversion; import brennus.model.UnboxingTypeConversion; import brennus.model.VarAccessType; public final class MethodContext { private final FutureType type; private final Method method; private final Map<String, LocalVarContext> localVars = new HashMap<String, LocalVarContext>(); public MethodContext(FutureType type, Method method) { this.type = type; this.method = method; } private Parameter getParam(String fieldName) { Iterable<Parameter> parameters = method.getParameters(); for (Parameter parameter : parameters) { if (parameter.getName().equals(fieldName)) { return parameter; } } return null; } public VarAccessType getVarAccessType(String varName) { Parameter param = getParam(varName); if (param != null) { return new ParameterAccessType(param); } else { Field field = type.getField(varName); if (field!=null) { return new FieldAccessType(field); } else { LocalVarContext localVarContext; if (!localVars.containsKey(varName)) { throw new RuntimeException("can not access " + varName + " in parameters, local variables or fields of " + type.getName() + "." + method.getName() + method.getSignature()); } else { localVarContext = localVars.get(varName); } return new LocalVariableAccessType(varName, localVarContext.getIndex(), localVarContext.getType()); } } } @Override public String toString() { return "["+this.getClass().getSimpleName()+" "+method+"]"; } public Type getReturnType() { return method.getReturnType(); } public TypeConversion getTypeConversion(Type from, Type to) { if (to.equals(from)) { return TypeConversion.NONE; } if (from.isPrimitive() && !to.isPrimitive()) { return new BoxingTypeConversion((PrimitiveType) from); } else if (!from.isPrimitive() && to.isPrimitive()) { return new UnboxingTypeConversion((PrimitiveType) to); } else if (!from.isPrimitive() && !to.isPrimitive()) { if (to.isAssignableFrom(from)) { return TypeConversion.NONE; } else { return new CastTypeConversion(to); } } else { // TODO: add cast in between primitives throw new UnsupportedOperationException("TODO: convert " + from + " to " + to); } } public Method getMethod() { return this.method; } public String getClassIdentifier() { return type.getClassIdentifier(); } public FutureType getType() { return type; } public LocalVarContext defineLocalVar(Type type, String varName) { // TODO: deal with scope if (localVars.containsKey(varName)) { throw new RuntimeException("Duplicate local variable "+varName+ " in method "+method.toString()); } LocalVarContext context = new LocalVarContext(varName, localVars.size(), type); localVars.put(varName, context); return context; } }
29.62931
182
0.688973
cb83c199c950a6f690629ded109f034d52c1202e
10,697
package org.nci.cgr; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import htsjdk.variant.variantcontext.Genotype; import htsjdk.variant.variantcontext.GenotypeBuilder; import htsjdk.variant.variantcontext.GenotypesContext; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; public class MergedVariant extends Variant { public MergedVariant(VariantContext variant, String callerID,int p,Byte s) throws ClassNotFoundException{ super(variant,callerID,p,s); } @Override public int hashCode() { String alt=""; if (variantContext.getAlleles().size()==2) alt=variantContext.getAlleles().get(1).getBaseString(); else alt=variantContext.getAlleles().get(0).getBaseString(); return Objects.hash(variantContext.getContig(), variantContext.getStart(),variantContext.getReference().getBaseString(),alt); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Variant that = (Variant) o; return this.variantContext.getContig().equals(that.variantContext.getContig()) && this.variantContext.getStart()==that.variantContext.getStart() && this.variantContext.getAlleles().equals(that.variantContext.getAlleles()); } public MergedVariant merge(MergedVariant other) throws ClassNotFoundException { assert(this.equals(other)); VariantContextBuilder build=new VariantContextBuilder(); // List<Allele> alleles = this.variantContext.getAlleles(); Boolean multipleCallerCalled=false; if (this.getCaller().contains(",")) multipleCallerCalled=true; //if (alleles.equals(other.variantContext.getAlleles())) { Byte s=(byte) (this.set|other.set); if (s==this.set) return(null); //duplicate variant from a same caller Map<String,Object> thisInfo=new HashMap<String,Object>(); Map<String,Object> otherInfo=new HashMap<String,Object>(); Map<String,Object> mergedInfo=new HashMap<String,Object>(); thisInfo=this.variantContext.getAttributes(); for (String key:thisInfo.keySet()){ if (multipleCallerCalled) mergedInfo.put(key, thisInfo.get(key)); else mergedInfo.put(SomaticCombiner.callerName(this.caller)+"_"+key, thisInfo.get(key)); } otherInfo=other.variantContext.getAttributes(); for (String key:otherInfo.keySet()) mergedInfo.put(SomaticCombiner.callerName(other.caller)+"_"+key, otherInfo.get(key)); String qual=""; if (this.getVariantContext().hasLog10PError()) { if (!multipleCallerCalled) { qual=String.valueOf(this.getVariantContext().getPhredScaledQual()); mergedInfo.put(SomaticCombiner.callerName(this.caller)+"_"+VCFFile.QUAL_TAG, qual); } } if (other.getVariantContext().hasLog10PError()) { qual=String.valueOf(other.getVariantContext().getPhredScaledQual()); mergedInfo.put(SomaticCombiner.callerName(other.caller)+"_"+VCFFile.QUAL_TAG, qual); } GenotypesContext thisGenotypes=null; GenotypesContext otherGenotypes=null; List<Genotype> mergedGenotypes=new ArrayList<Genotype>(); if (this.variantContext.hasGenotypes() && other.variantContext.hasGenotypes()) { thisGenotypes=this.variantContext.getGenotypes(); otherGenotypes=other.variantContext.getGenotypes(); if (thisGenotypes.size()==otherGenotypes.size()) { Set<String> thisSampleNames = thisGenotypes.getSampleNames(); Set<String> otherSampleNames = otherGenotypes.getSampleNames(); if (thisSampleNames.size() == 2) { String[] thisSamples = new String[2]; boolean thisFoundTumor = false; for (String sampleName : thisSampleNames) if (sampleName.toUpperCase().contains(VCFFile.TUMOR_TAG1)||sampleName.toUpperCase().contains(VCFFile.TUMOR_TAG2)) { thisSamples[0] = sampleName; thisFoundTumor = true; } else thisSamples[1] = sampleName; String[] otherSamples = new String[2]; boolean otherFoundTumor = false; for (String sampleName : otherSampleNames) if (sampleName.toUpperCase().contains(VCFFile.TUMOR_TAG1)||sampleName.toUpperCase().contains(VCFFile.TUMOR_TAG2)) { otherSamples[0] = sampleName; otherFoundTumor = true; } else otherSamples[1] = sampleName; if (thisFoundTumor && otherFoundTumor) { for (int i = 0; i < thisGenotypes.size(); i++) { String sampleName=VCFFile.TUMOR_TAG1; if (i==1) sampleName=VCFFile.NORMAL_TAG; GenotypeBuilder mergedGenotypeBuilder = new GenotypeBuilder(); Map<String, Object> mergedExtendedGT = new HashMap<String, Object>(); Genotype tmpGenotype = null; Map<String, Object> thisExtendedGT = thisGenotypes.get(thisSamples[i]).getExtendedAttributes(); Map<String, Object> otherExtendedGT = otherGenotypes.get(otherSamples[i]).getExtendedAttributes(); for (String key : thisExtendedGT.keySet()) { // if (key.contains("FDP")) // System.out.println("Found!"); if (multipleCallerCalled) mergedExtendedGT.put(key, thisExtendedGT.get(key)); else mergedExtendedGT.put(SomaticCombiner.callerName(this.caller) + "_" + key, thisExtendedGT.get(key)); } for (String key : otherExtendedGT.keySet()) mergedExtendedGT.put(SomaticCombiner.callerName(other.caller) + "_" + key, otherExtendedGT.get(key)); mergedGenotypeBuilder.attributes(mergedExtendedGT); if (this.priority > other.priority) tmpGenotype = thisGenotypes.get(thisSamples[i]); else tmpGenotype = otherGenotypes.get(otherSamples[i]); mergedGenotypeBuilder.alleles(tmpGenotype.getAlleles()); if (thisGenotypes.get(thisSamples[i]).hasAD() && otherGenotypes.get(otherSamples[i]).hasAD()) mergedGenotypeBuilder.AD(tmpGenotype.getAD()); else { if (thisGenotypes.get(thisSamples[i]).hasAD()) mergedGenotypeBuilder.AD(thisGenotypes.get(thisSamples[i]).getAD()); if (otherGenotypes.get(otherSamples[i]).hasAD()) mergedGenotypeBuilder.AD(otherGenotypes.get(otherSamples[i]).getAD()); } if (thisGenotypes.get(thisSamples[i]).hasDP() && otherGenotypes.get(otherSamples[i]).hasDP()) mergedGenotypeBuilder.DP(tmpGenotype.getDP()); else { if (thisGenotypes.get(thisSamples[i]).hasDP()) mergedGenotypeBuilder.DP(thisGenotypes.get(thisSamples[i]).getDP()); if (otherGenotypes.get(i).hasDP()) mergedGenotypeBuilder.DP(otherGenotypes.get(otherSamples[i]).getDP()); } mergedGenotypeBuilder.name(sampleName); mergedGenotypes.add(mergedGenotypeBuilder.make()); } } } } else { List<Genotype> tmpGenotypes=null; if (this.variantContext.getGenotypes().size()>other.variantContext.getGenotypes().size()) tmpGenotypes=this.variantContext.getGenotypes(); else tmpGenotypes=other.variantContext.getGenotypes(); if (tmpGenotypes!=null) { for (Genotype tmpGenotype:tmpGenotypes) mergedGenotypes.add(tmpGenotype); } } }else { GenotypesContext tmpGenotypes=null; Set<String> tmpSampleNames = null; String tmpCaller=""; if (this.variantContext.hasGenotypes()) { tmpGenotypes=this.variantContext.getGenotypes(); tmpSampleNames=this.variantContext.getSampleNames(); tmpCaller=this.getCaller(); } if (other.variantContext.hasGenotypes()) { tmpGenotypes=other.variantContext.getGenotypes(); tmpSampleNames=other.variantContext.getSampleNames(); tmpCaller=other.getCaller(); } if (tmpGenotypes!=null) { if (tmpSampleNames.size() == 2) { String[] tmpSamples = new String[2]; boolean tmpFoundTumor = false; for (String sampleName : tmpSampleNames) if (sampleName.toUpperCase().contains(VCFFile.TUMOR_TAG1)||sampleName.toUpperCase().contains(VCFFile.TUMOR_TAG2)) { tmpSamples[0] = sampleName; tmpFoundTumor = true; } else tmpSamples[1] = sampleName; if (tmpFoundTumor) { for (int i = 0; i < tmpGenotypes.size(); i++) { Map<String, Object> mergedExtendedGT = new HashMap<String, Object>(); GenotypeBuilder mergedGenotypeBuilder = new GenotypeBuilder(); String sampleName=VCFFile.TUMOR_TAG1; if (i==1) sampleName=VCFFile.NORMAL_TAG; Map<String, Object> thisExtendedGT = tmpGenotypes.get(tmpSamples[i]).getExtendedAttributes(); for (String key : thisExtendedGT.keySet()) mergedExtendedGT.put(SomaticCombiner.callerName(tmpCaller) + "_" + key, thisExtendedGT.get(key)); mergedGenotypeBuilder.attributes(mergedExtendedGT); mergedGenotypeBuilder.alleles(tmpGenotypes.get(tmpSamples[i]).getAlleles()); if (tmpGenotypes.get(tmpSamples[i]).hasAD() ) mergedGenotypeBuilder.AD(tmpGenotypes.get(tmpSamples[i]).getAD()); else { if (tmpGenotypes.get(tmpSamples[i]).hasAD()) mergedGenotypeBuilder.AD(tmpGenotypes.get(tmpSamples[i]).getAD()); } if (tmpGenotypes.get(tmpSamples[i]).hasDP()) mergedGenotypeBuilder.DP(tmpGenotypes.get(tmpSamples[i]).getDP()); else { if (tmpGenotypes.get(tmpSamples[i]).hasDP()) mergedGenotypeBuilder.DP(tmpGenotypes.get(tmpSamples[i]).getDP()); } mergedGenotypeBuilder.name(sampleName); mergedGenotypes.add(mergedGenotypeBuilder.make()); } } } } } build.alleles(this.variantContext.getAlleles()); build.chr(this.variantContext.getContig()); build.start(this.variantContext.getStart()); if (this.variantContext.getID().equals(other.variantContext.getID())) build.id(this.variantContext.getID()); else { if (this.variantContext.getID().equals(".")) build.id(other.variantContext.getID()); if (other.variantContext.getID().equals(".")) build.id(this.variantContext.getID()); } build.stop(this.variantContext.getEnd()); build.genotypes(mergedGenotypes); build.attributes(mergedInfo); VariantContext mergedVc=build.make(); int mergedPriority=this.priority; if (this.priority<other.priority) mergedPriority=other.priority; return new MergedVariant(mergedVc,this.caller+","+other.caller,mergedPriority,s); //} //return null; } }
40.366038
156
0.679723
0adef78d269b2aea3c0a837cd80e3353690345eb
2,204
/**************************************************** * Copyright (c) 2019, Grindrod Bank Limited * License MIT: https://opensource.org/licenses/MIT ****************************************************/ package za.co.grindrodbank.dokuti.documenttag; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import za.co.grindrodbank.dokuti.document.DocumentEntity; import za.co.grindrodbank.dokuti.exceptions.DatabaseLayerException; public interface DocumentTagService { /** * Finds a document tag using a composite document tag ID object as the key. * * @param documentTagId An instance of the documentTagId, which is the composite * key for a tag. * @return An instance of the Document Tag. */ public Optional<DocumentTagEntity> findById(DocumentTagId documentTagId); /** * Persists the state of a document tag to the database. Creates the record if * it does not exist. * * @param documentTag The document tag to persist. * @return The document Tag (with ID if created). */ public DocumentTagEntity save(DocumentTagEntity documentTag); /** * Creates all the required tag records for a document from an array of tag * strings. * * @param tags An array of tag strings to create tag records from. * @param document The document to create the tags for. */ public void createDocumentTags(List<String> tags, DocumentEntity document); /** * Flattens the the composite ID formatted DocumentTag set into a simple array * of all it's tags. * * @param documentTags The set of DocumentTags to flatten. * @return An array of document Tag strings pertaining to the document. */ public String[] getFlattenedTagsArray(Set<DocumentTagEntity> documentTags); /** * Finds a distinct list of all the tags that are assigned to documents. * * @param pageRequest An instance of the page request to perform paging with. * @return A list of distinct tags assigned to documents. * @throws DatabaseLayerException */ public Page<String> findAllDistinctTags(Pageable pageRequest) throws DatabaseLayerException; }
34.4375
93
0.709165
a8c29049c1fb0a6689d948cf44ea5d3d945fc6f5
10,227
/* * Copyright 2018 JDCLOUD.COM * * 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. * * * * * * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ package com.jdcloud.sdk.service.redis.model; import com.jdcloud.sdk.annotation.Required; /** * 缓存Redis实例的配置参数 */ public class ConfigItem implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * configName目前只支持以下参数: maxmemory-policy(redis 2.8和redis 4.0都支持,但配置值不相同):内存剔除策略的最大使用内存限制 hash-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中最多能存放entry个数的阈值 hash-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中能存放的value长度的最大值 list-max-ziplist-entries(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中最多能存放entry个数的阈值 list-max-ziplist-value(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中能存放的value长度的最大值 list-max-ziplist-size(只有redis 4.0支持):用ziplist编码实现的列表对象,按照数据项个数或占用的字节数,限定ziplist的长度 list-compress-depth(只有redis 4.0支持):用ziplist编码实现的列表对象,quicklist两端不被压缩的节点个数 set-max-intset-entries(redis 2.8和redis 4.0都支持):用intset编码实现的集合对象,intset中最多能存放entry个数的阈值 zset-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中最多能存放entry个数的阈值 zset-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中能存放的value长度的最大值 slowlog-log-slower-than(redis 2.8和redis 4.0都支持):慢查询日志超时时间,单位微秒(1000000表示1秒),0表示记录所有的命令 notify-keyspace-events(只有redis 4.0支持):事件通知 * Required:true */ @Required private String configName; /** * 参数的配置值,默认值、参考值如下: maxmemory-policy(redis 2.8和redis 4.0的默认值都为volatile-lru):redis 4.0 的参考值有[volatile-lru, allkeys-lru, volatile-lfu, allkeys-lfu, volatile-random, allkeys-random, volatile-ttl, noeviction],redis 2.8的参考值有[volatile-lru , allkeys-lru , volatile-random , allkeys-random , volatile-ttl , noeviction] hash-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] hash-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] list-max-ziplist-entries(redis 2.8的默认值为512,redis 4.0不支持):[0-10000] list-max-ziplist-value(redis 2.8的默认值为64,redis 4.0不支持):[0-10000] list-max-ziplist-size(redis 4.0的默认值为-2,redis 2.8不支持):[-5-10000] list-compress-depth(redis 4.0的默认值为0,redis 2.8不支持):[0-10000] set-max-intset-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] zset-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为128):[0-10000] zset-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] slowlog-log-slower-than(redis 2.8和redis 4.0的默认值都为10000):[0-10000] notify-keyspace-events(redis 4.0的默认值为空,redis 2.8不支持):[K , E , g , $ , l , s , h , z , x , e , A]字母的组合,区分大小写,或为空 * Required:true */ @Required private String configValue; /** * get configName目前只支持以下参数: maxmemory-policy(redis 2.8和redis 4.0都支持,但配置值不相同):内存剔除策略的最大使用内存限制 hash-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中最多能存放entry个数的阈值 hash-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中能存放的value长度的最大值 list-max-ziplist-entries(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中最多能存放entry个数的阈值 list-max-ziplist-value(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中能存放的value长度的最大值 list-max-ziplist-size(只有redis 4.0支持):用ziplist编码实现的列表对象,按照数据项个数或占用的字节数,限定ziplist的长度 list-compress-depth(只有redis 4.0支持):用ziplist编码实现的列表对象,quicklist两端不被压缩的节点个数 set-max-intset-entries(redis 2.8和redis 4.0都支持):用intset编码实现的集合对象,intset中最多能存放entry个数的阈值 zset-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中最多能存放entry个数的阈值 zset-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中能存放的value长度的最大值 slowlog-log-slower-than(redis 2.8和redis 4.0都支持):慢查询日志超时时间,单位微秒(1000000表示1秒),0表示记录所有的命令 notify-keyspace-events(只有redis 4.0支持):事件通知 * * @return */ public String getConfigName() { return configName; } /** * set configName目前只支持以下参数: maxmemory-policy(redis 2.8和redis 4.0都支持,但配置值不相同):内存剔除策略的最大使用内存限制 hash-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中最多能存放entry个数的阈值 hash-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中能存放的value长度的最大值 list-max-ziplist-entries(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中最多能存放entry个数的阈值 list-max-ziplist-value(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中能存放的value长度的最大值 list-max-ziplist-size(只有redis 4.0支持):用ziplist编码实现的列表对象,按照数据项个数或占用的字节数,限定ziplist的长度 list-compress-depth(只有redis 4.0支持):用ziplist编码实现的列表对象,quicklist两端不被压缩的节点个数 set-max-intset-entries(redis 2.8和redis 4.0都支持):用intset编码实现的集合对象,intset中最多能存放entry个数的阈值 zset-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中最多能存放entry个数的阈值 zset-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中能存放的value长度的最大值 slowlog-log-slower-than(redis 2.8和redis 4.0都支持):慢查询日志超时时间,单位微秒(1000000表示1秒),0表示记录所有的命令 notify-keyspace-events(只有redis 4.0支持):事件通知 * * @param configName */ public void setConfigName(String configName) { this.configName = configName; } /** * get 参数的配置值,默认值、参考值如下: maxmemory-policy(redis 2.8和redis 4.0的默认值都为volatile-lru):redis 4.0 的参考值有[volatile-lru, allkeys-lru, volatile-lfu, allkeys-lfu, volatile-random, allkeys-random, volatile-ttl, noeviction],redis 2.8的参考值有[volatile-lru , allkeys-lru , volatile-random , allkeys-random , volatile-ttl , noeviction] hash-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] hash-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] list-max-ziplist-entries(redis 2.8的默认值为512,redis 4.0不支持):[0-10000] list-max-ziplist-value(redis 2.8的默认值为64,redis 4.0不支持):[0-10000] list-max-ziplist-size(redis 4.0的默认值为-2,redis 2.8不支持):[-5-10000] list-compress-depth(redis 4.0的默认值为0,redis 2.8不支持):[0-10000] set-max-intset-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] zset-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为128):[0-10000] zset-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] slowlog-log-slower-than(redis 2.8和redis 4.0的默认值都为10000):[0-10000] notify-keyspace-events(redis 4.0的默认值为空,redis 2.8不支持):[K , E , g , $ , l , s , h , z , x , e , A]字母的组合,区分大小写,或为空 * * @return */ public String getConfigValue() { return configValue; } /** * set 参数的配置值,默认值、参考值如下: maxmemory-policy(redis 2.8和redis 4.0的默认值都为volatile-lru):redis 4.0 的参考值有[volatile-lru, allkeys-lru, volatile-lfu, allkeys-lfu, volatile-random, allkeys-random, volatile-ttl, noeviction],redis 2.8的参考值有[volatile-lru , allkeys-lru , volatile-random , allkeys-random , volatile-ttl , noeviction] hash-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] hash-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] list-max-ziplist-entries(redis 2.8的默认值为512,redis 4.0不支持):[0-10000] list-max-ziplist-value(redis 2.8的默认值为64,redis 4.0不支持):[0-10000] list-max-ziplist-size(redis 4.0的默认值为-2,redis 2.8不支持):[-5-10000] list-compress-depth(redis 4.0的默认值为0,redis 2.8不支持):[0-10000] set-max-intset-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] zset-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为128):[0-10000] zset-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] slowlog-log-slower-than(redis 2.8和redis 4.0的默认值都为10000):[0-10000] notify-keyspace-events(redis 4.0的默认值为空,redis 2.8不支持):[K , E , g , $ , l , s , h , z , x , e , A]字母的组合,区分大小写,或为空 * * @param configValue */ public void setConfigValue(String configValue) { this.configValue = configValue; } /** * set configName目前只支持以下参数: maxmemory-policy(redis 2.8和redis 4.0都支持,但配置值不相同):内存剔除策略的最大使用内存限制 hash-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中最多能存放entry个数的阈值 hash-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的哈希对象,ziplist中能存放的value长度的最大值 list-max-ziplist-entries(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中最多能存放entry个数的阈值 list-max-ziplist-value(只有redis 2.8支持):用ziplist编码实现的列表对象,ziplist中能存放的value长度的最大值 list-max-ziplist-size(只有redis 4.0支持):用ziplist编码实现的列表对象,按照数据项个数或占用的字节数,限定ziplist的长度 list-compress-depth(只有redis 4.0支持):用ziplist编码实现的列表对象,quicklist两端不被压缩的节点个数 set-max-intset-entries(redis 2.8和redis 4.0都支持):用intset编码实现的集合对象,intset中最多能存放entry个数的阈值 zset-max-ziplist-entries(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中最多能存放entry个数的阈值 zset-max-ziplist-value(redis 2.8和redis 4.0都支持):用ziplist编码实现的有序集合对象,ziplist中能存放的value长度的最大值 slowlog-log-slower-than(redis 2.8和redis 4.0都支持):慢查询日志超时时间,单位微秒(1000000表示1秒),0表示记录所有的命令 notify-keyspace-events(只有redis 4.0支持):事件通知 * * @param configName */ public ConfigItem configName(String configName) { this.configName = configName; return this; } /** * set 参数的配置值,默认值、参考值如下: maxmemory-policy(redis 2.8和redis 4.0的默认值都为volatile-lru):redis 4.0 的参考值有[volatile-lru, allkeys-lru, volatile-lfu, allkeys-lfu, volatile-random, allkeys-random, volatile-ttl, noeviction],redis 2.8的参考值有[volatile-lru , allkeys-lru , volatile-random , allkeys-random , volatile-ttl , noeviction] hash-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] hash-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] list-max-ziplist-entries(redis 2.8的默认值为512,redis 4.0不支持):[0-10000] list-max-ziplist-value(redis 2.8的默认值为64,redis 4.0不支持):[0-10000] list-max-ziplist-size(redis 4.0的默认值为-2,redis 2.8不支持):[-5-10000] list-compress-depth(redis 4.0的默认值为0,redis 2.8不支持):[0-10000] set-max-intset-entries(redis 2.8和redis 4.0的默认值都为512):[0-10000] zset-max-ziplist-entries(redis 2.8和redis 4.0的默认值都为128):[0-10000] zset-max-ziplist-value(redis 2.8和redis 4.0的默认值都为64):[0-10000] slowlog-log-slower-than(redis 2.8和redis 4.0的默认值都为10000):[0-10000] notify-keyspace-events(redis 4.0的默认值为空,redis 2.8不支持):[K , E , g , $ , l , s , h , z , x , e , A]字母的组合,区分大小写,或为空 * * @param configValue */ public ConfigItem configValue(String configValue) { this.configValue = configValue; return this; } }
48.014085
290
0.76738
35f99427a28959e1f967ba7de525937135d8cf59
5,823
package org.yun.string.handler; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Function; /** * <p>use builder mode build timeline data * <p>example: * <java> * List<Pojo> dataList = new ArrayList() {{ * add(new Pojo() {{ * setDate(new Date()); * setValue("1"); * }}); * add(new Pojo() {{ * setDate(Date.from(Instant.now().minusSeconds(3600 * 24 * 1))); * setValue("2"); * }}); * add(new Pojo() {{ * setDate(Date.from(Instant.now().minusSeconds(3600 * 24 * 1))); * setValue("3"); * }}); * add(new Pojo() {{ * setDate(Date.from(Instant.now().minusSeconds(3600 * 24 * 2))); * setValue("3"); * }}); * }}; * * Map<String, BigDecimal> result = new TimeLineData.Builder<Pojo>() * .dataList(dataList) * .k(it -> DateKit.getStr(LocalDateTime.ofInstant(it.getDate().toInstant(), ZoneId.systemDefault()), DateType.MONTH)) * .v(it -> BigDecimal.valueOf(Double.parseDouble(it.getValue()))) * .start(LocalDateTime.of(2020, 8, 1, 1, 1)) * .end(LocalDateTime.of(2021, 8, 1, 1, 1)) * .build() * .getData(); * </java> * * @author yunkuangao * @apiNote build time-line data */ public class TimeLineData<V> { private List<V> dataList; private Function<V, Boolean> perFilter; private Function<Map<String, BigDecimal>, Boolean> postFilter; private Function<V, String> k; private Function<V, BigDecimal> v; private DateType dateType; private LocalDateTime start; private LocalDateTime end; private BigDecimal init; private TimeLineData() { } protected void setDataList(List<V> dataList) { this.dataList = dataList; } protected void setPerFilter(Function<V, Boolean> perFilter) { this.perFilter = perFilter; } protected void setPostFilter(Function<Map<String, BigDecimal>, Boolean> postFilter) { this.postFilter = postFilter; } protected void setK(Function<V, String> k) { this.k = k; } protected void setV(Function<V, BigDecimal> v) { this.v = v; } protected void setDateType(DateType dateType) { this.dateType = dateType; } protected void setStart(LocalDateTime start) { this.start = start; } protected void setEnd(LocalDateTime end) { this.end = end; } protected void setInit(BigDecimal init) { this.init = init; } /** * @apiNote get timeline data * @return */ public Map<String, BigDecimal> getData() { return new TreeMap<String, BigDecimal>() {{ putAll(DateKit.getTimeLineTemplate(dateType, start, end, init)); putAll(dataList.stream() .filter(it -> perFilter.apply(it)) .map(it -> (Map<String, BigDecimal>) new HashMap<String, BigDecimal>() {{ put(k.apply(it), v.apply(it)); }}) .filter(it -> postFilter.apply(it)) .reduce(new HashMap<>(), (older, newer) -> { newer.forEach((key, value) -> older.merge(key, value, BigDecimal::add)); return older; })); }}; } static class Builder<V> { private List<V> dataList = null; private Function<V, Boolean> perFilter = v -> true; private Function<Map<String, BigDecimal>, Boolean> postFilter = v -> true; private Function<V, String> k = null; private Function<V, BigDecimal> v = null; private DateType dateType = DateType.MONTH; private LocalDateTime start = LocalDateTime.now().minusYears(1); private LocalDateTime end = LocalDateTime.now(); private BigDecimal init = BigDecimal.ZERO; public Builder<V> perFilter(Function<V, Boolean> perFilter) { this.perFilter = perFilter; return this; } public Builder<V> postFilter(Function<Map<String, BigDecimal>, Boolean> postFilter) { this.postFilter = postFilter; return this; } public Builder<V> dataList(List<V> dataList) { this.dataList = dataList; return this; } public Builder<V> k(Function<V, String> k) { this.k = k; return this; } public Builder<V> v(Function<V, BigDecimal> v) { this.v = v; return this; } public Builder<V> dateType(DateType dateType) { this.dateType = dateType; return this; } public Builder<V> start(LocalDateTime start) { this.start = start; return this; } public Builder<V> end(LocalDateTime end) { this.end = end; return this; } public Builder<V> init(BigDecimal init) { this.init = init; return this; } public TimeLineData<V> build() { return new TimeLineData<V>() {{ this.setDataList(dataList); this.setK(k); this.setV(v); this.setPerFilter(perFilter); this.setPostFilter(postFilter); this.setDateType(dateType); this.setStart(start); this.setEnd(end); this.setInit(init); }}; } } }
28.26699
134
0.532543
c4cdd802f0752d05ffc9e2ae55578716d4f06b24
211
package perococco.aoc.day14.structures; import lombok.NonNull; public interface Memory { void setValue(int address, long value); void setActiveMask(@NonNull Mask mask); long sumOfAllValues(); }
16.230769
43
0.734597
7a82ba8526aba23f94f82cc69574ccb573b5062e
4,952
package com.example.android.miwok; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class PhrasesFragment extends Fragment { private MediaPlayer mMediaPlayer; private AudioManager mAudioManager; private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { releaseMediaPlayer(); } }; AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() { public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { releaseMediaPlayer(); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK) { // Pause playback mMediaPlayer.pause(); mMediaPlayer.seekTo(0); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { mMediaPlayer.start(); // Your app has been granted audio focus again // Raise volume to normal, restart playback if necessary } } }; public PhrasesFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.word_list, container, false); mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); final ArrayList<Word> phrases = new ArrayList<>(); phrases.add(new Word("minto wuksus", "Where are you going?", R.raw.phrase_where_are_you_going)); phrases.add(new Word("tinnә oyaase'nә", "What is your name?", R.raw.phrase_what_is_your_name)); phrases.add(new Word("oyaaset...", "My name is...", R.raw.phrase_my_name_is)); phrases.add(new Word("michәksәs?", "How are you feeling?", R.raw.phrase_how_are_you_feeling)); phrases.add(new Word("kuchi achit", "I'm feeling good.", R.raw.phrase_im_feeling_good)); phrases.add(new Word("әәnәs'aa?", "Are you coming?", R.raw.phrase_are_you_coming)); phrases.add(new Word("hәә’ әәnәm", "Yes, I’m coming.", R.raw.phrase_yes_im_coming)); phrases.add(new Word("әәnәm", "I’m coming.", R.raw.phrase_im_coming)); phrases.add(new Word("yoowutis", "Let’s go.", R.raw.phrase_lets_go)); phrases.add(new Word("әnni'nem", "Come here.", R.raw.phrase_come_here)); WordAdapter phrasesAdapter = new WordAdapter(getActivity(), phrases, R.color.category_phrases); ListView phrasesList = rootView.findViewById(R.id.word_activity_list_view); phrasesList.setAdapter(phrasesAdapter); phrasesList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { Word word = phrases.get(position); releaseMediaPlayer(); // Request audio focus for playback int result = mAudioManager.requestAudioFocus(afChangeListener, // Use the music stream. AudioManager.STREAM_MUSIC, // Request permanent focus. AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // Start playback mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioId()); mMediaPlayer.start(); mMediaPlayer.setOnCompletionListener(mOnCompletionListener); } } }); return rootView; } @Override public void onStop() { super.onStop(); releaseMediaPlayer(); } private void releaseMediaPlayer() { if(mMediaPlayer != null) { mMediaPlayer.release(); mMediaPlayer = null; // Abandon audio focus when playback complete mAudioManager.abandonAudioFocus(afChangeListener); } } }
40.92562
152
0.609653
1c48a8621083770726e907af47ae5a4e54720404
5,122
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.conversion; import javax.time.calendar.Period; import javax.time.calendar.ZonedDateTime; import org.apache.commons.lang.Validate; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.core.holiday.HolidaySource; import com.opengamma.financial.convention.ConventionBundle; import com.opengamma.financial.convention.ConventionBundleSource; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.frequency.Frequency; import com.opengamma.financial.instrument.FixedIncomeInstrumentConverter; import com.opengamma.financial.instrument.index.CMSIndex; import com.opengamma.financial.instrument.index.IborIndex; import com.opengamma.financial.instrument.payment.CapFloorCMSSpreadDefinition; import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity; import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurityVisitor; import com.opengamma.id.ExternalId; import com.opengamma.util.money.Currency; /** * */ public class CapFloorCMSSpreadSecurityConverter implements CapFloorCMSSpreadSecurityVisitor<FixedIncomeInstrumentConverter<?>> { private final HolidaySource _holidaySource; private final ConventionBundleSource _conventionSource; public CapFloorCMSSpreadSecurityConverter(final HolidaySource holidaySource, final ConventionBundleSource conventionSource) { Validate.notNull(holidaySource, "holiday source"); Validate.notNull(conventionSource, "convention source"); _holidaySource = holidaySource; _conventionSource = conventionSource; } //TODO too much is being done in this method - should be in the constructor @Override public FixedIncomeInstrumentConverter<?> visitCapFloorCMSSpreadSecurity(final CapFloorCMSSpreadSecurity capFloorCMSSpreadSecurity) { Validate.notNull(capFloorCMSSpreadSecurity, "cap/floor security"); final double notional = capFloorCMSSpreadSecurity.getNotional(); final ZonedDateTime paymentDate = capFloorCMSSpreadSecurity.getMaturityDate(); //TODO check this final ZonedDateTime accrualStartDate = capFloorCMSSpreadSecurity.getStartDate(); //TODO check this final ZonedDateTime accrualEndDate = capFloorCMSSpreadSecurity.getMaturityDate(); //TODO check this final double accrualFactor = capFloorCMSSpreadSecurity.getDayCount().getDayCountFraction(accrualStartDate, accrualEndDate); final double strike = capFloorCMSSpreadSecurity.getStrike(); final boolean isCap = capFloorCMSSpreadSecurity.isCap(); final ExternalId longId = capFloorCMSSpreadSecurity.getLongId(); final ExternalId shortId = capFloorCMSSpreadSecurity.getShortId(); final Currency currency = capFloorCMSSpreadSecurity.getCurrency(); final Frequency tenor = capFloorCMSSpreadSecurity.getFrequency(); final Calendar calendar = CalendarUtils.getCalendar(_holidaySource, currency); final ConventionBundle longConvention = _conventionSource.getConventionBundle(longId); if (longConvention == null) { throw new OpenGammaRuntimeException("Could not get convention for " + longId); } final IborIndex iborIndex1 = new IborIndex(currency, getTenor(tenor), longConvention.getSettlementDays(), calendar, longConvention.getDayCount(), longConvention.getBusinessDayConvention(), longConvention.isEOMConvention()); final CMSIndex cmsIndex1 = new CMSIndex(longConvention.getPeriod(), longConvention.getDayCount(), iborIndex1, getTenor(tenor)); final ConventionBundle shortConvention = _conventionSource.getConventionBundle(longId); if (shortConvention == null) { throw new OpenGammaRuntimeException("Could not get convention for " + shortId); } final IborIndex iborIndex2 = new IborIndex(currency, getTenor(tenor), shortConvention.getSettlementDays(), calendar, shortConvention.getDayCount(), shortConvention.getBusinessDayConvention(), shortConvention.isEOMConvention()); final CMSIndex cmsIndex2 = new CMSIndex(shortConvention.getPeriod(), shortConvention.getDayCount(), iborIndex2, getTenor(tenor)); return CapFloorCMSSpreadDefinition.from(paymentDate, accrualStartDate, accrualEndDate, accrualFactor, notional, cmsIndex1, cmsIndex2, strike, isCap); } // FIXME: convert frequency to period in a better way private Period getTenor(final Frequency freq) { Period tenor; if (Frequency.ANNUAL_NAME.equals(freq.getConventionName())) { tenor = Period.ofMonths(12); } else if (Frequency.SEMI_ANNUAL_NAME.equals(freq.getConventionName())) { tenor = Period.ofMonths(6); } else if (Frequency.QUARTERLY_NAME.equals(freq.getConventionName())) { tenor = Period.ofMonths(3); } else if (Frequency.MONTHLY_NAME.equals(freq.getConventionName())) { tenor = Period.ofMonths(1); } else { throw new OpenGammaRuntimeException( "Can only handle annual, semi-annual, quarterly and monthly frequencies for cap/floor CMS spreads"); } return tenor; } }
55.075269
153
0.794611
d40c8925aa82188588496ce6ad62cc00b1b2088c
5,003
/* * Project: Speedith.Core * * File name: NullSpiderDiagram.java * Author: Matej Urbas [matej.urbas@gmail.com] * * Copyright © 2011 Matej Urbas * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package speedith.core.lang; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import static speedith.core.i18n.Translations.i18n; /** * Represents an empty spider diagram (it is a tautology and evaluates to '⊤' or * {@code true}). <p>This class is a singleton. To get the only instance of the {@link * NullSpiderDiagram} use the {@link NullSpiderDiagram#getInstance()} * method.</p> <p>Instances of this class (and its derived classes) are * immutable.</p> * * @author Matej Urbas [matej.urbas@gmail.com] */ public class NullSpiderDiagram extends SpiderDiagram { // <editor-fold defaultstate="collapsed" desc="Constants"> /** * The identifier of the null spider diagram in the textual representation * of spider diagrams. <p>This value is used in the textual representation * of spider diagrams (see {@link SpiderDiagram#toString()}).</p> */ public static final String SDTextNullId = "NullSD"; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="The Singleton Instance Method"> /** * Returns the only instance of the null spider diagram. * * @return the only instance of the null spider diagram. */ public static NullSpiderDiagram getInstance() { return SingletonHolder.Instance; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Public Methods"> @Override public SpiderDiagram transform(Transformer t, boolean trackParents) { if (t == null) { throw new IllegalArgumentException(i18n("GERR_NULL_ARGUMENT", "t")); } SpiderDiagram curTransform = t.transform(this, 0, new ArrayList<CompoundSpiderDiagram>(), new ArrayList<Integer>()); return curTransform == null ? this : curTransform; } @Override public int getSubDiagramCount() { return 1; } @Override public SpiderDiagram getSubDiagramAt(int index) { if (index == 0) { return this; } else { throw new IndexOutOfBoundsException(i18n("GERR_INDEX_OUT_OF_BOUNDS")); } } @Override public boolean isValid() { return true; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Iterable Implementation"> @Override public Iterator<SpiderDiagram> iterator() { return new PrimarySpiderDiagram.AtomicSpiderDiagramIterator(this); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Equality"> @Override public boolean equals(Object other) { return this == other || other instanceof NullSpiderDiagram; } @Override public int hashCode() { return 0xb8e9561a; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="The Singleton Holder Class"> private static class SingletonHolder { public static final NullSpiderDiagram Instance = new NullSpiderDiagram(); } // </editor-fold> //Zohreh: Privae to protected // <editor-fold defaultstate="collapsed" desc="Private Constructor"> protected NullSpiderDiagram() { } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Text Conversion Methods"> @Override public void toString(Appendable sb) throws IOException { if (sb == null) { throw new IllegalArgumentException(i18n("GERR_NULL_ARGUMENT", "sb")); } sb.append(SDTextNullId); } @Override public String toString() { try { final StringBuilder sb = new StringBuilder(); toString(sb); return sb.toString(); } catch (IOException ex) { throw new RuntimeException(ex); } } // </editor-fold> }
33.577181
124
0.672596
4015a9219850d38c8d6dc2810ce914888a7f0044
225
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package com.github.badsyntax.gradle; public enum GradleProjectConnectionType { WRAPPER, SPECIFICVERSION, LOCALINSTALLATION, }
25
60
0.8
2ebb734921e94452c4481ec94f8e176b4e834d58
5,023
package com.prowidesoftware.swift.model.mx; import com.prowidesoftware.swift.model.mx.dic.*; import com.prowidesoftware.swift.model.mx.AbstractMX; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import com.prowidesoftware.swift.model.MxSwiftMessage; import com.prowidesoftware.swift.model.mx.MxRead; import com.prowidesoftware.swift.model.mx.MxReadImpl; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Class for tsmt.022.001.01 ISO 20022 message. * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Document", propOrder = { "tsmt02200101" }) @XmlRootElement(name = "Document", namespace = "urn:swift:xsd:tsmt.022.001.01") public class MxTsmt02200101 extends com.prowidesoftware.swift.model.mx.AbstractMX { @XmlElement(name = "tsmt.022.001.01", required = true) protected Tsmt02200101 tsmt02200101; public final static transient String BUSINESS_PROCESS = "tsmt"; public final static transient int FUNCTIONALITY = 22; public final static transient int VARIANT = 1; public final static transient int VERSION = 1; @SuppressWarnings("rawtypes") public final static transient Class[] _classes = new Class[] {BICIdentification1 .class, DocumentIdentification5 .class, MessageIdentification1 .class, MxTsmt02200101 .class, Reason2 .class, RejectedElement1 .class, RejectionReason1Choice.class, SimpleIdentificationInformation.class, Tsmt02200101 .class }; public final static transient String NAMESPACE = "urn:swift:xsd:tsmt.022.001.01"; public MxTsmt02200101() { super(); } /** * Creates the MX object parsing the parameter String with the XML content * */ public MxTsmt02200101(final String xml) { this(); MxTsmt02200101 tmp = parse(xml); tsmt02200101 = tmp.getTsmt02200101(); } /** * Creates the MX object parsing the raw content from the parameter MxSwiftMessage * */ public MxTsmt02200101(final MxSwiftMessage mxSwiftMessage) { this(mxSwiftMessage.message()); } /** * Gets the value of the tsmt02200101 property. * * @return * possible object is * {@link Tsmt02200101 } * */ public Tsmt02200101 getTsmt02200101() { return tsmt02200101; } /** * Sets the value of the tsmt02200101 property. * * @param value * allowed object is * {@link Tsmt02200101 } * */ public MxTsmt02200101 setTsmt02200101(Tsmt02200101 value) { this.tsmt02200101 = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public String getBusinessProcess() { return BUSINESS_PROCESS; } @Override public int getFunctionality() { return FUNCTIONALITY; } @Override public int getVariant() { return VARIANT; } @Override public int getVersion() { return VERSION; } /** * Creates the MX object parsing the raw content from the parameter XML * */ public static MxTsmt02200101 parse(String xml) { return ((MxTsmt02200101) MxReadImpl.parse(MxTsmt02200101 .class, xml, _classes)); } /** * Creates the MX object parsing the raw content from the parameter XML with injected read implementation * @since 9.0.1 * * @param parserImpl an MX unmarshall implementation */ public static MxTsmt02200101 parse(String xml, MxRead parserImpl) { return ((MxTsmt02200101) parserImpl.read(MxTsmt02200101 .class, xml, _classes)); } @Override public String getNamespace() { return NAMESPACE; } @Override @SuppressWarnings("rawtypes") public Class[] getClasses() { return _classes; } /** * Creates an MxTsmt02200101 messages from its JSON representation. * <p> * For generic conversion of JSON into the corresponding MX instance * see {@link AbstractMX#fromJson(String)} * * @since 7.10.2 * * @param json a JSON representation of an MxTsmt02200101 message * @return * a new instance of MxTsmt02200101 */ public final static MxTsmt02200101 fromJson(String json) { return com.prowidesoftware.swift.model.mx.AbstractMX.fromJson(json, MxTsmt02200101 .class); } }
29.203488
311
0.681664
a780f1ab5615b6adb2140e308f1f118986379c33
10,101
/** Copyright © 2020 Ricardo Ferreira (riferrei@riferrei.com) 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.riferrei.kafka.core; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apache.kafka.common.Configurable; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.InvalidConfigurationException; import org.apache.kafka.clients.consumer.internals.AbstractPartitionAssignor; import org.apache.kafka.common.utils.Utils; public class BucketPriorityAssignor extends AbstractPartitionAssignor implements Configurable { private AbstractPartitionAssignor fallback; private BucketPriorityConfig config; private Map<String, Bucket> buckets; private int lastPartitionCount; @Override public String name() { return "bucket-priority"; } @Override public void configure(Map<String, ?> configs) { config = new BucketPriorityConfig(configs); List<Integer> bucketAlloc = new ArrayList<>(config.allocation().size()); for (String allocItem : config.allocation()) { allocItem = allocItem.replaceAll("%", "").trim(); bucketAlloc.add(Integer.parseInt(allocItem)); } if (config.buckets().size() != bucketAlloc.size()) { throw new InvalidConfigurationException("The bucket allocation " + "doesn't match with the number of buckets configured."); } int oneHundredPerc = bucketAlloc.stream() .mapToInt(Integer::intValue) .sum(); if (oneHundredPerc != 100) { throw new InvalidConfigurationException("The bucket allocation " + "is incorrect. The sum of all buckets needs to be 100."); } try { fallback = config.getConfiguredInstance( BucketPriorityConfig.FALLBACK_ASSIGNOR_CONFIG, AbstractPartitionAssignor.class); } catch (Exception ex) { throw new InvalidConfigurationException("The fallback " + "assignor configured is invalid.", ex); } buckets = new LinkedHashMap<>(); for (int i = 0; i < config.buckets().size(); i++) { String bucketName = config.buckets().get(i).trim(); buckets.put(bucketName, new Bucket(bucketAlloc.get(i))); } // Sort the buckets with higher allocation to come // first than the others. This will help later during // the allocation if unassigned partitions are found. buckets = buckets.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); } @Override public ByteBuffer subscriptionUserData(Set<String> topics) { ByteBuffer userData = null; for (String topic : topics) { if (topic.equals(config.topic())) { String bucket = config.bucket(); Charset charset = StandardCharsets.UTF_8; userData = charset.encode(bucket); break; } } return userData; } @Override public Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions) { int numPartitions = partitionsPerTopic.get(config.topic()); // Check if the # of partitions has changed // and trigger an update if that happened. if (lastPartitionCount != numPartitions) { updatePartitionsAssignment(numPartitions); lastPartitionCount = numPartitions; } Map<String, List<TopicPartition>> assignments = new LinkedHashMap<>(); Map<String, List<String>> consumersPerBucket = new LinkedHashMap<>(); Map<String, Subscription> otherTopicsSubscriptions = new LinkedHashMap<>(); for (String consumer : subscriptions.keySet()) { Subscription subscription = subscriptions.get(consumer); if (subscription.topics().contains(config.topic())) { assignments.put(consumer, new ArrayList<>()); ByteBuffer userData = subscription.userData(); Charset charset = StandardCharsets.UTF_8; String bucket = charset.decode(userData).toString(); if (buckets.containsKey(bucket)) { if (consumersPerBucket.containsKey(bucket)) { List<String> consumers = consumersPerBucket.get(bucket); consumers.add(consumer); } else { List<String> consumers = new ArrayList<>(); consumers.add(consumer); consumersPerBucket.put(bucket, consumers); } } } else { otherTopicsSubscriptions.put(consumer, subscription); } } // Evenly distribute the partitions across the // available consumers in a per-bucket basis. AtomicInteger counter = new AtomicInteger(-1); for (Map.Entry<String, Bucket> bucket : buckets.entrySet()) { List<String> consumers = consumersPerBucket.get(bucket.getKey()); // Check if the bucket has consumers available... if (consumers != null && !consumers.isEmpty()) { for (TopicPartition partition : bucket.getValue().getPartitions()) { int nextValue = counter.incrementAndGet(); int index = Utils.toPositive(nextValue) % consumers.size(); String consumer = consumers.get(index); assignments.get(consumer).add(partition); } } } // If there are subscriptions for topics that // are not based on buckets then use the fallback // assignor to create their partition assignments. if (!otherTopicsSubscriptions.isEmpty()) { Map<String, List<TopicPartition>> fallbackAssignments = fallback.assign(partitionsPerTopic, otherTopicsSubscriptions); assignments.putAll(fallbackAssignments); } return assignments; } private void updatePartitionsAssignment(int numPartitions) { List<TopicPartition> partitions = partitions(config.topic(), numPartitions); if (partitions.size() < buckets.size()) { StringBuilder message = new StringBuilder(); message.append("The number of partitions available for the topic '"); message.append(config.topic()).append("' is incompatible with the "); message.append("number of buckets. It needs to be at least "); message.append(buckets.size()).append("."); throw new InvalidConfigurationException(message.toString()); } // Sort partitions in ascendent order since // the partitions will be mapped into the // buckets from partition-0 to partition-n. partitions = partitions.stream() .sorted(Comparator.comparing(TopicPartition::partition)) .collect(Collectors.toList()); // Design the layout of the distribution int distribution = 0; Map<String, Integer> layout = new LinkedHashMap<>(); for (Map.Entry<String, Bucket> entry : buckets.entrySet()) { int bucketSize = entry.getValue().size(partitions.size()); layout.put(entry.getKey(), bucketSize); distribution += bucketSize; } // Check if there are unassigned partitions. // If so then distribute them over the buckets // starting from the top to bottom until there // are no partitions left. int remaining = partitions.size() - distribution; if (remaining > 0) { AtomicInteger counter = new AtomicInteger(-1); List<String> availableBuckets = new ArrayList<>(); buckets.keySet().stream().forEach(bucket -> { availableBuckets.add(bucket); }); while (remaining > 0) { int nextValue = counter.incrementAndGet(); int index = Utils.toPositive(nextValue) % availableBuckets.size(); String bucketName = availableBuckets.get(index); int bucketSize = layout.get(bucketName); layout.put(bucketName, ++bucketSize); remaining--; } } // Finally assign the available partitions to buckets int partition = -1; TopicPartition topicPartition = null; bucketAssign: for (Map.Entry<String, Bucket> entry : buckets.entrySet()) { int bucketSize = layout.get(entry.getKey()); entry.getValue().getPartitions().clear(); for (int i = 0; i < bucketSize; i++) { topicPartition = new TopicPartition(config.topic(), ++partition); entry.getValue().getPartitions().add(topicPartition); if (partition == partitions.size() - 1) { break bucketAssign; } } } } }
44.10917
95
0.613504
92541f473b273aaf996f0892b98126c36f4c7cb4
3,024
/* * Copyright 2021 Ian Jones. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package api.equinix.javasdk.networkedge.client.internal.implementation; import api.equinix.javasdk.core.client.ClientBase; import api.equinix.javasdk.core.http.Utils; import api.equinix.javasdk.core.http.request.EquinixRequest; import api.equinix.javasdk.core.http.response.EquinixResponse; import api.equinix.javasdk.core.enums.RequestType; import api.equinix.javasdk.networkedge.client.RequestBuilder; import api.equinix.javasdk.networkedge.client.implementation.NetworkEdgeConfigImpl; import api.equinix.javasdk.networkedge.client.internal.PricingClient; import api.equinix.javasdk.networkedge.model.json.Pricing; import api.equinix.javasdk.networkedge.model.json.VPNJson; import java.util.List; import java.util.Map; /** * <p>PricingClientImpl class.</p> * * @author ianjones * @version $Id: $Id */ public class PricingClientImpl extends ClientBase implements PricingClient { /** * <p>Constructor for PricingClientImpl.</p> * * @param configClient a {@link api.equinix.javasdk.networkedge.client.implementation.NetworkEdgeConfigImpl} object. */ public PricingClientImpl(NetworkEdgeConfigImpl configClient) { super(configClient, "NetworkEdge", "Pricing"); } /** * {@inheritDoc} * * <p>getPricing.</p> */ public Pricing getPricing(RequestBuilder.Pricing requestBuilder) { Map<String, List<String>> qParams = Utils.newMap(requestBuilder); EquinixRequest<Pricing> equinixRequest = this.buildRequestWithQueryParams("GetPricing", RequestType.SINGLE, qParams, Pricing.getSingleTypeRef()); EquinixResponse<Pricing> equinixResponse = this.invoke(equinixRequest); return Utils.handleSingletonResponse(equinixResponse, equinixRequest); } /** * <p>getPricing.</p> * * @param deviceUuid a {@link java.lang.String} object. * @return a {@link api.equinix.javasdk.networkedge.model.json.Pricing} object. */ public Pricing getPricing(String deviceUuid) { Map<String, List<String>> qParams = Utils.singleParamMap("virtualDeviceUuid", deviceUuid); EquinixRequest<VPNJson> equinixRequest = this.buildRequestWithQueryParams("GetPricing", RequestType.SINGLE, qParams, Pricing.getSingleTypeRef()); EquinixResponse<VPNJson> equinixResponse = this.invoke(equinixRequest); return Utils.handleSingletonResponse(equinixResponse, equinixRequest); } }
39.272727
153
0.746362
926acd3ba5679929b079301aaa796bb1f25697e4
292
package at.uibk.dps.ee.enactables.local.utility; /** * Constants used by the utility enactables. * * @author Fedor Smirnov */ public final class ConstantsUtility { public static final double epsilon = 0.000_000_001; /** * No constructor */ private ConstantsUtility() {} }
17.176471
53
0.695205
3046569f63b4ee5aad45ba85390b7dfe6c7539b2
164
package com.silverknife.meizhi.features.main; import com.silvericekey.skutilslibrary.base.BasePresenter; public interface MainPresenter extends BasePresenter { }
23.428571
58
0.847561
6e5abd3cba210f14c97926e2b8d5b066edfa64aa
349
package cn.gitlab.virtualcry.sapjco.server.handler; import com.sap.conn.jco.JCoFunctionTemplate; /** * Define SAP RFC function. * * @author VirtualCry */ public interface DynamicFunctionHandler { /** * Register sap rfc function. * @return The definition of SAP RFC function. */ JCoFunctionTemplate registerSapFunc(); }
19.388889
51
0.704871
3b6996ceb39a35e0144137473c64cea580886906
1,747
package org.spacehq.mc.auth; import org.spacehq.mc.auth.properties.PropertyMap; import java.util.UUID; public class GameProfile { private UUID id; private String name; private PropertyMap properties = new PropertyMap(); private boolean legacy; public GameProfile(String id, String name) { this(id == null || id.equals("") ? null : UUID.fromString(id), name); } public GameProfile(UUID id, String name) { if(id == null && (name == null || name.equals(""))) { throw new IllegalArgumentException("Name and ID cannot both be blank"); } else { this.id = id; this.name = name; } } public UUID getId() { return this.id; } public String getIdAsString() { return this.id != null ? this.id.toString() : ""; } public String getName() { return this.name; } public PropertyMap getProperties() { return this.properties; } public boolean isLegacy() { return this.legacy; } public boolean isComplete() { return this.id != null && this.name != null && !this.name.equals(""); } @Override public boolean equals(Object o) { if(this == o) { return true; } else if(o != null && this.getClass() == o.getClass()) { GameProfile that = (GameProfile) o; return (this.id != null ? this.id.equals(that.id) : that.id == null) && (this.name != null ? this.name.equals(that.name) : that.name == null); } else { return false; } } @Override public int hashCode() { int result = this.id != null ? this.id.hashCode() : 0; result = 31 * result + (this.name != null ? this.name.hashCode() : 0); return result; } @Override public String toString() { return "GameProfile{id=" + this.id + ", name=" + this.name + ", properties=" + this.properties + ", legacy=" + this.legacy + "}"; } }
22.986842
145
0.639382
89e23a6987f169925fc3b3af1b2d2d2d5eda5414
188
/** * Author: Alexander Gatsenko (alexandr.gatsenko@gmail.com) * Created: 2020-03-14 */ package com.agatsenko.mongo.mapper.impl; public abstract class FieldCollectionReaderWriter { }
18.8
59
0.755319
4bcad1f0f932066f43df7a1a0d2d9498ab24acae
585
package io.serializable; import java.io.FileInputStream; import java.io.ObjectInputStream; /** * @author zhouT * @date 2018/12/17 13:44 */ public class ReadObject { public static void main(String[] args) { try { // 创建一个ObjectInputStream输入流 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt")); // 从输入流中读取一个java对象,并将其强制转换为Person类 Person person = (Person) ois.readObject(); System.out.println("名字为:" + person.getName() + "\n年龄为:" + person.getAge()); } catch (Exception e) { e.printStackTrace(); } } }
24.375
87
0.664957
f4d6b803acac9096e7b37268ee0f68d2c045e2e5
2,180
package com.thinkgem.jeesite.test; import java.io.IOException; import java.sql.DriverManager; import java.util.ArrayList; import java.util.Base64; import java.util.List; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.junit.Test; import com.thinkgem.jeesite.base.BaseTest; import com.thinkgem.jeesite.common.utils.JedisUtils; /** * * 项目名称:JeeSite 类名称:TestEnvironment 类描述: 基础运行环境测试 创建人:Administrator * 创建时间:2018年4月21日 下午7:23:08 修改人:Administrator 修改时间:2018年4月21日 下午7:23:08 修改备注: * * @version * */ public class TestEnvironment extends BaseTest { @org.junit.Test public void mysqlTest() throws Exception { String url = "jdbc:mysql://192.168.40.129:3306/mengmengyuan?useUnicode=true&characterEncoding=utf-8"; // 连接数据库(kucun是数据库名) String name = "root";// 连接mysql的用户名 String pwd = "123";// 连接mysql的密码 Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection conn = DriverManager.getConnection(url, name, pwd); System.out.println(conn); } @Test public void JedisTest() { JedisUtils.set("key", "value", 0); System.out.println(JedisUtils.get("key")); } @Test public void zookeeperTest() throws IOException, KeeperException, InterruptedException { String hostPort = "192.168.40.129:2181"; String zpath = "/"; List<String> zooChildren = new ArrayList<String>(); ZooKeeper zk = new ZooKeeper(hostPort, 2000, null); if (zk != null) { try { zooChildren = zk.getChildren(zpath, false); for (String child : zooChildren) { // print the children System.out.println(child); } } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { System.out.println("renjianping".getBytes()); byte[] encode = Base64.getEncoder().encode("renjianping".getBytes()); System.out.println(encode); } }
29.066667
130
0.627982
a76ff17a08c663f3397e7b38f915b0dd0727b3da
16,764
/* * * Copyright 2001-2004 The Ant-Contrib project * * 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.sf.antcontrib.cpptasks; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Execute; import org.apache.tools.ant.taskdefs.LogStreamHandler; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.types.Environment; import java.io.File; import java.io.IOException; import java.util.Locale; import java.util.StringTokenizer; import java.util.Vector; /** * Some utilities used by the CC and Link tasks. * * @author Adam Murdoch * @author Curt Arnold */ public class CUtil { public static final String STANDARD_EXCUSE = "Not an actual task, but looks like one for documentation purposes"; /** * A class that splits a white-space, comma-separated list into a String * array. Used for task attributes. */ public static final class StringArrayBuilder { private final String[] values; public StringArrayBuilder(String value) { // Split the defines up StringTokenizer tokens = new StringTokenizer(value, ", "); Vector<String> valueList = new Vector<String>(); while (tokens.hasMoreTokens()) { String val = tokens.nextToken().trim(); if (val.isEmpty()) { continue; } valueList.addElement(val); } values = valueList.toArray(new String[0]); } public String[] getValue() { return values; } } /** * Checks a array of names for non existent or non directory entries and * nulls them out. * * @param names array of String * @return Count of non-null elements */ public static int checkDirectoryArray(String[] names) { int count = 0; for (int i = 0; i < names.length; i++) { if (names[i] != null) { File dir = new File(names[i]); if (dir.exists() && dir.isDirectory()) { count++; } else { names[i] = null; } } } return count; } /** * Extracts the basename of a file, removing the extension, if present * * @param file File * @return String */ public static String getBasename(File file) { String path = file.getPath(); // Remove the extension String basename = file.getName(); int pos = basename.lastIndexOf('.'); if (pos != -1) { basename = basename.substring(0, pos); } return basename; } /** * Gets the parent directory for the executable file name using the current * directory and system executable path * * @param exeName Name of executable such as "cl.exe" * @return parent directory or null if not located */ public static File getExecutableLocation(String exeName) { // // must add current working directory to the // from of the path from the "path" environment variable File currentDir = new File(System.getProperty("user.dir")); if (new File(currentDir, exeName).exists()) { return currentDir; } for (File file : getPathFromEnvironment("PATH", File.pathSeparator)) { if (new File(file, exeName).exists()) { return file; } } return null; } /** * Extracts the parent of a file * * @param path String * @return String */ public static String getParentPath(String path) { int pos = path.lastIndexOf(File.separator); if (pos <= 0) { return null; } return path.substring(0, pos); } /** * Returns an array of File for each existing directory in the specified * environment variable * * @param envVariable environment variable name such as "LIB" or "INCLUDE" * @param delim delimiter used to separate parts of the path, typically ";" * or ":" * @return array of File's for each part that is an existing directory */ public static File[] getPathFromEnvironment(String envVariable, String delim) { // OS/4000 does not support the env command. if (System.getProperty("os.name").equals("OS/400")) { return new File[]{}; } String match = envVariable.concat("="); for (String e : Execute.getProcEnvironment()) { String entry = e.trim(); if (entry.length() > match.length()) { String entryFrag = entry.substring(0, match.length()); if (entryFrag.equalsIgnoreCase(match)) { String path = entry.substring(match.length()); return parsePath(path, delim); } } } return new File[0]; } /** * Returns a relative path for the targetFile relative to the base * directory. * * @param base base directory as returned by File.getCanonicalPath() * @param targetFile target file * @return relative path of target file. Returns targetFile if there were * no commonalities between the base and the target */ public static String getRelativePath(final String base, final File targetFile) { try { // // remove trailing file separator // String canonicalBase = base; if (base.charAt(base.length() - 1) != File.separatorChar) { canonicalBase = base + File.separatorChar; } // // get canonical name of target // String canonicalTarget; if (System.getProperty("os.name").equals("OS/400")) { canonicalTarget = targetFile.getPath(); } else { canonicalTarget = targetFile.getCanonicalPath(); } if (canonicalBase.startsWith(canonicalTarget + File.separatorChar)) { canonicalTarget = canonicalTarget + File.separator; } if (canonicalTarget.equals(canonicalBase)) { return "."; } // // see if the prefixes are the same // if (canonicalBase.startsWith("\\\\")) { // // UNC file name, if target file doesn't also start with same // server name, don't go there int endPrefix = canonicalBase.indexOf('\\', 2); String prefix1 = canonicalBase.substring(0, endPrefix); String prefix2 = canonicalTarget.substring(0, endPrefix); if (!prefix1.equals(prefix2)) { return canonicalTarget; } } else if (canonicalBase.startsWith(":\\", 1)) { int endPrefix = 2; String prefix1 = canonicalBase.substring(0, endPrefix); String prefix2 = canonicalTarget.substring(0, endPrefix); if (!prefix1.equals(prefix2)) { return canonicalTarget; } } else if (canonicalBase.charAt(0) == '/' && canonicalTarget.charAt(0) != '/') { return canonicalTarget; } char separator = File.separatorChar; int lastCommonSeparator = -1; int minLength = canonicalBase.length(); if (canonicalTarget.length() < minLength) { minLength = canonicalTarget.length(); } // // walk to the shorter of the two paths // finding the last separator they have in common for (int i = 0; i < minLength; i++) { if (canonicalTarget.charAt(i) != canonicalBase.charAt(i)) { break; } if (canonicalTarget.charAt(i) == separator) { lastCommonSeparator = i; } } StringBuilder relativePath = new StringBuilder(50); // // walk from the first difference to the end of the base // adding "../" for each separator encountered // for (int i = lastCommonSeparator + 1; i < canonicalBase.length(); i++) { if (canonicalBase.charAt(i) == separator) { if (relativePath.length() > 0) { relativePath.append(separator); } relativePath.append(".."); } } if (canonicalTarget.length() > lastCommonSeparator + 1) { if (relativePath.length() > 0) { relativePath.append(separator); } relativePath.append(canonicalTarget.substring(lastCommonSeparator + 1)); } return relativePath.toString(); } catch (IOException ex) { } return targetFile.toString(); } public static boolean isActive(Project p, String ifCond, String unlessCond) throws BuildException { if (ifCond != null) { String ifValue = p.getProperty(ifCond); if (ifValue == null) { return false; } else { if (ifValue.equals("false") || ifValue.equals("no")) { throw new BuildException("if condition \"" + ifCond + "\" has suspicious value \"" + ifValue); } } } if (unlessCond != null) { String unlessValue = p.getProperty(unlessCond); if (unlessValue != null) { if (unlessValue.equals("false") || unlessValue.equals("no")) { throw new BuildException("unless condition \"" + unlessCond + "\" has suspicious value \"" + unlessValue); } return false; } } return true; } /** * Parse a string containing directories into an File[] * * @param path path string, for example ".;c:\something\include" * @param delim delimiter, typically ; or : * @return an array of File */ public static File[] parsePath(String path, String delim) { Vector<File> libpaths = new Vector<File>(); int startPos = 0; while (startPos < path.length()) { int delimPos = path.indexOf(delim, startPos); if (delimPos < 0) { delimPos = path.length(); } // // don't add an entry for zero-length paths // if (delimPos > startPos) { File dir = new File(path.substring(startPos, delimPos)); if (dir.exists() && dir.isDirectory()) { libpaths.addElement(dir); } } startPos = delimPos + delim.length(); } return libpaths.toArray(new File[0]); } /** * This method is exposed so test classes can overload and test the * arguments without actually spawning the compiler * * @param task CCTask * @param workingDir File * @param cmdline an array of String * @param newEnvironment boolean * @param env Environment * @return int * @throws BuildException if anything goes wrong */ public static int runCommand(CCTask task, File workingDir, String[] cmdline, boolean newEnvironment, Environment env) throws BuildException { try { task.log(Commandline.toString(cmdline), Project.MSG_VERBOSE); Execute exe = new Execute(new LogStreamHandler(task, Project.MSG_INFO, Project.MSG_ERR)); if (System.getProperty("os.name").equals("OS/390")) { exe.setVMLauncher(false); } exe.setAntRun(task.getProject()); exe.setCommandline(cmdline); exe.setWorkingDirectory(workingDir); if (env != null) { String[] environment = env.getVariables(); if (environment != null) { for (String s : environment) { task.log("Setting environment variable: " + s, Project.MSG_VERBOSE); } } exe.setEnvironment(environment); } exe.setNewenvironment(newEnvironment); return exe.execute(); } catch (IOException exc) { throw new BuildException("Could not launch " + cmdline[0] + ": " + exc, task.getLocation()); } } /** * Replaces any embedded quotes in the string so that the value can be * placed in an attribute in an XML file * * @param attrValue value to be expressed * @return equivalent attribute literal */ public static String xmlAttribEncode(String attrValue) { StringBuilder buf = new StringBuilder(attrValue); int quotePos; for (quotePos = -1; (quotePos = buf.toString().indexOf("\"", quotePos + 1)) >= 0; ) { buf.deleteCharAt(quotePos); buf.insert(quotePos, "&quot;"); quotePos += 5; } for (quotePos = -1; (quotePos = buf.toString().indexOf("<", quotePos + 1)) >= 0; ) { buf.deleteCharAt(quotePos); buf.insert(quotePos, "&lt;"); quotePos += 3; } for (quotePos = -1; (quotePos = buf.toString().indexOf(">", quotePos + 1)) >= 0; ) { buf.deleteCharAt(quotePos); buf.insert(quotePos, "&gt;"); quotePos += 3; } return buf.toString(); } public final static int FILETIME_EPSILON = 500; /** * Determines whether time1 is earlier than time2 * to a degree that file system time truncation is not significant. * * @param time1 long first time value * @param time2 long second time value * @return boolean if first time value is earlier than second time value. * If the values are within the rounding error of the file system return false. */ public static boolean isSignificantlyBefore(long time1, long time2) { return (time1 + FILETIME_EPSILON) < time2; } /** * Determines whether time1 is later than time2 * to a degree that file system time truncation is not significant. * * @param time1 long first time value * @param time2 long second time value * @return boolean if first time value is later than second time value. * If the values are within the rounding error of the file system return false. */ public static boolean isSignificantlyAfter(long time1, long time2) { return time1 > (time2 + FILETIME_EPSILON); } public static String toWindowsPath(final String path) { if (File.separatorChar == '\\' || !path.contains(File.separator)) { return path; } return path.replace(File.separator, "\\"); } public static String toUnixPath(final String path) { if (File.separatorChar == '/' || !path.contains(File.separator)) { return path; } return path.replace(File.separator, "/"); } /** * Determines if source file has a system path, * that is part of the compiler or platform. * * @param source source, may not be null. * @return true is source file appears to be system library * and its path should be discarded. */ public static boolean isSystemPath(final File source) { String lcPath = source.getAbsolutePath().toLowerCase(Locale.US); return lcPath.contains("platformsdk") || lcPath.contains("microsoft") || "/usr/include".equals(lcPath) || "/usr/lib".equals(lcPath) || "/usr/local/include".equals(lcPath) || "/usr/local/lib".equals(lcPath); } }
36.60262
97
0.551241
56343713f65e01086523050604e4b87e02c5086c
690
package br.com.diovani.golden.raspberry.awards.deserializer; import java.io.IOException; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; public class BooleanCSVDeserializer extends JsonDeserializer<Boolean> { @Override public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException { switch (p.getText()) { case "yes": case "Yes": case "YES": case "YEs": case "yES": case "y": case "Y": case "1": return true; default: return false; } } }
21.5625
109
0.753623
e895722f5cc6fef7b183d555232aad221a1e6c9c
4,318
package model; import services.TgApi; import utils.BMasked; import utils.Optioned; import utils.Strings; import java.nio.file.Paths; import java.util.UUID; import static utils.TextUtils.notNull; /** * @author Denis Danilin | denis@danilin.name * 01.05.2020 * tfs ☭ sweat and blood */ public class TFile implements Comparable<TFile>, Optioned { public String uniqId; private UUID id, parentId; private long owner; public String refId; public ContentType type; public String name; private String path; private int options; private boolean rw; public TgApi.Button toButton(final int idx) { return new TgApi.Button( (isDir() ? Strings.Uni.folder + " " : "") + name, (isDir() ? CommandType.openDir : isFile() ? CommandType.openFile : CommandType.openLabel).toString() + idx ); } public TgApi.Button toSearchedButton(final int pathSkip, final int idx) { final String label = path.substring(pathSkip); return new TgApi.Button( (isDir() ? Strings.Uni.folder + " " : "") + label, (isDir() ? CommandType.openSearchedDir : isFile() ? CommandType.openSearchedFile : CommandType.openSearchedLabel).toString() + idx ); } public String parentPath() { return Paths.get(path).getParent().toString(); } public boolean isDir() { return type == ContentType.DIR; } public boolean isFile() { return type != ContentType.DIR && type != ContentType.LABEL; } @Override public int compareTo(final TFile o) { return id.compareTo(o.id); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final TFile file = (TFile) o; return id.equals(file.id); } @Override public int hashCode() { return id.hashCode(); } // getters/setters public UUID getId() { return id; } public void setId(final UUID id) { this.id = id; } public UUID getParentId() { return parentId; } public void setParentId(final UUID parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getRefId() { return refId; } public void setRefId(final String refId) { this.refId = refId; } public ContentType getType() { return type; } public void setType(final ContentType type) { this.type = type; } public String getPath() { return notNull(path, "/"); } public void setPath(final String path) { this.path = path; } public boolean isLabel() { return type == ContentType.LABEL; } public int getOptions() { return options; } public void setOptions(final int options) { this.options = options; } public long getOwner() { return owner; } public void setOwner(final long owner) { this.owner = owner; } public boolean isRw() { return rw; } public void setRw(final boolean rw) { this.rw = rw; } public void setLocked() { Optz.locked.set(this); } public boolean isSharesRoot() { return Optz.sharesRoot.is(this); } public void setSharesRoot() { Optz.sharesRoot.set(this); } public void setShareFor(final long shareOwner) { Optz.shareFor.set(this); refId = String.valueOf(shareOwner); } public boolean isShareFor() { return Optz.shareFor.is(this); } public boolean isLocked() { return Optz.locked.is(this); } public void setUnlocked() { Optz.locked.remove(this); } enum Optz implements BMasked { unused, locked, sharesRoot, shareFor, unused2 } }
21.698492
77
0.551181
d8d4203c2e309b419d616dabaaef13f7d22530e1
2,997
package me.dylanmullen.agar.window.input; import java.awt.Dimension; import java.util.ArrayList; import java.util.List; import org.joml.Vector2f; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWCursorPosCallbackI; import org.lwjgl.glfw.GLFWMouseButtonCallbackI; public class MouseHandler { private long windowRef; private List<Button> buttons; private Vector2f center; private Vector2f mousePosition; private Vector2f lastPosition; private Dimension windowDimensions; public MouseHandler(Dimension windowDimensions, long windowRef) { this.windowDimensions = windowDimensions; this.windowRef = windowRef; this.center = new Vector2f(windowDimensions.width / 2, windowDimensions.height / 2); this.mousePosition = new Vector2f(); this.lastPosition = new Vector2f(); this.buttons = new ArrayList<Button>(); init(); } private void init() { GLFW.glfwSetMouseButtonCallback(windowRef, new GLFWMouseButtonCallbackI() { @Override public void invoke(long window, int button, int action, int mods) { if (!isButton(button)) { buttons.add(new Button(button)); } getMouseButton(button).setClicked(action); } }); GLFW.glfwSetCursorPosCallback(windowRef, new GLFWCursorPosCallbackI() { @Override public void invoke(long window, double xpos, double ypos) { if (lastPosition.x != xpos || lastPosition.y != ypos) lastPosition.set(mousePosition.x, mousePosition.x); mousePosition = mousePosition.set(xpos, ypos); } }); } public Vector2f convertToOpenGLCoords() { float oX = (float) (mousePosition.x * 2) / windowDimensions.width - 1; float oY = (float) (mousePosition.y * 2) / windowDimensions.height - 1; return new Vector2f(oX, oY); } public boolean isPressed(int code) { Button button = getMouseButton(code); if (button == null) return false; else return button.isClicked(); } private Button getMouseButton(int code) { try { return buttons.stream().filter(e -> e.getButtonCode() == code).findFirst().get(); } catch (Exception e) { return null; } } private boolean isButton(int code) { return buttons.stream().filter(e -> e.getButtonCode() == code).findFirst().isPresent(); } public Vector2f getLastPosition() { return lastPosition; } public Vector2f getDirectionFromCenter() { Vector2f position = new Vector2f(mousePosition); position.sub(center); position.normalize(); return position; } public Vector2f getDirectionFrom(Vector2f vector) { Vector2f position = new Vector2f(mousePosition); position.sub(vector); position.normalize(); return position; } public float distanceFromCenter() { return center.distance(mousePosition); } public Vector2f center() { return new Vector2f(0, -0); } public float getXChange() { return lastPosition.x - mousePosition.x; } public float getYChange() { return lastPosition.y - mousePosition.y; } public Vector2f getMousePosition() { return mousePosition; } }
21.407143
89
0.716383
cd62e43295fde6ce573f19ba88775f919d08a9c2
13,241
/** * Copyright 2014 Netflix, 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.netflix.config; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class that provides the chaining functionality of dynamic properties. * The idea is that the head property holds the current up-to-date value of the property and the "next" property * in the chain serves as the default if the head property value does not exist or is not acceptable. * Concrete implementation is available for IntProperty, StringProperty, BooleanProperty and FloatProperty. * * <p>For example * * <pre> * {@code DynamicStringProperty pString = DynamicPropertyFactory.getInstance().getStringProperty("defaultString", "default-default"); ChainedDynamicProperty.StringProperty fString = new ChainedDynamicProperty.StringProperty("overrideString", pString); assertTrue("default-default".equals(fString.get())); ConfigurationManager.getConfigInstance().setProperty("defaultString", "default"); assertTrue("default".equals(fString.get())); ConfigurationManager.getConfigInstance().setProperty("overrideString", "override"); assertTrue("override".equals(fString.get())); ConfigurationManager.getConfigInstance().clearProperty("overrideString"); assertTrue("default".equals(fString.get())); ConfigurationManager.getConfigInstance().clearProperty("defaultString"); assertTrue("default-default".equals(fString.get())); * } * </pre> * * @see IntProperty * @see StringProperty * @see BooleanProperty * @see FloatProperty */ public class ChainedDynamicProperty { private static final Logger logger = LoggerFactory.getLogger(ChainedDynamicProperty.class); public static abstract class ChainLink<T> implements Property<T> { private final AtomicReference<ChainLink<T>> pReference; private final ChainLink<T> next; private final List<Runnable> callbacks; private final T defaultValue; /** * @return Boolean */ public abstract boolean isValueAcceptable(); /** * Get the property referenced by this ChainLink * @return the referenced property */ protected abstract Property<T> getReferencedProperty(); /** * Used for end node */ public ChainLink(T defaultValue) { next = null; pReference = new AtomicReference<ChainLink<T>>(this); callbacks = new ArrayList<Runnable>(); this.defaultValue = defaultValue; } /** * @param nextProperty */ public ChainLink(ChainLink<T> nextProperty) { next = nextProperty; pReference = new AtomicReference<ChainLink<T>>(next); callbacks = new ArrayList<Runnable>(); this.defaultValue = nextProperty.getDefaultValue(); } protected void checkAndFlip() { // in case this is the end node if(next == null) { pReference.set(this); return; } if (this.isValueAcceptable()) { logger.info("Flipping property: " + getName() + " to use it's current value:" + getValue()); pReference.set(this); } else { logger.info("Flipping property: " + getName() + " to use NEXT property: " + next); pReference.set(next); } for (Runnable r : callbacks) { r.run(); } } /** * @return T */ public T get() { if (pReference.get() == this) { return this.getValue(); } else { return pReference.get().get(); } } @Override public T getValue() { return getReferencedProperty().getValue(); } @Override public T getDefaultValue() { return defaultValue; } @Override public String getName() { return getReferencedProperty().getName(); } @Override public long getChangedTimestamp() { if (pReference.get() == this) { return getReferencedProperty().getChangedTimestamp(); } else { return pReference.get().getChangedTimestamp(); } } /** * @param r */ @Override public void addCallback(Runnable r) { callbacks.add(r); } /** * Remove callback from callbacks list */ @Override public void removeAllCallbacks() { callbacks.clear(); } /** * @return String */ @Override public String toString() { return getName() + " = " + get(); } } public static class StringProperty extends ChainLink<String> { private final DynamicStringProperty sProp; private Runnable callback; public StringProperty(DynamicStringProperty sProperty) { super(sProperty.getDefaultValue()); sProp = sProperty; } public StringProperty(String name, DynamicStringProperty sProperty) { this(name, new StringProperty(sProperty)); } public StringProperty(String name, StringProperty next) { super(next); // setup next pointer sProp = DynamicPropertyFactory.getInstance().getStringProperty(name, null); callback = new Runnable() { @Override public void run() { logger.info("Property changed: '" + getName() + " = " + getValue() + "'"); checkAndFlip(); } }; sProp.addCallback(callback); checkAndFlip(); } @Override public boolean isValueAcceptable() { return (sProp.get() != null); } @Override protected Property<String> getReferencedProperty() { return sProp; } @Override public void removeAllCallbacks() { super.removeAllCallbacks(); sProp.prop.removeCallback(callback); } } public static class IntProperty extends ChainLink<Integer> { private final DynamicIntProperty sProp; private Runnable callback; public IntProperty(DynamicIntProperty sProperty) { super(sProperty.getDefaultValue()); sProp = sProperty; } public IntProperty(String name, DynamicIntProperty sProperty) { this(name, new IntProperty(sProperty)); } public IntProperty(String name, IntProperty next) { super(next); // setup next pointer sProp = DynamicPropertyFactory.getInstance().getIntProperty(name, Integer.MIN_VALUE); callback = new Runnable() { @Override public void run() { logger.info("Property changed: '" + getName() + " = " + getValue() + "'"); checkAndFlip(); } }; sProp.addCallback(callback); checkAndFlip(); } @Override public boolean isValueAcceptable() { return (sProp.get() != Integer.MIN_VALUE); } @Override protected Property<Integer> getReferencedProperty() { return sProp; } @Override public void removeAllCallbacks() { super.removeAllCallbacks(); sProp.prop.removeCallback(callback); } } public static class LongProperty extends ChainLink<Long> { private final DynamicLongProperty sProp; private Runnable callback; public LongProperty(DynamicLongProperty sProperty) { super(sProperty.getDefaultValue()); sProp = sProperty; } public LongProperty(String name, DynamicLongProperty sProperty) { this(name, new LongProperty(sProperty)); } public LongProperty(String name, LongProperty next) { super(next); // setup next pointer sProp = DynamicPropertyFactory.getInstance().getLongProperty(name, Long.MIN_VALUE); callback = new Runnable() { @Override public void run() { logger.info("Property changed: '" + getName() + " = " + getValue() + "'"); checkAndFlip(); } }; sProp.addCallback(callback); checkAndFlip(); } @Override public boolean isValueAcceptable() { return (sProp.get() != Long.MIN_VALUE); } @Override protected Property<Long> getReferencedProperty() { return sProp; } @Override public void removeAllCallbacks() { super.removeAllCallbacks(); sProp.prop.removeCallback(callback); } } public static class FloatProperty extends ChainLink<Float> { private final DynamicFloatProperty sProp; private Runnable callback; public FloatProperty(DynamicFloatProperty sProperty) { super(sProperty.getDefaultValue()); sProp = sProperty; } public FloatProperty(String name, DynamicFloatProperty sProperty) { this(name, new FloatProperty(sProperty)); } public FloatProperty(String name, FloatProperty next) { super(next); // setup next pointer sProp = DynamicPropertyFactory.getInstance().getFloatProperty(name, Float.MIN_VALUE); callback = new Runnable() { @Override public void run() { logger.info("Property changed: '" + getName() + " = " + getValue() + "'"); checkAndFlip(); } }; sProp.addCallback(callback); checkAndFlip(); } @Override public boolean isValueAcceptable() { return Math.abs(sProp.get() - Float.MIN_VALUE) > 0.000001f ; } @Override protected Property<Float> getReferencedProperty() { return sProp; } @Override public void removeAllCallbacks() { super.removeAllCallbacks(); sProp.prop.removeCallback(callback); } } public static class BooleanProperty extends ChainLink<Boolean> { private final DynamicBooleanPropertyThatSupportsNull sProp; private Runnable callback; public BooleanProperty(DynamicBooleanPropertyThatSupportsNull sProperty) { super(sProperty.getDefaultValue()); sProp = sProperty; } public BooleanProperty(String name, DynamicBooleanPropertyThatSupportsNull sProperty) { this(name, new BooleanProperty(sProperty)); } public BooleanProperty(String name, BooleanProperty next) { super(next); // setup next pointer sProp = new DynamicBooleanPropertyThatSupportsNull(name, null); callback = new Runnable() { @Override public void run() { logger.info("Property changed: '" + getName() + " = " + getValue() + "'"); checkAndFlip(); } }; sProp.addCallback(callback); checkAndFlip(); } @Override public boolean isValueAcceptable() { return (sProp.getValue() != null); } @Override protected Property<Boolean> getReferencedProperty() { return sProp; } @Override public void removeAllCallbacks() { super.removeAllCallbacks(); sProp.prop.removeCallback(callback); } } public static class DynamicBooleanPropertyThatSupportsNull extends PropertyWrapper<Boolean> { public DynamicBooleanPropertyThatSupportsNull(String propName, Boolean defaultValue) { super(propName, defaultValue); } /** * Get the current value from the underlying DynamicProperty */ public Boolean get() { return prop.getBoolean(defaultValue); } @Override public Boolean getValue() { return get(); } } }
30.721578
131
0.574579
76da45757e5d0ff2a526d0bc0ca50d58e84c060b
954
package com.oc.hawk.project.domain.model.codebase.git; import com.oc.hawk.project.domain.model.project.URLProtocol; import org.apache.commons.lang3.StringUtils; public class CodeBaseUrl { public static final String PROTOCAL_SIGN = "://"; private String url; private URLProtocol protocol; public CodeBaseUrl(String url) { if (url.contains(PROTOCAL_SIGN)) { String protocol = StringUtils.substringBefore(url, ":"); this.protocol = URLProtocol.valueOf(protocol.toLowerCase()); this.url = StringUtils.substringAfterLast(url, PROTOCAL_SIGN); } else { this.protocol = URLProtocol.http; this.url = url; } } public URLProtocol protocol() { return protocol; } public String url(boolean protocol) { if (protocol) { return this.protocol.withUrl(url); } else { return this.url; } } }
27.257143
74
0.62369
88e98a4ca53991e4b6c4fdcf63f5d369e4ee99f9
230
package com.buy.tsg.service; import javax.jws.WebParam; import javax.jws.WebService; @WebService(targetNamespace ="/service.jws/") public interface SendService { public boolean sendOA(@WebParam(name="param") String param); }
20.909091
61
0.769565
860cc99c25b2809d53c9ce3112ce9a91eab335b1
6,136
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.dom.converters; import com.android.tools.idea.model.AndroidModel; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementResolveResult; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiPackage; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveResult; import com.intellij.psi.impl.source.resolve.reference.impl.providers.PackageReferenceSet; import com.intellij.psi.impl.source.resolve.reference.impl.providers.PsiPackageReference; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlFile; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import com.intellij.util.xml.ConvertContext; import com.intellij.util.xml.Converter; import com.intellij.util.xml.CustomReferenceConverter; import com.intellij.util.xml.GenericAttributeValue; import com.intellij.util.xml.GenericDomValue; import org.jetbrains.android.AndroidApplicationPackageRenameProcessor; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class AndroidPackageConverter extends Converter<String> implements CustomReferenceConverter<String> { @Override public String fromString(@Nullable @NonNls String s, ConvertContext context) { return s; } @Override public String toString(@Nullable String s, ConvertContext context) { return s; } @NotNull @Override public PsiReference[] createReferences(GenericDomValue<String> value, PsiElement element, ConvertContext context) { final String s = value.getStringValue(); return s != null ? new MyPackageReferenceSet(s, element).getPsiReferences() : PsiReference.EMPTY_ARRAY; } private static class MyPackageReferenceSet extends PackageReferenceSet { final int myStartInElement; public MyPackageReferenceSet(String s, PsiElement element) { this(s, element, ElementManipulators.getOffsetInElement(element)); } public MyPackageReferenceSet(String str, PsiElement element, int startInElement) { super(str, element, startInElement); myStartInElement = startInElement; } @NotNull @Override protected PsiPackageReference createReference(TextRange range, int index) { // If the Gradle model specifies an application id, which does not rely on // the package in any way, then the package attribute in the manifest should // be taken to be a normal package reference, and should participate in normal // package rename refactoring AndroidFacet facet = AndroidFacet.getInstance(getElement()); if (facet != null) { AndroidModel androidModel = AndroidModel.get(facet); if (androidModel != null && androidModel.overridesManifestPackage() || facet.getConfiguration().isLibraryProject()) { return new PsiPackageReference(this, range, index); } } return new MyPsiPackageReference(this, range, index); } } private static class MyPsiPackageReference extends PsiPackageReference { private final MyPackageReferenceSet myReferenceSet; private final TextRange myTextRange; public MyPsiPackageReference(MyPackageReferenceSet referenceSet, TextRange textRange, int index) { super(referenceSet, textRange, index); myReferenceSet = referenceSet; myTextRange = textRange; } @NotNull @Override public ResolveResult[] multiResolve(boolean incompleteCode) { return PsiElementResolveResult.createResults(myElement); } @Override public boolean isReferenceTo(@NotNull PsiElement element) { final ResolveResult[] results = doMultiResolve(); for (ResolveResult result : results) { if (getElement().getManager().areElementsEquivalent(result.getElement(), element)) { return true; } } return false; } @Override public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException { return myElement; } @Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { // here we only detect package movement and update relative names of components in manifest, don't change the current element if (!(element instanceof PsiPackage) || !(myElement instanceof XmlAttributeValue)) { throw new IncorrectOperationException("Cannot bind to " + element); } final String newPackageName = ((PsiPackage)element).getQualifiedName(); final String basePackage = ((XmlAttributeValue)myElement).getValue(); final String oldPackageName = myElement.getText().substring(myReferenceSet.myStartInElement, myTextRange.getEndOffset()); final PsiFile file = myElement.getContainingFile(); if (!basePackage.isEmpty() && file instanceof XmlFile) { AndroidApplicationPackageRenameProcessor.processAllAttributesToUpdate( (XmlFile)file, basePackage, oldPackageName, newPackageName, new Processor<Pair<GenericAttributeValue, String>>() { @Override public boolean process(Pair<GenericAttributeValue, String> pair) { pair.getFirst().setStringValue(pair.getSecond()); return true; } }); } return myElement; } } }
39.587097
131
0.745274
3120715bd52cd20ba70c2359f347f3481b54dda5
532
package com.lei.stu.classload; /** * @Description * @Author leihaoyuan * @Date 2019/10/21 16:55 */ public class MyTest8 { public static void main(String[] args) { Fruit apple = new Apple(); Fruit orange = new Orange(); apple.test(); orange.test(); } } class Fruit{ public void test(){ System.out.println("Fruit"); } } class Apple extends Fruit{ @Override public void test() { System.out.println("Apple"); } } class Orange extends Fruit{ }
15.2
44
0.575188
1b3b2bf2a687d72c50b1b08c5200d4ed9f027d97
272
package proyecto_integrador_franciscosantos; public class Rey extends Pieza { public Rey() { super(); } public Rey(boolean acceso) { super(acceso); } @Override public String toString() { return "♠"; } }
12.363636
44
0.547794
a7d685c582c63734586ef59a0ba73561e6f2c8da
1,892
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.org.apache.mina.common; /** * An {@link IoFuture} for asynchronous write requests. * * <h3>Example</h3> * <pre> * IoSession session = ...; * WriteFuture future = session.write(...); * // Wait until the message is completely written out to the O/S buffer. * future.join(); * if( future.isWritten() ) * { * // The message has been written successfully. * } * else * { * // The messsage couldn't be written out completely for some reason. * // (e.g. Connection is closed) * } * </pre> * * @author The Apache Directory Project (mina-dev@directory.apache.org) * @version $Rev$, $Date$ */ public interface WriteFuture extends IoFuture { /** * Returns <tt>true</tt> if the write operation is finished successfully. */ boolean isWritten(); /** * Sets whether the message is written or not, and notifies all threads * waiting for this future. This method is invoked by MINA internally. * Please do not call this method directly. */ void setWritten(boolean written); }
32.62069
77
0.683404
c2e5b7eb6060e458e7c2f3bc9f5aa9dddc421c1d
1,939
package dao; import models.User; import org.sql2o.*; import java.util.List; public class Sql2oUserDao implements UserDao { private final Sql2o sql2o; public Sql2oUserDao(Sql2o sql2o){ this.sql2o =sql2o; } @Override public void add(User user){ String sql = "INSERT INTO users(userName,userCompanyPosition,userRole,departmentId) VALUES (:userName,:userCompanyPosition,:userRole,:departmentId)"; try(Connection conn =sql2o.open()){ int id =(int) conn.createQuery(sql,true) .bind(user) .executeUpdate() .getKey(); user.setId(id); }catch(Sql2oException ex){ System.out.println(ex); } } @Override public List<User> getAll(){ try(Connection conn =sql2o.open()){ return conn.createQuery("SELECT * FROM users") .executeAndFetch(User.class); } } @Override public List<User>getAllUsersByDepartment(int departmentId){ try (Connection conn = sql2o.open()){ return conn.createQuery("SELECT * FROM users WHERE departmentId = :departmentId") .addParameter("departmentId",departmentId) .executeAndFetch(User.class); } } @Override public void deleteById(int id){ String sql = "DELETE from users WHERE id =:id"; try (Connection conn = sql2o.open()){ conn.createQuery(sql) .addParameter("id",id) .executeUpdate(); }catch (Sql2oException ex){ System.out.println(ex); } } @Override public void clearAll(){ String sql ="DELETE from users"; try (Connection conn = sql2o.open()){ conn.createQuery(sql).executeUpdate(); }catch (Sql2oException ex){ System.out.println(ex); } } }
28.940299
157
0.565756
0cc8e9fa89c2f9428b29e80bad57dbd016105d70
561
package com.company; public class Main { public static void main(String[] args) { Mamiferos baleia = new Mamiferos("wale","cordado","aquático"); baleia.animalInfo(); /* This repteis class can't be instantiated because it's an abstract class, so this code below can't be done Repteis jacaré = new Repteis("alligator","cordado","terrestre e aquático"); jacaré.animalInfo(); */ Anfibios sapo = new Anfibios("frog","cordado","terrestre"); sapo.animalInfo(); } }
31.166667
115
0.602496
22996a5c6626125da7631fc7baa508a4dbdaf23f
37,729
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.47 * Generated at: 2019-11-01 07:39:17 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.page.novel; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class novel_005fchapter_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005ftype_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fif_0026_005ftest; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005ftype_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005ftype_005fnobody.release(); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.release(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.release(); } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<title>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.name }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("章节列表-清风小说网</title>\r\n"); out.write("<meta charset=\"utf-8\" />\r\n"); out.write("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\r\n"); out.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n"); out.write("<script src=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/js/jquery-3.3.1.min.js\"></script>\r\n"); out.write("<script src=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/js/bootstrap.min.js\"></script>\r\n"); out.write("<link rel=\"stylesheet\"\r\n"); out.write("\thref=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/css/bootstrap.min.css\">\r\n"); out.write("<link rel=\"stylesheet\" type=\"text/css\"\r\n"); out.write("\thref=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/css/header.css\">\r\n"); out.write("<link rel=\"stylesheet\" type=\"text/css\"\r\n"); out.write("\thref=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/css/footer.css\" />\r\n"); out.write("<link rel=\"stylesheet\" type=\"text/css\"\r\n"); out.write("\thref=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/css/novel_chapter.css\" />\r\n"); out.write("<style>\r\n"); out.write("</style>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\t<div class=\"container\">\r\n"); out.write("\t\t"); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "../public/novel_header_nav.jsp", out, false); out.write("\r\n"); out.write("\t\t<div class=\"book\">\r\n"); out.write("\t\t\t<div class=\"path\">\r\n"); out.write("\t\t\t\t<div class=\"p\">\r\n"); out.write("\t\t\t\t\t<a href=\"/\">清风小说网</a> &gt; "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.name }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\t\t\t<div class=\"info clearfix\">\r\n"); out.write("\t\t\t\t<div class=\"cover\">\r\n"); out.write("\t\t\t\t\t<img src=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.cover }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("\" alt=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.name }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("\">\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t\t<div class=\"small\">\r\n"); out.write("\t\t\t\t\t<h4>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.name }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</h4>\r\n"); out.write("\t\t\t\t\t<div class=\"book_info\">\r\n"); out.write("\t\t\t\t\t\t<p>\r\n"); out.write("\t\t\t\t\t\t\t<span><b>作 者:</b>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.author }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</span>&nbsp; <span><b>分类:</b>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.type }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</span>\r\n"); out.write("\t\t\t\t\t\t\t<span><b>状态:</b>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.status == 1 ? \"连载\" : \"完结\" }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</span>&nbsp;\r\n"); out.write("\t\t\t\t\t\t\t<span><b>字数:</b>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.wordage }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</span>\r\n"); out.write("\t\t\t\t\t\t</p>\r\n"); out.write("\t\t\t\t\t\t<p>\r\n"); out.write("\t\t\t\t\t\t\t<span><b>简介:</b></span>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.introduce}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write(" <br>作者:"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.author }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("所写的《"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.name }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("》无弹窗免费全文阅读为转载作品,章节由网友发布。\r\n"); out.write("\t\t\t\t\t\t</p>\r\n"); out.write("\t\t\t\t\t\t<p>\r\n"); out.write("\t\t\t\t\t\t\t<span class=\"last\"><b>最新章节:</b><a href=\"\">"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.lastUpdateChapter}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</a></span>&nbsp;<span\r\n"); out.write("\t\t\t\t\t\t\t\tclass=\"last\"><b>更新时间:</b> "); if (_jspx_meth_fmt_005fformatDate_005f0(_jspx_page_context)) return; out.write(" </span>\r\n"); out.write("\t\t\t\t\t\t</p>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\r\n"); out.write("\t\t\t\t\t<div class=\"book_btn\">\r\n"); out.write("\t\t\t\t\t\t<button class=\"book-start btn btn-danger\" id=\"novelStart\">开始阅读</button>\r\n"); out.write("\t\t\t\t\t\t<button class=\"add-book btn btn-info \" id=\"addBookshelf\"\r\n"); out.write("\t\t\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f0(_jspx_page_context)) return; out.write(">加入书架</button>\r\n"); out.write("\t\t\t\t\t</div>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\t\t\t<div class=\"listmain\">\r\n"); out.write("\t\t\t\t<table class=\"table table-bordered\">\r\n"); out.write("\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t<tr class=\"bt\">\r\n"); out.write("\t\t\t\t\t\t\t<td colspan=\"3\">最新十二章章节</td>\r\n"); out.write("\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t"); if (_jspx_meth_c_005fforEach_005f0(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t</table>\r\n"); out.write("\t\t\t\t<table class=\"table table-bordered\">\r\n"); out.write("\t\t\t\t\t<thead>\r\n"); out.write("\t\t\t\t\t\t<tr class=\"bt\">\r\n"); out.write("\t\t\t\t\t\t\t<td colspan=\"3\">完整章节</td>\r\n"); out.write("\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t</thead>\r\n"); out.write("\t\t\t\t\t<tbody>\r\n"); out.write("\t\t\t\t\t\t"); if (_jspx_meth_c_005fforEach_005f2(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t\t\t\t</tbody>\r\n"); out.write("\t\t\t\t</table>\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\t\t</div>\r\n"); out.write("\t</div>\r\n"); out.write("\t<div class=\"footer\">\r\n"); out.write("\t\t<div class=\"footer_link\"></div>\r\n"); out.write("\t\t<div class=\"footer_cont\">\r\n"); out.write("\t\t\t<p>本站所有小说为转载作品,所有章节均由网友上传,转载至本站只是为了宣传本书让更多读者欣赏。</p>\r\n"); out.write("\t\t</div>\r\n"); out.write("\t</div>\r\n"); out.write("\r\n"); out.write("\t<!--增加书架列表模态框-->\r\n"); out.write("\t<div class=\"modal fade\" id=\"addBookshelfList\" tabindex=\"-1\"\r\n"); out.write("\t\trole=\"dialog\" aria-labelledby=\"addBookshelfModalLabel\">\r\n"); out.write("\t\t<div class=\"modal-dialog\" role=\"document\" style=\"max-width: 300px;\">\r\n"); out.write("\t\t\t<div class=\"modal-content\">\r\n"); out.write("\t\t\t\t<div class=\"modal-header\">\r\n"); out.write("\t\t\t\t\t<h4 class=\"modal-title\">请选择加入的书架</h4>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t\t<div class=\"modal-body\">\r\n"); out.write("\t\t\t\t\t<ul class=\"list-group\">\r\n"); out.write("\t\t\t\t\t\t"); if (_jspx_meth_c_005fforEach_005f4(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t\t\t\t</ul>\r\n"); out.write("\t\t\t\t</div>\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\t\t</div>\r\n"); out.write("\t</div>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\t<script type=\"text/javascript\">\r\n"); out.write("\t\tfunction selectBookshelf(bid,nid){\r\n"); out.write("\t\t\t$.ajax({\r\n"); out.write("\t\t\t\ttype:'post',\r\n"); out.write("\t\t\t\turl:'/addNovel',\r\n"); out.write("\t\t\t\tdata:{\"bid\":bid,\"nid\":nid},\r\n"); out.write("\t\t\t\tcache:false,\r\n"); out.write("\t\t\t\tsuccess:function(){\r\n"); out.write("\t\t\t\t\talert(\"添加成功\");\r\n"); out.write("\t\t\t\t\twindow.location.reload();\r\n"); out.write("\t\t\t\t}\r\n"); out.write("\t\t\t})\r\n"); out.write("\t\t}\r\n"); out.write("\t\t$(\"#addBookshelf\").click(function() {\r\n"); out.write("\t\t\tif("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${user!=null}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("){ \r\n"); out.write("\t\t\t\t$(\"#addBookshelfList\").modal(\"show\");\r\n"); out.write("\t\t\t}else{\r\n"); out.write("\t\t\t\talert(\"请先进行登录\");\r\n"); out.write("\t\t\t\twindow.location.href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/toLogin\";\r\n"); out.write("\t\t\t}\r\n"); out.write("\t\t})\r\n"); out.write("\t\t$(\"#novelStart\").click(function() {\r\n"); out.write("\t\t\tvar id = $(\".chapter\").eq(0).find(\"a\").first().attr(\"href\");\r\n"); out.write("\t\t\twindow.location.href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("\"+id;\r\n"); out.write("\t\t})\r\n"); out.write("\t</script>\r\n"); out.write("</body>\r\n"); out.write("</html>\r\n"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_fmt_005fformatDate_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:formatDate org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_005fformatDate_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005ftype_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class); _jspx_th_fmt_005fformatDate_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fformatDate_005f0.setParent(null); // /WEB-INF/page/novel/novel_chapter.jsp(51,34) name = value type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.lastUpdateTime}", java.util.Date.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); // /WEB-INF/page/novel/novel_chapter.jsp(51,34) name = type type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setType("both"); int _jspx_eval_fmt_005fformatDate_005f0 = _jspx_th_fmt_005fformatDate_005f0.doStartTag(); if (_jspx_th_fmt_005fformatDate_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005ftype_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return true; } _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005ftype_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return false; } private boolean _jspx_meth_c_005fif_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f0.setParent(null); // /WEB-INF/page/novel/novel_chapter.jsp(59,7) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${result>0 }", java.lang.Boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)).booleanValue()); int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag(); if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("disabled=\"disabled\" \r\n"); out.write("\t\t\t\t\t "); int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); return false; } private boolean _jspx_meth_c_005fforEach_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f0.setParent(null); // /WEB-INF/page/novel/novel_chapter.jsp(72,6) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f0.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/page/novel/novel_chapter.jsp(72,6) '${newChapterLists }'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${newChapterLists }",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/page/novel/novel_chapter.jsp(72,6) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f0.setVar("chapterList"); int[] _jspx_push_body_count_c_005fforEach_005f0 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f0 = _jspx_th_c_005fforEach_005f0.doStartTag(); if (_jspx_eval_c_005fforEach_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t"); if (_jspx_meth_c_005fforEach_005f1(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0)) return true; out.write("\r\n"); out.write("\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f0[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f0.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f0.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f0); } return false; } private boolean _jspx_meth_c_005fforEach_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0); // /WEB-INF/page/novel/novel_chapter.jsp(74,8) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f1.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/page/novel/novel_chapter.jsp(74,8) '${chapterList }'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${chapterList }",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/page/novel/novel_chapter.jsp(74,8) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f1.setVar("chapter"); int[] _jspx_push_body_count_c_005fforEach_005f1 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f1 = _jspx_th_c_005fforEach_005f1.doStartTag(); if (_jspx_eval_c_005fforEach_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td width=\"33.3%\"><a\r\n"); out.write("\t\t\t\t\t\t\t\t\t\thref=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/novel/"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.id }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write('/'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${chapter.url }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write('"'); out.write('>'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${chapter.title }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</a></td>\r\n"); out.write("\t\t\t\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f1[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f1.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f1.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f1); } return false; } private boolean _jspx_meth_c_005fforEach_005f2(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f2 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f2.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f2.setParent(null); // /WEB-INF/page/novel/novel_chapter.jsp(89,6) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f2.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/page/novel/novel_chapter.jsp(89,6) '${chapterLists }'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${chapterLists }",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/page/novel/novel_chapter.jsp(89,6) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f2.setVar("chapterList"); int[] _jspx_push_body_count_c_005fforEach_005f2 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f2 = _jspx_th_c_005fforEach_005f2.doStartTag(); if (_jspx_eval_c_005fforEach_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t\t<tr>\r\n"); out.write("\t\t\t\t\t\t\t\t"); if (_jspx_meth_c_005fforEach_005f3(_jspx_th_c_005fforEach_005f2, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f2)) return true; out.write("\r\n"); out.write("\t\t\t\t\t\t\t</tr>\r\n"); out.write("\t\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f2.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f2[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f2.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f2.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f2); } return false; } private boolean _jspx_meth_c_005fforEach_005f3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f2, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f2) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f3 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f3.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f2); // /WEB-INF/page/novel/novel_chapter.jsp(91,8) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f3.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/page/novel/novel_chapter.jsp(91,8) '${chapterList }'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${chapterList }",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/page/novel/novel_chapter.jsp(91,8) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f3.setVar("chapter"); int[] _jspx_push_body_count_c_005fforEach_005f3 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f3 = _jspx_th_c_005fforEach_005f3.doStartTag(); if (_jspx_eval_c_005fforEach_005f3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t\t\t\t<td class=\"chapter\" width=\"33.3%\"><a\r\n"); out.write("\t\t\t\t\t\t\t\t\t\thref=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("/novel/"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.id }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write('/'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${chapter.url }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write('"'); out.write('>'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${chapter.title }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</a></td>\r\n"); out.write("\t\t\t\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f3.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f3[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f3.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f3.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f3); } return false; } private boolean _jspx_meth_c_005fforEach_005f4(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f4 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f4.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f4.setParent(null); // /WEB-INF/page/novel/novel_chapter.jsp(119,6) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f4.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/page/novel/novel_chapter.jsp(119,6) '${user.bookshelfList }'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${user.bookshelfList }",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/page/novel/novel_chapter.jsp(119,6) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f4.setVar("b"); int[] _jspx_push_body_count_c_005fforEach_005f4 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f4 = _jspx_th_c_005fforEach_005f4.doStartTag(); if (_jspx_eval_c_005fforEach_005f4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t\t<li class=\"list-group-item\"><a href=\"javascript:void(0);\"\r\n"); out.write("\t\t\t\t\t\t\t\tonclick=\"selectBookshelf("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${b.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write(','); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${novel.id }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write(')'); out.write('"'); out.write('>'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${b.name}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("</a></li>\r\n"); out.write("\t\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f4.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f4[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f4.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f4.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f4); } return false; } }
66.659011
331
0.700416
943a54b7a2c419d587158036632909c207210b43
28
test test test test test foo
28
28
0.821429
38e01205256eca5c532c5daf46df0bd600e0b736
1,572
/** * *Copyright 2014 The Darks Codec Project (Liu lihua) * *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 darks.codec.logs; /** * * Logger.java * @version 1.0.0 * @author Liu lihua */ public abstract class Logger { public static Logger getLogger(Class<?> clazz) { return LoggerFactory.getLogger(clazz); } public static Logger getLogger(String tag) { return LoggerFactory.getLogger(tag); } public abstract boolean isDebugEnabled(); public abstract void info(String paramString, Throwable e); public abstract void info(String paramString); public abstract void error(String paramString, Throwable e); public abstract void error(String paramString); public abstract void debug(String paramString); public abstract void debug(String s, Throwable e); public abstract void warn(String paramString); public abstract void warn(String paramString, Throwable e); }
27.103448
75
0.67112
5d4a0e85bc99ba183b89a30b85e44fab61bb1a64
13,945
/* * Janino - An embedded Java[TM] compiler * * Copyright (c) 2019 Arno Unkrig. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.codehaus.commons.compiler.jdk; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import javax.tools.Diagnostic; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import org.codehaus.commons.compiler.AbstractCompiler; import org.codehaus.commons.compiler.CompileException; import org.codehaus.commons.compiler.ErrorHandler; import org.codehaus.commons.compiler.ICompiler; import org.codehaus.commons.compiler.Location; import org.codehaus.commons.compiler.WarningHandler; import org.codehaus.commons.compiler.jdk.util.JavaFileManagers; import org.codehaus.commons.compiler.jdk.util.JavaFileObjects; import org.codehaus.commons.compiler.jdk.util.JavaFileObjects.ResourceJavaFileObject; import org.codehaus.commons.compiler.util.reflect.ApiLog; import org.codehaus.commons.compiler.util.resource.Resource; import org.codehaus.commons.compiler.util.resource.ResourceCreator; import org.codehaus.commons.compiler.util.resource.ResourceFinder; import org.codehaus.commons.nullanalysis.Nullable; /** * {@code javax.tools}-based implementation of the {@link ICompiler}. */ public class Compiler extends AbstractCompiler { private Collection<String> compilerOptions = new ArrayList<>(); private final JavaCompiler compiler; public Compiler() { JavaCompiler c = ToolProvider.getSystemJavaCompiler(); if (c == null) { throw new RuntimeException( "JDK Java compiler not available - probably you're running a JRE, not a JDK", null ); } this.compiler = c; } /** * Initializes with a <em>different</em>, {@code javax.tools.JavaCompiler}-compatible Java compiler. */ public Compiler(JavaCompiler compiler) { this.compiler = compiler; } @Override public void setVerbose(boolean verbose) {} /** * Adds command line options that are passed unchecked to the {@link java.lang.Compiler}. * <p> * Notice: Don't use the '-g' options - these are controlled through {@link #setDebugLines(boolean)}, {@link * #setDebugVars(boolean)} and {@link #setDebugSource(boolean)}. * </p> * * @param compilerOptions All command line options supported by the JDK JAVAC tool */ public void setCompilerOptions(String[] compilerOptions) { this.compilerOptions = Arrays.asList(compilerOptions); } @Override public void compile(final Resource[] sourceResources) throws CompileException, IOException { this.compile(sourceResources, null); } public void compile(final Resource[] sourceResources, @Nullable SortedSet<Location> offsets) throws CompileException, IOException { // Compose the effective compiler options. List<String> options = new ArrayList<>(this.compilerOptions); // Debug options. { List<String> l = new ArrayList<>(); if (this.debugLines) l.add("lines"); if (this.debugSource) l.add("source"); if (this.debugVars) l.add("vars"); if (l.isEmpty()) l.add("none"); Iterator<String> it = l.iterator(); String o = "-g:" + it.next(); while (it.hasNext()) o += "," + it.next(); options.add(o); } // Source / target version options. { if (this.sourceVersion != -1) { options.add("-source"); options.add(Integer.toString(this.sourceVersion)); } if (this.targetVersion != -1) { options.add("-target"); options.add(Integer.toString(this.targetVersion)); } } // Bootclasspath. { File[] bcp = this.bootClassPath; if (bcp != null) { options.add("-bootclasspath"); options.add(Compiler.filesToPath(bcp)); } } // Classpath. options.add("-classpath"); options.add(Compiler.filesToPath(this.classPath)); Compiler.compile( this.compiler, options, this.sourceFinder, this.sourceCharset, this.classFileFinder, this.classFileCreator, sourceResources, this.compileErrorHandler, this.warningHandler, offsets ); } static void compile( JavaCompiler compiler, List<String> options, ResourceFinder sourceFinder, Charset sourceFileCharset, ResourceFinder classFileFinder, ResourceCreator classFileCreator, Resource[] sourceFiles, @Nullable ErrorHandler compileErrorHandler, @Nullable WarningHandler warningHandler, @Nullable SortedSet<Location> offsets ) throws CompileException, IOException { // Wrap the source files in JavaFileObjects. Collection<JavaFileObject> sourceFileObjects = new ArrayList<>(); for (int i = 0; i < sourceFiles.length; i++) { Resource sourceResource = sourceFiles[i]; String fn = sourceResource.getFileName(); String className = fn.substring(fn.lastIndexOf(File.separatorChar) + 1).replace('/', '.'); if (className.endsWith(".java")) className = className.substring(0, className.length() - 5); sourceFileObjects.add(JavaFileObjects.fromResource( sourceResource, className, Kind.SOURCE, sourceFileCharset )); } final JavaFileManager fileManager = Compiler.getJavaFileManager( compiler, sourceFinder, sourceFileCharset, classFileFinder, classFileCreator ); try { Compiler.compile( compiler, options, sourceFileObjects, fileManager, compileErrorHandler, warningHandler, offsets ); } finally { fileManager.close(); } } /** * Creates a {@link JavaFileManager} that implements the given <var>sourceFileFinder</var>, <var>sourceFileCharset</var>, * <var>classFileFinder</var> and <var>classFileCreator</var>. */ private static JavaFileManager getJavaFileManager( JavaCompiler compiler, ResourceFinder sourceFileFinder, Charset sourceFileCharset, ResourceFinder classFileFinder, ResourceCreator classFileCreator ) { // Get the original FM, which reads class files through this JVM's BOOTCLASSPATH and // CLASSPATH. JavaFileManager jfm = compiler.getStandardFileManager(null, null, null); // Store .class file via the classFileCreator. jfm = JavaFileManagers.fromResourceCreator( jfm, StandardLocation.CLASS_OUTPUT, Kind.CLASS, classFileCreator, Charset.defaultCharset() ); // Find existing .class files through the classFileFinder. jfm = JavaFileManagers.fromResourceFinder( jfm, StandardLocation.CLASS_PATH, Kind.CLASS, classFileFinder, Charset.defaultCharset() // irrelevant ); // Wrap it in a file manager that finds source files through the .sourceFinder. jfm = JavaFileManagers.fromResourceFinder( jfm, StandardLocation.SOURCE_PATH, Kind.SOURCE, sourceFileFinder, sourceFileCharset ); return jfm; } /** * Compiles on the {@link JavaFileManager} / {@link JavaFileObject} level. */ static void compile( JavaCompiler compiler, List<String> options, Collection<JavaFileObject> sourceFileObjects, JavaFileManager fileManager, @Nullable final ErrorHandler compileErrorHandler, @Nullable final WarningHandler warningHandler, @Nullable final SortedSet<Location> offsets ) throws CompileException, IOException { fileManager = (JavaFileManager) ApiLog.logMethodInvocations(fileManager); final int[] compileErrorCount = new int[1]; final DiagnosticListener<JavaFileObject> dl = new DiagnosticListener<JavaFileObject>() { @Override public void report(@Nullable Diagnostic<? extends JavaFileObject> diagnostic) { assert diagnostic != null; JavaFileObject source = diagnostic.getSource(); Location loc = new Location( ( // fileName source == null ? null : source instanceof ResourceJavaFileObject ? ((ResourceJavaFileObject) source).getResourceFileName() : source.getName() ), (short) diagnostic.getLineNumber(), (short) diagnostic.getColumnNumber() ); // Manipulate the diagnostic location to accomodate for the "offsets" (see "addOffset(String)"): if (offsets != null) { SortedSet<Location> hs = offsets.headSet(loc); if (!hs.isEmpty()) { Location co = hs.last(); loc = new Location( co.getFileName(), loc.getLineNumber() - co.getLineNumber() + 1, ( loc.getLineNumber() == co.getLineNumber() ? loc.getColumnNumber() - co.getColumnNumber() + 1 : loc.getColumnNumber() ) ); } } String message = diagnostic.getMessage(null) + " (" + diagnostic.getCode() + ")"; try { switch (diagnostic.getKind()) { case ERROR: compileErrorCount[0]++; if (compileErrorHandler == null) throw new CompileException(message, loc); compileErrorHandler.handleError(diagnostic.toString(), loc); break; case MANDATORY_WARNING: case WARNING: if (warningHandler != null) warningHandler.handleWarning(null, message, loc); break; case NOTE: case OTHER: default: break; } } catch (CompileException ce) { throw new RuntimeException(ce); } } }; // Run the compiler. try { if (!compiler.getTask( null, // out fileManager, // fileManager dl, // diagnosticListener options, // options null, // classes sourceFileObjects // compilationUnits ).call() || compileErrorCount[0] > 0) { throw new CompileException("Compilation failed with " + compileErrorCount[0] + " errors", null); } } catch (RuntimeException rte) { // Unwrap the compilation exception and throw it. for (Throwable t = rte.getCause(); t != null; t = t.getCause()) { if (t instanceof CompileException) { throw (CompileException) t; // SUPPRESS CHECKSTYLE AvoidHidingCause } if (t instanceof IOException) { throw (IOException) t; // SUPPRESS CHECKSTYLE AvoidHidingCause } } throw rte; } } private static String filesToPath(File[] files) { StringBuilder sb = new StringBuilder(); for (File cpe : files) { if (sb.length() > 0) sb.append(File.pathSeparatorChar); sb.append(cpe.getPath()); } return sb.toString(); } }
36.033592
126
0.606526
49201a46aa79e14bde71d145e27df05d1af0a17a
493
package com.ziroom.tech.demeterapi.common.enums; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author lipp3 * @date 2021/6/30 18:19 * @Description */ @Getter @AllArgsConstructor @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum SkillManifestFlowStatus { ONGOING(2 ,"进行中"), PASS(4 , "认证通过"); /** * 类型码 */ private Integer code; /** * 类型描述 */ private String name; }
16.433333
51
0.661258
618ba66e223680c4b9b31fd1fe537b45d947dbf5
1,060
package com.fincatto.nfe310.classes.cadastro; import org.junit.Assert; import org.junit.Test; public class NFIndicadorContribuinteNFeTest { @Test public void deveRepresentarOCodigoCorretamente() { Assert.assertEquals(NFIndicadorContribuinteNFe.NAO_CREDENCIADO_PARA_EMISSAO_NFE, NFIndicadorContribuinteNFe.valueOfCodigo(0)); Assert.assertEquals(NFIndicadorContribuinteNFe.CREDENCIADO, NFIndicadorContribuinteNFe.valueOfCodigo(1)); Assert.assertEquals(NFIndicadorContribuinteNFe.CREDENCIADO_COM_OBRIGATORIEDADE_PARA_TODAS_OPERACOES, NFIndicadorContribuinteNFe.valueOfCodigo(2)); Assert.assertEquals(NFIndicadorContribuinteNFe.CREDENCIADO_COM_OBRIGATORIEDADE_PARCIAL, NFIndicadorContribuinteNFe.valueOfCodigo(3)); Assert.assertEquals(NFIndicadorContribuinteNFe.SEFAZ_NAO_FORNECE_ESSA_INFO, NFIndicadorContribuinteNFe.valueOfCodigo(4)); } @Test(expected = IllegalStateException.class) public void deveLancarExcecaoCasoNaoEncontreCodigo() { NFIndicadorContribuinteNFe.valueOfCodigo(5); } }
50.47619
154
0.823585
c4ee1790dd2395685da331a2507266ef3eda5de1
3,607
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.atlas.repository.graphdb.janus.migration; import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.apache.atlas.model.typedef.AtlasRelationshipDef.PropagateTags; import org.apache.atlas.model.typedef.AtlasRelationshipEndDef; import org.apache.atlas.repository.Constants; import org.apache.atlas.type.AtlasRelationshipType; import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.v1.typesystem.types.utils.TypesUtil; import org.apache.commons.lang.StringUtils; import java.util.HashMap; import java.util.Map; public class RelationshipCacheGenerator { public static class TypeInfo extends TypesUtil.Pair<String, PropagateTags> { public TypeInfo(String typeName, PropagateTags propagateTags) { super(typeName, propagateTags); } public String getTypeName() { return left; } public PropagateTags getPropagateTags() { return right; } } public static Map<String, TypeInfo> get(AtlasTypeRegistry typeRegistry) { Map<String, TypeInfo> ret = new HashMap<>(); for (AtlasRelationshipType relType : typeRegistry.getAllRelationshipTypes()) { AtlasRelationshipDef relDef = relType.getRelationshipDef(); String relTypeName = relType.getTypeName(); add(ret, getKey(relDef.getEndDef1()), relTypeName, relDef.getPropagateTags()); add(ret, getKey(relDef.getEndDef2()), relTypeName, getEnd2PropagateTag(relDef.getPropagateTags())); } return ret; } private static String getKey(AtlasRelationshipEndDef endDef) { return getKey(endDef.getIsLegacyAttribute(), endDef.getType(), endDef.getName()); } private static String getKey(String lhs, String rhs) { return String.format("%s%s.%s", Constants.INTERNAL_PROPERTY_KEY_PREFIX, lhs, rhs); } private static String getKey(boolean isLegacy, String entityTypeName, String relEndName) { if (!isLegacy) { return ""; } return getKey(entityTypeName, relEndName); } private static void add(Map<String, TypeInfo> map, String key, String relationTypeName, PropagateTags propagateTags) { if (StringUtils.isEmpty(key) || map.containsKey(key)) { return; } map.put(key, new TypeInfo(relationTypeName, propagateTags)); } private static PropagateTags getEnd2PropagateTag(PropagateTags end1PropagateTags) { if (end1PropagateTags == PropagateTags.ONE_TO_TWO) { return PropagateTags.TWO_TO_ONE; } else if (end1PropagateTags == PropagateTags.TWO_TO_ONE) { return PropagateTags.ONE_TO_TWO; } else { return end1PropagateTags; } } }
36.434343
122
0.701414
b3e5faa098508d4d7bae56ea8be64d435ad89b56
1,727
package com.marverenic.music.ui; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.databinding.BaseObservable; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.DimenRes; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.v4.content.ContextCompat; public abstract class BaseViewModel extends BaseObservable { private Context mContext; public BaseViewModel(Context context) { mContext = context; } protected Context getContext() { return mContext; } protected Resources getResources() { return mContext.getResources(); } @ColorInt protected int getColor(@ColorRes int colorRes) { return ContextCompat.getColor(mContext, colorRes); } protected Drawable getDrawable(@DrawableRes int drawableRes) { return ContextCompat.getDrawable(mContext, drawableRes); } protected String getString(@StringRes int stringRes) { return mContext.getString(stringRes); } protected String getString(@StringRes int stringRes, Object... formatArgs) { return mContext.getString(stringRes, formatArgs); } protected float getDimension(@DimenRes int dimenRes) { return mContext.getResources().getDimension(dimenRes); } protected int getDimensionPixelSize(@DimenRes int dimenRes) { return mContext.getResources().getDimensionPixelSize(dimenRes); } protected void startActivity(Intent intent) { mContext.startActivity(intent); } }
28.311475
80
0.739433
7f914bcf05998c8fa1105a5b1040290ce3abaa40
1,793
package com.giongstore.vn.runner; import com.giongstore.vn.behavior.memento_pattern.*; import com.giongstore.vn.creation.Cart; import com.giongstore.vn.creation.Product; import com.giongstore.vn.creation.ProductFactory; /** * Created by huytt99 on 23/08/19 */ public class DemoMemento { public static void main(String[] args) { ProductFactory productFactory = new ProductFactory(); Product owenTshirt = productFactory.getProduct("Clothes", "owen T-shirt", 20.45); Product seikoWatch = productFactory.getProduct("Watches", "seiko watch", 29.45); Cart cart1 = new Cart(); cart1.addItem(owenTshirt); cart1.addItem(seikoWatch); State pendingState = new State("pending", cart1); // wait for processing State processingState = new State("processing", cart1); // move goods to warehouse and prepare for delivery State deliveryState = new State("delivery", cart1); // move goods to warehouse and prepare for delivery SpecificTransaction transaction = new SpecificTransaction(); SpecificSnapshot snapshot1 = new SpecificSnapshot(transaction, pendingState); SpecificSnapshot snapshot2 = new SpecificSnapshot(transaction, processingState); SpecificSnapshot snapshot3 = new SpecificSnapshot(transaction, deliveryState); TransactionHistory transactionHistory = new TransactionHistory(); transactionHistory.makeBackup(snapshot1); transactionHistory.makeBackup(snapshot2); transactionHistory.makeBackup(snapshot3); transactionHistory.undo(); System.out.println("Current state: " + transaction.getState().getState()); transactionHistory.undo(); System.out.println("Current state: " + transaction.getState().getState()); } }
43.731707
115
0.717234
f67a00d66ddee01894ffc00a515eb8ed57e3bcc0
852
package command; import connection.ConnectionListener; import server.Application; import server.Server; import java.io.IOException; /** * Класс-команда, реализующая выход из JVM */ public class ExitCommand implements ServerCommand { private final ConnectionListener connectionListener; private final Application application; private final Server server; public ExitCommand(ConnectionListener connectionListener, Application application, Server server) { this.connectionListener = connectionListener; this.application = application; this.server = server; } public synchronized void execute() { try { application.setIsRunning(false); server.shutdownExecutorServices(); connectionListener.stop(); } catch (IOException ignored) { } } }
25.818182
103
0.704225
11901be5116055878903b7c27c4b857becc8cc13
572
package com.facebook.imagepipeline.cache; import com.facebook.common.references.ResourceReleaser; import com.facebook.imagepipeline.cache.CountingMemoryCache.Entry; class CountingMemoryCache$2 implements ResourceReleaser<V> { final /* synthetic */ CountingMemoryCache this$0; final /* synthetic */ Entry val$entry; CountingMemoryCache$2(CountingMemoryCache this$0, Entry entry) { this.this$0 = this$0; this.val$entry = entry; } public void release(V v) { CountingMemoryCache.access$000(this.this$0, this.val$entry); } }
30.105263
68
0.723776
2aa6cbb16ff23a9f3409dccfa65205a7e5b2aa6c
5,313
/* * Copyright 2006-2013 the original author or authors. * * 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.consol.citrus.channel; import com.consol.citrus.context.TestContext; import com.consol.citrus.exceptions.ActionTimeoutException; import com.consol.citrus.message.*; import com.consol.citrus.messaging.ReplyConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Christoph Deppisch * @since 1.4 */ public class ChannelSyncProducer extends ChannelProducer implements ReplyConsumer { /** Logger */ private static Logger log = LoggerFactory.getLogger(ChannelSyncProducer.class); /** Store of reply messages */ private CorrelationManager<Message> replyManager = new DefaultCorrelationManager<Message>(); /** Endpoint configuration */ private final ChannelSyncEndpointConfiguration endpointConfiguration; /** Retry logger */ private static final Logger RETRY_LOG = LoggerFactory.getLogger("com.consol.citrus.MessageRetryLogger"); /** * Default constructor using endpoint configuration. * * @param name * @param endpointConfiguration */ public ChannelSyncProducer(String name, ChannelSyncEndpointConfiguration endpointConfiguration) { super(name, endpointConfiguration); this.endpointConfiguration = endpointConfiguration; } @Override public void send(Message message, TestContext context) { String correlationKey = endpointConfiguration.getCorrelator().getCorrelationKey(message); context.saveCorrelationKey(correlationKey, this); String destinationChannelName = getDestinationChannelName(); log.info("Sending message to channel: '" + destinationChannelName + "'"); if (log.isDebugEnabled()) { log.debug("Message to sent is:\n" + message.toString()); } endpointConfiguration.getMessagingTemplate().setReceiveTimeout(endpointConfiguration.getTimeout()); log.info("Message was successfully sent to channel: '" + destinationChannelName + "'"); org.springframework.messaging.Message replyMessage = endpointConfiguration.getMessagingTemplate().sendAndReceive(getDestinationChannel(), endpointConfiguration.getMessageConverter().convertOutbound(message, endpointConfiguration)); if (replyMessage == null) { throw new ActionTimeoutException("Reply timed out after " + endpointConfiguration.getTimeout() + "ms. Did not receive reply message on reply channel"); } else { log.info("Received synchronous response message from reply channel"); } onReplyMessage(correlationKey, endpointConfiguration.getMessageConverter().convertInbound(replyMessage, endpointConfiguration)); } @Override public Message receive(TestContext context) { return receive(context.getCorrelationKey(this), context); } @Override public Message receive(String selector, TestContext context) { return receive(selector, context, endpointConfiguration.getTimeout()); } @Override public Message receive(TestContext context, long timeout) { return receive(context.getCorrelationKey(this), context, timeout); } @Override public Message receive(String selector, TestContext context, long timeout) { long timeLeft = timeout; Message message = findReplyMessage(selector); while (message == null && timeLeft > 0) { timeLeft -= endpointConfiguration.getPollingInterval(); if (RETRY_LOG.isDebugEnabled()) { RETRY_LOG.debug("Reply message did not arrive yet - retrying in " + (timeLeft > 0 ? endpointConfiguration.getPollingInterval() : endpointConfiguration.getPollingInterval() + timeLeft) + "ms"); } try { Thread.sleep(timeLeft > 0 ? endpointConfiguration.getPollingInterval() : endpointConfiguration.getPollingInterval() + timeLeft); } catch (InterruptedException e) { RETRY_LOG.warn("Thread interrupted while waiting for retry", e); } message = findReplyMessage(selector); } return message; } /** * Saves reply message with correlation key to local store for later processing. * @param correlationKey * @param replyMessage the reply message. */ public void onReplyMessage(String correlationKey, Message replyMessage) { replyManager.store(correlationKey, replyMessage); } /** * Tries to find reply message for correlation key from local store. * @param correlationKey * @return */ public Message findReplyMessage(String correlationKey) { return replyManager.find(correlationKey); } }
37.680851
208
0.701675
987b1d234f64422bdd7df7a3eea5e3256b137e67
1,564
package osmparser; import java.util.*; public class Graph { private final static double AVERAGE_RADIUS_OF_EARTH_CM = 6371 * 1000 * 100; private final Map<Long, Node> graph; public Graph() { this.graph = new HashMap<>(); } public void addNode(Node node) { this.graph.put(node.getId(), node); } public void addEdge(long fromId, long toId) { Node from = this.graph.get(fromId); Node to = this.graph.get(toId); if (from != null && to != null) { int distance = distanceOnEarth(from.getLa(), from.getLo(), to.getLa(), to.getLo()); from.addEdgeTo(toId, distance); } } public Map<Long, Node> getNodesWithEdges() { Map<Long,Node> map = new HashMap<>(); for (Map.Entry<Long, Node> entry : graph.entrySet()) { if (entry.getValue().haveEdges()) { map.put(entry.getKey(), entry.getValue()); } } return map; } private int distanceOnEarth(double lat1, double lon1, double lat2, double lon2) { double latDistance = Math.toRadians(lat1 - lat2); double lngDistance = Math.toRadians(lon1 - lon2); double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return (int) (Math.round(AVERAGE_RADIUS_OF_EARTH_CM * c)); } }
30.666667
95
0.580563
3173e22bd81e8c82ba9f92e6620af62c41352c87
1,185
package ru.job4j.chess.firuges.black; import org.junit.Test; import ru.job4j.chess.ImpossibleMoveException; import ru.job4j.chess.firuges.Cell; import ru.job4j.chess.firuges.Figure; import static org.junit.Assert.*; public class BishopBlackTest { @Test public void whenPositionMatches() { Figure figure = new BishopBlack(Cell.F8); Cell cell = figure.position(); int expectedX = 5; int expectedY = 0; assertEquals(expectedX, cell.getX()); assertEquals(expectedY, cell.getY()); } @Test public void whenCopyIsValidPosition() { Figure figure = new BishopBlack(Cell.F8); Cell cell = figure.position(); assertEquals(figure, figure.copy(cell)); } @Test public void whenWayCOneToGFive() { Figure figure = new BishopBlack(Cell.C1); Cell[] rsl = figure.way(Cell.G5); Cell[] expected = {Cell.D2, Cell.E3, Cell.F4, Cell.G5}; assertArrayEquals(expected, rsl); } @Test(expected = ImpossibleMoveException.class) public void whenWayImpossible() { Figure figure = new BishopBlack(Cell.C1); Cell[] rsl = figure.way(Cell.D3); } }
28.214286
63
0.647257
7922b49c59277198ca6047a7b9f9bf4754f7c76a
2,065
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.vocabulary.test; import junit.framework.*; import org.apache.jena.vocabulary.* ; public class TestVocabDC10 extends VocabTestBase { public TestVocabDC10(String name) { super(name); } public static TestSuite suite() { return new TestSuite( TestVocabDC10.class ); } public void testDC10() { String ns = "http://purl.org/dc/elements/1.0/"; assertProperty( ns + "contributor", DC_10.contributor ); assertProperty( ns + "coverage", DC_10.coverage ); assertProperty( ns + "creator", DC_10.creator ); assertProperty( ns + "date", DC_10.date ); assertProperty( ns + "description", DC_10.description ); assertProperty( ns + "format", DC_10.format ); assertProperty( ns + "identifier", DC_10.identifier ); assertProperty( ns + "language", DC_10.language ); assertProperty( ns + "publisher", DC_10.publisher ); assertProperty( ns + "relation", DC_10.relation ); assertProperty( ns + "rights", DC_10.rights ); assertProperty( ns + "source", DC_10.source ); assertProperty( ns + "subject", DC_10.subject ); assertProperty( ns + "title", DC_10.title ); assertProperty( ns + "type", DC_10.type ); } }
39.711538
75
0.686683
50c7b69ee6d7a373f3447f296bf2fa0be0d34d0e
1,605
import com.didispace.lock.consul.CheckTtl; import com.didispace.lock.consul.Lock; import com.ecwid.consul.v1.ConsulClient; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.util.Random; /** * 测试 */ public class TestLock { @Test public void testLock() throws Exception { ConsulClient consulClient = new ConsulClient(); CheckTtl checkTtl = new CheckTtl("lock-1", consulClient); new Thread(new LockRunner(1, new CheckTtl("lock-1", consulClient))).start(); new Thread(new LockRunner(2, new CheckTtl("lock-2", consulClient))).start(); new Thread(new LockRunner(3, new CheckTtl("lock-3", consulClient))).start(); new Thread(new LockRunner(4, new CheckTtl("lock-4", consulClient))).start(); new Thread(new LockRunner(5, new CheckTtl("lock-5", consulClient))).start(); Thread.sleep(30000L); } } @Slf4j @AllArgsConstructor class LockRunner implements Runnable { private int flag; private CheckTtl checkTtl; @Override public void run() { Lock lock = new Lock(new ConsulClient(), "lock-key", checkTtl); try { // 获取分布式互斥锁(参数含义:阻塞模式、每次尝试获取锁的间隔500ms、尝试n次) if (lock.lock(true, 500L, null)) { log.info("Thread {} start!", flag); // 处理业务逻辑 Thread.sleep(new Random().nextInt(5000)); log.info("Thread {} end!", flag); } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
28.157895
84
0.611838
9a6c33291dbd9cf10ae43e2b7039c6cedcd4a866
92
@interface MyAnnotation { Class value(); } @MyAnnotation(<caret>A.class) class MyClass {}
15.333333
29
0.717391
7428a5cb6f959dcf5aaccc536c1fd8c738ce88bd
3,198
package spoon.test.prettyprinter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import spoon.Launcher; import spoon.compiler.SpoonResourceHelper; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtStatement; import spoon.reflect.code.CtThisAccess; import spoon.reflect.code.CtTypeAccess; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtMethod; import spoon.reflect.declaration.CtType; import spoon.reflect.factory.Factory; import spoon.reflect.reference.CtReference; import spoon.reflect.reference.CtTypeReference; import spoon.reflect.visitor.DefaultJavaPrettyPrinter; import spoon.reflect.visitor.filter.TypeFilter; import spoon.test.delete.testclasses.Adobada; import spoon.test.prettyprinter.testclasses.QualifiedThisRef; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static javax.swing.text.html.HTML.Tag.HEAD; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static spoon.testing.utils.ModelUtils.build; public class QualifiedThisRefTest { Factory factory; @Before public void setup() throws Exception { Launcher spoon = new Launcher(); factory = spoon.createFactory(); factory.getEnvironment().setComplianceLevel(8); spoon.createCompiler( factory, SpoonResourceHelper .resources( "./src/test/java/spoon/test/prettyprinter/testclasses/QualifiedThisRef.java")) .build(); factory.getEnvironment().setAutoImports(true); } @Test public void testQualifiedThisRef() { DefaultJavaPrettyPrinter printer = new DefaultJavaPrettyPrinter(factory.getEnvironment()); CtType<?> ctClass = factory.Type().get(QualifiedThisRef.class); Collection<CtReference> imports = printer.computeImports(ctClass); final List<CtType<?>> ctTypes = new ArrayList<>(); ctTypes.add(ctClass); printer.getElementPrinterHelper().writeHeader(ctTypes, imports); printer.scan(ctClass); Assert.assertTrue(printer.getResult().contains("Object o = this")); Assert.assertTrue(printer.getResult().contains("Object o2 = QualifiedThisRef.this")); } @Test public void testCloneThisAccess() throws Exception { // contract: the target of "this" is correct and can be cloned final Factory factory = build(Adobada.class); final CtClass<Adobada> adobada = factory.Class().get(Adobada.class); final CtMethod<?> m2 = adobada.getMethod("methodUsingjlObjectMethods"); CtThisAccess th = (CtThisAccess) m2.getElements(new TypeFilter(CtThisAccess.class)).get(0); assertEquals(true,th.isImplicit()); assertEquals("notify()",th.getParent().toString()); CtInvocation<?> clone = m2.clone().getBody().getStatement(0); // clone preserves implicitness assertEquals(true, clone.getTarget().isImplicit()); assertEquals("notify()", clone.toString()); // the original bug // note that this behavior means that you can only keep cloned "this" in the same class, // and you cannot "transplant" a cloned "this" to another class // it makes perfectly sense about the meaning of this. // to "transplant" a this, you have to first set the target to null } }
37.623529
93
0.774859
93cc2d387b7eb3247a02418eb8a5a93284575a0a
916
/* * Copyright (c) 2013, Inmite s.r.o. (www.inmite.eu). * * All rights reserved. This source code can be used only for purposes specified * by the given license contract signed by the rightful deputy of Inmite s.r.o. * This source code can be used only by the owner of the license. * * Any disputes arising in respect of this agreement (license) shall be brought * before the Municipal Court of Prague. */ package eu.inmite.android.lib.validations.form.adapters; import android.widget.TextView; import eu.inmite.android.lib.validations.form.iface.IFieldAdapter; import java.lang.annotation.Annotation; /** * Adapter for all views inherited from {@link TextView} * * @author Tomas Vondracek */ public class TextViewAdapter implements IFieldAdapter<TextView, String> { @Override public String getFieldValue(Annotation annotation, TextView fieldView) { return fieldView.getText().toString(); } }
29.548387
80
0.757642
59f8f5c8477f18042e0ba30d442de686bf1f946b
4,431
package eu.fbk.das.other; import eu.fbk.das.innowee.InnoWeeAnalyze; import org.apache.log4j.Logger; import org.junit.Test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static eu.fbk.das.utils.Utils.pf; public class CostAssigner { private static final Logger logger = Logger.getLogger(CostAssigner.class); String path = "/home/loskana/Desktop/choices.csv"; private List<String> players; private HashMap<String, Map<Integer, Integer>> record; private int timelimit = 60; private int N; int[] costs = new int[] {0, 3, 5, 7, 9, 10, 11, 12}; @Test public void test() { CostAssigner ca = new CostAssigner(); ca.execute(); } public void execute() { if (!readChoices()) return; N = players.size(); int[][] costMatrix = getChoicesCost(); HungarianAlgorithm ha = new HungarianAlgorithm(costMatrix); int[][] assignment = ha.findOptimalAssignment(); int tot_cost = 0; for (int[] a: assignment) { String pl = players.get(a[1]); int ch = a[0] + 1; int cost = getPlayerCost(pl, ch); tot_cost += cost; pf("PlayerStateDTO %s: %d (%d) \n", pl, ch, cost); } pf("\n\nMean delusion: %.2f - tot delusion: %d \n", tot_cost * 1.0/N, tot_cost); } private int getPlayerCost(String s, int j) { int c = 99; if (record.get(s).containsKey(j)) c = costs[record.get(s).get(j)]; return c; } /* public void execute() { if (!readChoices()) return; Model model = new Model("group assignment"); N = players.size(); int[][] costMatrix = getChoicesCost(); // variables IntVar[][] vs = model.intVarMatrix("vs", N, N, new int[] {0, 1}); // only one value for row for(int i = 0; i < N; i++) { model.sum(vs[i], "=", 1).post(); } // only one value for column for(int j = 0; j < N; j++) { IntVar[] aux = new IntVar[N]; for (int i = 0; i < N; i++) aux[i] = vs[i][j]; model.sum(aux, "=", 1).post(); } IntVar[] aux_cost = model.intVarArray("ac", N, 0, 999999,true); for(int i = 0; i < N; i++) { model.scalar(vs[i], costMatrix[i], "=", aux_cost[i]).post(); } IntVar tot_cost = model.intVar("C", 0, 999999, true); model.sum(aux_cost, "=", tot_cost).post(); model.setObjective(Model.MINIMIZE, tot_cost); Solver solver = model.getSolver(); // Find a solution that minimizes 'tot_cost' solver.limitTime(f("%ds", timelimit)); Solution best = solver.findOptimalSolution(tot_cost, false); solver.printStatistics(); for(int i = 0; i < N; i++) { for(int j = i +1; j < N; j++) { if (best.getIntVal(vs[i][j]) > 0) { pf("PlayerStateDTO %s: %d (%d) \n", players.get(i), j, costMatrix[i][j]); } } } p("completed"); } */ private int[][] getChoicesCost() { int[][] cost = new int[N][]; int c; for (int i = 0; i < N; i++) { cost[i] = new int[N]; Map<Integer, Integer> map = record.get(players.get(i)); for (int j = 0; j < N; j++) { cost[i][j] = getPlayerCost(players.get(i), j+1); } } return cost; } private boolean readChoices() { players = new ArrayList<>(); record = new HashMap<String, Map<Integer, Integer>>(); try (BufferedReader br = new BufferedReader(new FileReader(path))) { String line; while ((line = br.readLine()) != null) { String[] values = line.split("\t"); players.add(values[0]); HashMap<Integer, Integer> choices = new HashMap<Integer, Integer>(); for (int i = 1; i < values.length; i++) choices.put(Integer.valueOf(values[i]), i-1); record.put(values[0], choices); } } catch (IOException e) { logger.error(e); return false; } return true; } }
27.867925
93
0.516813
6a74a4d2c5014206ac70cc1ce55e2db77e01b943
1,025
package ua.oledok.algorithms.part1; public class ArrayQueue<T> implements Queue<T> { private int head; private int tail; private Object[] elements; public ArrayQueue() { elements = new Object[1]; } @Override public int size() { return tail - head; } @Override public void enqueue(T element) { elements[tail++] = element; if (tail == elements.length) { resize(elements.length * 2); } } @Override public T dequeue() { @SuppressWarnings("unchecked") T result = (T) elements[head]; elements[head++] = null; if (size() <= elements.length / 4) { resize(elements.length / 2); } return result; } private void resize(int size) { Object[] current = elements; int length = tail - head; elements = new Object[size]; tail = length; System.arraycopy(current, head, elements, 0, length); head = 0; } }
19.339623
61
0.541463
9cc5fce82751e1a156a3abf514c0bad6ae489982
1,884
package uk.gov.ons.ctp.response.action.endpoint; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import uk.gov.ons.ctp.common.endpoint.CTPEndpoint; import uk.gov.ons.ctp.common.error.CTPException; import uk.gov.ons.ctp.response.action.message.instruction.ActionInstruction; import uk.gov.ons.ctp.response.action.service.PublisherConfirmsService; /** * The REST endpoint controller for ActionSvc Support tasks */ @RestController @RequestMapping(value = "/support", produces = "application/json") @Slf4j public class SupportEndpoint implements CTPEndpoint { public static final String UNEXPECTED_MSG_TYPE = "Unexpected message type: %s"; @Autowired private PublisherConfirmsService publisherConfirmsService; /** * To replay messages that are stored in the database because they failed reaching a RabbitMQ queue when initially * published. * * @return the response 204 if all ok * @throws CTPException something went wrong */ @RequestMapping(value = "/replayMessages/{msgType}", method = RequestMethod.POST) public ResponseEntity<?> replayMessages(@PathVariable("msgType") final String msgType) throws CTPException { log.info("Entering replayMessages with msgType {}", msgType); if (msgType.equalsIgnoreCase(ActionInstruction.class.getSimpleName())) { publisherConfirmsService.replayActionInstruction(); } else { throw new CTPException(CTPException.Fault.RESOURCE_NOT_FOUND, String.format(UNEXPECTED_MSG_TYPE, msgType)); } return ResponseEntity.noContent().build(); } }
40.956522
116
0.789278
908a7a494aa97055444cc2c6b9470bed69264b3a
2,372
package nl.knaw.dans.repo.arrdf.http; import nl.knaw.dans.repo.arrdf.xml.RsLn; import nl.knaw.dans.repo.arrdf.xml.UrlItem; import nl.knaw.dans.repo.arrdf.xml.Urlset; import org.junit.Test; import java.net.URI; import static org.junit.Assume.assumeTrue; /** * Created on 2018-08-23 16:08. */ public class RsNavigatorTest { @Test public void navigate() throws Exception { assumeTrue("Live testing is off.", Testing.LIVE_TESTS); String url = "https://data.anansi.clariah.nl/.well-known/resourcesync"; String dwcCL = "https://data.anansi.clariah.nl/v5/resourcesync/u74ccc032adf8422d7ea92df96cd4783f0543db3b/dwc/capabilitylist.xml"; String nlgisCL = "https://data.anansi.clariah.nl/v5/resourcesync/u74ccc032adf8422d7ea92df96cd4783f0543db3b/nlgis/capabilitylist.xml"; String someRresorceList = "https://data.anansi.clariah.nl/v5/resourcesync/u74ccc032adf8422d7ea92df96cd4783f0543db3b/tbi/resourcelist.xml"; String noRs = "https://github.com/DANS-repo/arrdf"; RsNavigator navigator = new RsNavigator(new CapabilityListener() { @Override public boolean accept(URI capabilityListURI) { System.out.println("accept " + capabilityListURI); return dwcCL.equals(capabilityListURI.toString()); } @Override public void onCapabilityListItem(UrlItem item) { System.out.println("onCapabilityListItem " + item); } @Override public void onDescribedBy(URI capabilityListUrl, RsLn rsLn) { System.out.println("onDescribedBy " + rsLn.getHref()); } @Override public void onResourceList(URI capabilityListUrl, Urlset urlset) { System.out.println("onResourceList " + urlset); } @Override public void onChangeList(URI capabilityListUrl, Urlset urlset) { System.out.println("onChangeList " + urlset); } }); navigator.navigate(new URI(url)); //navigator.navigate(dwcCL); //navigator.navigate(nlgisCL); //navigator.navigate(someResourceList); // WARN n.k.dans.repo.arrdf.http.RsNavigator - Capability not implemented. //navigator.navigate(noRs); // throws javax.xml.bind.UnmarshalException } }
36.492308
146
0.653035
fcbeacc4aa8455aeb0543d5ae43ff0acc233dbb1
8,279
/** * */ package com.chatcor.biz.svc; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.chatcor.core.BaseService; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; /** * (파일 시스템 기반) Intent 학습문장 편집 기능 처리 기능 처리 Serive 클래스 * * @author Lewis * */ @Service("intentService") public class IntentServiceImpl extends BaseService implements IntentService { @Autowired public MainService mainService; @Override public Map<String, Object> listIntents(String prjName) throws Exception { Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("result", true); IOFileFilter filter = new NotFileFilter(new WildcardFileFilter("*".concat(SUFFIX_INTENTS).concat("*"))); Iterator<File> iter = FileUtils.iterateFiles(Paths.get(projectRoot, prjName, intentWork).toFile(), filter, TrueFileFilter.INSTANCE); List<String> files = new ArrayList<String>(); while (iter.hasNext()) { files.add(iter.next().getName()); } result.put("intent_files", files); return result; } @Override public boolean hasIntent(Map<String, Object> map) throws Exception { logger.debug("{}", map); File intentJson = Paths.get(projectRoot, map.get("project_id").toString(), intentWork, map.get("intent_name").toString().concat(SUFFIX_JSON)).toFile(); return intentJson.exists(); } @Override public Map<String, Object> createIntent(Map<String, Object> map) throws Exception { logger.debug("{}", map); Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("result", true); File intentJson = Paths.get(projectRoot, map.get("project_id").toString(), intentWork, map.get("intent_name").toString().concat(SUFFIX_JSON)).toFile(); File usersayJson = Paths.get(projectRoot, map.get("project_id").toString(), intentWork, map.get("intent_name").toString().concat(SUFFIX_INTENTS).concat(SUFFIX_JSON)).toFile(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.writeValue(intentJson, map.get("intent_obj")); objectMapper.writeValue(usersayJson, map.get("usersay_list")); return result; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public List<Map<String, Object>> validIntent(Map<String, Object> map) throws Exception { logger.debug("{}", map); List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> predicates = mainService.getPredicates(map.get("project_id").toString()); List<Map> lstIntent = (List<Map>) map.get("intent_list"); for (Map mapIntent : lstIntent) { Map<String, Object> mapValid = new LinkedHashMap<String, Object>(); mapValid.put("intent", mapIntent.get("intent")); List<Map<String, Object>> lstValid = new ArrayList<Map<String, Object>>(); int count = 0; List<String> list = (ArrayList<String>) mapIntent.get("predicates"); for (String prdName : list) { Map<String, Object> valid = new LinkedHashMap<String, Object>(); valid.put("value", prdName); Boolean boolPedicate = hasPredicate(prdName, predicates); valid.put("exists", boolPedicate); if (!boolPedicate.booleanValue()) { count ++; } lstValid.add(valid); } mapValid.put("status", count == 0); mapValid.put("valid_list", lstValid); result.add(mapValid); } return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Map<String, Object> getIntents(Map<String, Object> map) throws Exception { logger.debug("{}", map); ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); List<Map> list = null; File file = Paths.get(projectRoot, map.get("project_id").toString(), intentWork, map.get("intent_id").toString().concat(SUFFIX_INTENTS).concat(SUFFIX_JSON)).toFile(); try { list = mapper.readValue(file, List.class); } catch (JsonMappingException je) { InputStreamReader is = new InputStreamReader(new FileInputStream(file), "EUC-KR"); list = mapper.readValue(is, List.class); } Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("result", true); result.put("intent_id", map.get("intent_id")); List<String> intentList = new ArrayList<String>(); for (Map imap : list) { List<Map> lstData = (ArrayList<Map>) imap.get("data"); StringBuilder sbIntent = new StringBuilder(); for (Map dmap : lstData) { sbIntent.append(dmap.get("text")); } intentList.add(sbIntent.toString()); } result.put("intent_list", intentList); return result; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Map<String, Object> addIntent(Map<String, Object> map) throws Exception { logger.debug("{}", map); ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); List<Map> listUsersay = null; File file = Paths.get(projectRoot, map.get("project_id").toString(), intentWork, map.get("intent_id").toString().concat(SUFFIX_INTENTS).concat(SUFFIX_JSON)).toFile(); try { listUsersay = mapper.readValue(file, List.class); } catch (JsonMappingException je) { InputStreamReader is = new InputStreamReader(new FileInputStream(file), "EUC-KR"); listUsersay = mapper.readValue(is, List.class); } logger.debug("{}", listUsersay); listUsersay.add((Map) map.get("usersay")); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); mapper.writeValue(file, listUsersay); Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("result", true); result.put("intent_id", map.get("intent_id")); result.put("user_content", map.get("user_content")); return result; } private Boolean hasPredicate(String predicateName, List<Map<String, Object>> predicates) throws Exception { boolean result = false; for (Map<String, Object> map : predicates) { if (StringUtils.equals(predicateName, map.get("predicate_name").toString())) { result = true; break; } } return Boolean.valueOf(result); } @Override public Map<String, Object> rebuildIntents(Map<String, Object> map) throws Exception { logger.debug("{}", map); Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("result", true); File usersayJson = Paths.get(projectRoot, map.get("project_id").toString(), intentWork, map.get("intent_id").toString().concat(SUFFIX_INTENTS).concat(SUFFIX_JSON)).toFile(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.writeValue(usersayJson, map.get("usersay_list")); return result; } }
44.751351
183
0.652857
495cfad3546054ea29ac30012377415af2ac188c
1,662
/* * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.datastore.index.constraint; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * @since 6.5 */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = CardinalityPredicateFragment.class, name = "cardinality"), @Type(value = ConcreteDomainPredicateFragment.class, name = "concreteDomain"), @Type(value = DependencyPredicateFragment.class, name = "dependency"), @Type(value = DescriptionPredicateFragment.class, name = "description"), @Type(value = RelationshipPredicateFragment.class, name = "relationship"), }) public abstract class PredicateFragment extends ConceptModelComponentFragment { protected PredicateFragment( final String uuid, final boolean active, final long effectiveTime, final String author) { super(uuid, active, effectiveTime, author); } }
34.625
80
0.753309
af3d8960e084f0bd49b2aaabb0234b524442deb4
1,269
package ru.job4j.math; /** * Класс статических математических операций. * Демонстрация применения статического импорта. * * @author ViktorJava (gipsyscrew@gmail.com) * @version 0.1 * @since 9/4/2021 */ public class MathFunction { /** * Сумма двух чисел. * * @param first Первое число. * @param second Второе число. * @return Сумма двух чисел. */ public static double sum(double first, double second) { return first + second; } /** * Произведение двух чисел. * * @param first Первое число. * @param second Второе число. * @return Произведение двух чисел. */ public static double multiply(double first, double second) { return first * second; } /** * Частное двух чисел. * * @param first Первое число. * @param second Второе число. * @return Частное двух чисел. */ public static double divide(double first, double second) { return first / second; } /** * Разность двух чисел. * * @param first Первое число. * @param second Второе число. * @return Разность двух чисел. */ public static double minus(double first, double second) { return first - second; } }
22.660714
64
0.598897
ed0ad8e5ad5c3bfce563758bb26bb0c777ea85f4
3,615
/* */ package mcheli.mcheli; /* */ import java.io.File; /* */ import java.io.PrintWriter; /* */ import java.util.ArrayList; /* */ import java.util.LinkedHashMap; /* */ import mcheli.MCH_Lib; /* */ /* */ public class MCH_SoundsJson { /* */ public static boolean update(String path) { /* 10 */ boolean result = true; /* 11 */ path = path.replace('\\', '/'); /* 12 */ File dir = new File(path + "sounds"); /* 13 */ File[] files = dir.listFiles((FileFilter)new Object()); /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 25 */ int cnt = 0; /* */ /* 27 */ PrintWriter pw = null; /* */ /* */ /* */ try { /* 31 */ File file = new File(path + "sounds.json"); /* */ /* 33 */ pw = new PrintWriter(file); /* */ /* 35 */ pw.println("{"); /* */ /* 37 */ if (files != null) { /* */ /* 39 */ LinkedHashMap<String, ArrayList<String>> map = new LinkedHashMap<String, ArrayList<String>>(); /* 40 */ for (File f : files) { /* */ /* 42 */ String name = f.getName().toLowerCase(); /* 43 */ int ei = name.lastIndexOf("."); /* 44 */ name = name.substring(0, ei); /* 45 */ String key = name; /* 46 */ char c = key.charAt(key.length() - 1); /* 47 */ if (c >= '0' && c <= '9') /* */ { /* 49 */ key = key.substring(0, key.length() - 1); /* */ } /* */ /* 52 */ if (!map.containsKey(key)) /* */ { /* 54 */ map.put(key, new ArrayList<String>()); /* */ } /* 56 */ ((ArrayList<String>)map.get(key)).add(name); /* */ } /* 58 */ for (String key : map.keySet()) { /* */ /* 60 */ cnt++; /* 61 */ ArrayList<String> list = map.get(key); /* 62 */ String line = ""; /* */ /* 64 */ line = "\"" + key + "\": {\"category\": \"master\",\"sounds\": ["; /* 65 */ for (int fi = 0; fi < list.size(); fi++) /* */ { /* 67 */ line = line + ((fi > 0) ? "," : "") + "\"" + (String)list.get(fi) + "\""; /* */ } /* 69 */ line = line + "]}"; /* */ /* 71 */ if (cnt < map.size()) line = line + ","; /* 72 */ pw.println(line); /* */ } /* */ } /* */ /* 76 */ pw.println("}"); /* 77 */ pw.println(""); /* */ /* 79 */ result = true; /* */ } /* 81 */ catch (IOException e) { /* */ /* 83 */ result = false; /* 84 */ e.printStackTrace(); /* */ } /* */ finally { /* */ /* 88 */ if (pw != null) /* */ { /* 90 */ pw.close(); /* */ } /* */ } /* */ /* 94 */ if (result) { /* */ /* 96 */ MCH_Lib.Log("Update sounds.json. %d sounds", new Object[] { Integer.valueOf(cnt) }); /* */ } /* */ else { /* */ /* 100 */ MCH_Lib.Log("Failed sounds.json update! %d sounds", new Object[] { Integer.valueOf(cnt) }); /* */ } /* 102 */ return result; /* */ } /* */ } /* Location: C:\Users\danie\Desktop\Mod Porting Tools\MC1.7.10_mcheli_1.0.3.jar!\mcheli\mcheli\MCH_SoundsJson.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
32.863636
128
0.365422
0a7c84b36933f08ee9cbb1021099e3990d0dbaed
10,631
package com.serviciomecanico.serviciomecanico.Visualizar; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import com.bumptech.glide.Glide; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.Query; import com.serviciomecanico.serviciomecanico.Adaptadores.AutomovilAdapter; import com.serviciomecanico.serviciomecanico.Adaptadores.ClienteAdapter; import com.serviciomecanico.serviciomecanico.Conexion.Conexion; import com.serviciomecanico.serviciomecanico.Consultar.ConsultarAutomovilActivity; import com.serviciomecanico.serviciomecanico.Consultar.ConsultarClienteActivity; import com.serviciomecanico.serviciomecanico.MenuPrincipalActivity; import com.serviciomecanico.serviciomecanico.Modelo.Automovil; import com.serviciomecanico.serviciomecanico.Modelo.Cliente; import com.serviciomecanico.serviciomecanico.R; import com.serviciomecanico.serviciomecanico.Registrar.RegistrarAutomovilActivity; import com.serviciomecanico.serviciomecanico.Registrar.RegistrarClienteActivity; import com.serviciomecanico.serviciomecanico.Sesion.IniciarSeionActivity; public class VisualizarAutomovilesActivity extends AppCompatActivity { Conexion conexion = new Conexion(); DatabaseReference firebase; RecyclerView rcv_visualizar_automoviles; FloatingActionButton btn_float_registrar_automoviles; ProgressBar progressBar_visualizar_automoviles; EditText searchAutomovil; String nombrecliente; //Adapter FirebaseRecyclerAdapter<Automovil, AutomovilAdapter.ViewHolder> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_visualizar_automoviles); firebase = conexion.conexion(); //Toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Lista de automóviles"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); rcv_visualizar_automoviles = findViewById(R.id.rcv_visualizar_automoviles); btn_float_registrar_automoviles = findViewById(R.id.btn_float_registrar_automoviles); progressBar_visualizar_automoviles = findViewById(R.id.progressBar_visualizar_automoviles); searchAutomovil = findViewById(R.id.searchAutomovil); progressBar_visualizar_automoviles.setVisibility(View.VISIBLE); nombrecliente = getIntent().getStringExtra("nombrecliente"); //Setear al linerlayaour manager nuestro reciclerView LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); rcv_visualizar_automoviles.setLayoutManager(linearLayoutManager); //FirebaseUI definido para llamar de nuestro firebase la lista adapter = new FirebaseRecyclerAdapter<Automovil, AutomovilAdapter.ViewHolder>( /*Clase que utilizaremos*/Automovil.class, /*La interfaz grafica*/R.layout.automovil, /*ViewHolder archivo ClienteAdapter*/AutomovilAdapter.ViewHolder.class, /*La referencia de firebase donde buscara*/firebase.child("Cliente").child(nombrecliente).child("Automovil") ) { @Override protected void populateViewHolder(final AutomovilAdapter.ViewHolder viewHolder, Automovil model, int position) { viewHolder.txv_automovil_placa.setText(model.getPlaca()); viewHolder.txv_automovil_marca.setText(model.getMarca()); viewHolder.txv_automovil_linea.setText(model.getLinea()); String urlchida = model.getUrlImagenAutomovil(); Glide.with(getApplicationContext()) .load(urlchida) .into(viewHolder.imageView_automovil); final String modelo = model.getModelo(); final String color = model.getColor(); final String urlimagen = model.getUrlImagenAutomovil(); viewHolder.cdv_automovil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VisualizarAutomovilesActivity.this, ConsultarAutomovilActivity.class); intent.putExtra("placa",viewHolder.txv_automovil_placa.getText().toString()); intent.putExtra("marca",viewHolder.txv_automovil_marca.getText().toString()); intent.putExtra("linea",viewHolder.txv_automovil_linea.getText().toString()); intent.putExtra("modelo",modelo); intent.putExtra("color",color); intent.putExtra("urlimagen",urlimagen); intent.putExtra("nombre",nombrecliente); startActivity(intent); } }); progressBar_visualizar_automoviles.setVisibility(View.INVISIBLE); } }; rcv_visualizar_automoviles.setAdapter(adapter); //Scroll funcion boton rcv_visualizar_automoviles.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if(newState == RecyclerView.SCROLL_STATE_IDLE){ btn_float_registrar_automoviles.show(); } } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if(dy>0 || dy<0 && btn_float_registrar_automoviles.isShown()){ btn_float_registrar_automoviles.hide(); } } }); } public void btn_float_registrar_automoviles (View view){ Intent intent = new Intent(VisualizarAutomovilesActivity.this, RegistrarAutomovilActivity.class); intent.putExtra("nombrecliente",nombrecliente); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: Intent intent = new Intent(VisualizarAutomovilesActivity.this, MenuPrincipalActivity.class); startActivity(intent); finish(); return true; default: return super.onOptionsItemSelected(item); } } public void buscarAutomovil(View view){ //FirebaseUI definido para llamar de nuestro firebase la lista String text = searchAutomovil.getText().toString(); Query fireBaseSearch = firebase.child("Cliente").child(nombrecliente).child("Automovil").orderByChild("placa").startAt(text).endAt(text + "\uf8ff"); adapter = new FirebaseRecyclerAdapter<Automovil, AutomovilAdapter.ViewHolder>( /*Clase que utilizaremos*/Automovil.class, /*La interfaz grafica*/R.layout.automovil, /*ViewHolder archivo ClienteAdapter*/AutomovilAdapter.ViewHolder.class, /*La referencia de firebase donde buscara*/fireBaseSearch ) { @Override protected void populateViewHolder(final AutomovilAdapter.ViewHolder viewHolder, Automovil model, int position) { viewHolder.txv_automovil_placa.setText(model.getPlaca()); viewHolder.txv_automovil_marca.setText(model.getMarca()); viewHolder.txv_automovil_linea.setText(model.getLinea()); String urlchida = model.getUrlImagenAutomovil(); Glide.with(getApplicationContext()) .load(urlchida) .into(viewHolder.imageView_automovil); final String modelo = model.getModelo(); final String color = model.getColor(); final String urlimagen = model.getUrlImagenAutomovil(); viewHolder.cdv_automovil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(VisualizarAutomovilesActivity.this, ConsultarAutomovilActivity.class); intent.putExtra("placa",viewHolder.txv_automovil_placa.getText().toString()); intent.putExtra("marca",viewHolder.txv_automovil_marca.getText().toString()); intent.putExtra("linea",viewHolder.txv_automovil_linea.getText().toString()); intent.putExtra("modelo",modelo); intent.putExtra("color",color); intent.putExtra("urlimagen",urlimagen); intent.putExtra("nombre",nombrecliente); startActivity(intent); } }); progressBar_visualizar_automoviles.setVisibility(View.INVISIBLE); } }; rcv_visualizar_automoviles.setAdapter(adapter); //Scroll funcion boton rcv_visualizar_automoviles.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if(newState == RecyclerView.SCROLL_STATE_IDLE){ btn_float_registrar_automoviles.show(); } } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if(dy>0 || dy<0 && btn_float_registrar_automoviles.isShown()){ btn_float_registrar_automoviles.hide(); } } }); } }
48.322727
156
0.667294
bda425c81fc8db369ab3a8bfc30c90e20554e294
1,343
package com.salescompany.productservice.infrastructure.persistence.entity; import com.salescompany.productservice.domain.product.Product; import com.salescompany.productservice.domain.product.type.Category; import com.salescompany.productservice.domain.warranty_policy.WarrantyPolicy; import com.salescompany.productservice.infrastructure.persistence.entity.base.BaseEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.SuperBuilder; import javax.persistence.*; import java.math.BigDecimal; import java.util.List; @NoArgsConstructor @AllArgsConstructor @SuperBuilder @Entity @Getter @Table(name = "products") @ToString public class ProductEntity extends BaseEntity { private String name; private BigDecimal price; private Category category; @ManyToOne @JoinColumn(name = "producer_id") private ProducerEntity producer; @OneToOne private WarrantyPolicyEntity warrantyPolicy; public Product toProduct() { return Product.builder() .id(id) .name(name) .price(price) .category(category) .producer(producer.toProducer()) .warrantyPolicy(warrantyPolicy.toWarrantyPolicy()) .build(); } }
27.408163
89
0.731943
0a6638715e450ccca6f5746d95fa8b08d2146b5b
3,042
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.http; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.client.util.BufferingResponseListener; import org.eclipse.jetty.http.HttpMethod; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.util.ssl.SslContextFactory; public class HttpTraceTestSupport { public static List<Object[]> getTestParameters() { return Arrays.asList(new Object[][] { //value is empty {"http.enableTrace=", HttpStatus.FORBIDDEN_403}, //default, trace method not specified {null, HttpStatus.FORBIDDEN_403}, // enable http trace method {"http.enableTrace=true", HttpStatus.OK_200}, // disable trace method {"http.enableTrace=false", HttpStatus.FORBIDDEN_403} }); } public static void testHttpTraceEnabled(final String uri, final int expectedStatus) throws Exception { //IC see: https://issues.apache.org/jira/browse/AMQ-7289 testHttpTraceEnabled(uri, expectedStatus, new SslContextFactory.Client()); } public static void testHttpTraceEnabled(final String uri, final int expectedStatus, SslContextFactory sslContextFactory) throws Exception { HttpClient httpClient = sslContextFactory != null ? new HttpClient(sslContextFactory) : new HttpClient(new SslContextFactory.Client()); httpClient.start(); final CountDownLatch latch = new CountDownLatch(1); Request request = httpClient.newRequest(uri).method(HttpMethod.TRACE); final AtomicInteger status = new AtomicInteger(); request.send(new BufferingResponseListener() { @Override public void onComplete(Result result) { status.set(result.getResponse().getStatus()); latch.countDown(); } }); latch.await(); assertEquals(expectedStatus, status.get()); } }
41.108108
106
0.708087
c94dbec2a4204d6f074edee1d8752b072084e8d4
2,755
import java.util.Scanner; import java.util.Random; public class CombatRoom extends Room{ private Monster monster; private static final int ATTACK = 1; private static final int CHECKBACKPACK = 2; private static final int RUNAWAY = 3; private Random randomGenerator = new Random(); private Scanner keyboard = new Scanner(System.in); private boolean isFighting = true; private boolean isAlive = true; private boolean isEnemyAlive = true; private static boolean runAway = false; private String afterCombatDescription; public CombatRoom(String description, Monster monster, String secondDescription){ //Constructor takes an enemy parameter, that I should be able to pass on. super(description); this.monster = monster; this.afterCombatDescription = secondDescription; } public void doRoomFunction(){ this.runAway = false; printRoomDescription(); while(isEnemyAlive && isFighting && isAlive && !runAway){ System.out.println(this.monster.getCharacterName() + "'s health: " + this.monster.getCharacterHealth()); System.out.println(Hero.hero.getCharacterName() + "'s health: " + Hero.hero.getCharacterHealth()); Hero.hero.takeTurn(this.monster); this.monster.takeTurn(Hero.hero); checkCombatStatus(); //This should be replace by a take turn method. //Player.takeTurn(); //Enemy.takeTurn(); //And thats the loop. } if (!isEnemyAlive){ System.out.println(afterCombatDescription); //Drop enemy item into backpack. if (this.monster.getMonsterItem() != null){ BackPack.addToBackPack(this.monster.getMonsterItem()); System.out.println("The " + this.monster.getCharacterName() + " dropped a " + this.monster.getMonsterItem()); } } } private void checkCombatStatus(){ //Check if you're dead, if monster is dead, if you ran away. if (Hero.hero.getCharacterHealth() <= 0){ System.out.println("You have been killed."); this.isAlive = false; SuperAdventure.endGame(); } else if (this.monster.getCharacterHealth() <= 0){ System.out.println("You have defeated the " + this.monster.getCharacterName()); this.isEnemyAlive = false; } } private void printRoomDescription(){ System.out.println(super.getDescription()); } public static void runAway(){ System.out.println("You ran away from combat!"); runAway = true; SuperAdventure.currentRoom = SuperAdventure.currentRoom.getEast(); } }
40.514706
159
0.629038
8933ce73932f1eac696bd454bf368e694a6f333c
14,620
/* * Copyright (C) 2019 The Android Open Source Project * * 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.android.wifitrackerlib; import static androidx.core.util.Preconditions.checkNotNull; import static com.android.wifitrackerlib.PasspointWifiEntry.uniqueIdToPasspointWifiEntryKey; import static com.android.wifitrackerlib.StandardWifiEntry.ScanResultKey; import static com.android.wifitrackerlib.StandardWifiEntry.StandardWifiEntryKey; import static java.util.stream.Collectors.toMap; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkScoreManager; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.net.wifi.hotspot2.PasspointConfiguration; import android.os.Handler; import android.util.Log; import android.util.Pair; import androidx.annotation.AnyThread; import androidx.annotation.GuardedBy; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; import androidx.lifecycle.Lifecycle; import java.time.Clock; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.function.Function; import java.util.stream.Collectors; /** * Wi-Fi tracker that provides all Wi-Fi related data to the Saved Networks page. * * These include * - List of WifiEntries for all saved networks, dynamically updated with ScanResults * - List of WifiEntries for all saved subscriptions, dynamically updated with ScanResults */ public class SavedNetworkTracker extends BaseWifiTracker { private static final String TAG = "SavedNetworkTracker"; private final SavedNetworkTrackerCallback mListener; // Lock object for data returned by the public API private final Object mLock = new Object(); @GuardedBy("mLock") private final List<WifiEntry> mSavedWifiEntries = new ArrayList<>(); @GuardedBy("mLock") private final List<WifiEntry> mSubscriptionWifiEntries = new ArrayList<>(); // Cache containing saved StandardWifiEntries. Must be accessed only by the worker thread. private final List<StandardWifiEntry> mStandardWifiEntryCache = new ArrayList<>(); // Cache containing saved PasspointWifiEntries. Must be accessed only by the worker thread. private final Map<String, PasspointWifiEntry> mPasspointWifiEntryCache = new HashMap<>(); public SavedNetworkTracker(@NonNull Lifecycle lifecycle, @NonNull Context context, @NonNull WifiManager wifiManager, @NonNull ConnectivityManager connectivityManager, @NonNull NetworkScoreManager networkScoreManager, @NonNull Handler mainHandler, @NonNull Handler workerHandler, @NonNull Clock clock, long maxScanAgeMillis, long scanIntervalMillis, @Nullable SavedNetworkTracker.SavedNetworkTrackerCallback listener) { super(lifecycle, context, wifiManager, connectivityManager, networkScoreManager, mainHandler, workerHandler, clock, maxScanAgeMillis, scanIntervalMillis, listener, TAG); mListener = listener; } /** * Returns a list of WifiEntries for all saved networks. If a network is in range, the * corresponding WifiEntry will be updated with live ScanResult data. * @return */ @AnyThread @NonNull public List<WifiEntry> getSavedWifiEntries() { synchronized (mLock) { return new ArrayList<>(mSavedWifiEntries); } } /** * Returns a list of WifiEntries for all saved subscriptions. If a subscription network is in * range, the corresponding WifiEntry will be updated with live ScanResult data. * @return */ @AnyThread @NonNull public List<WifiEntry> getSubscriptionWifiEntries() { synchronized (mLock) { return new ArrayList<>(mSubscriptionWifiEntries); } } @WorkerThread @Override protected void handleOnStart() { updateStandardWifiEntryConfigs(mWifiManager.getConfiguredNetworks()); updatePasspointWifiEntryConfigs(mWifiManager.getPasspointConfigurations()); conditionallyUpdateScanResults(true /* lastScanSucceeded */); updateSavedWifiEntries(); updateSubscriptionWifiEntries(); } @WorkerThread @Override protected void handleWifiStateChangedAction() { conditionallyUpdateScanResults(true /* lastScanSucceeded */); updateSavedWifiEntries(); updateSubscriptionWifiEntries(); } @WorkerThread @Override protected void handleScanResultsAvailableAction(@Nullable Intent intent) { checkNotNull(intent, "Intent cannot be null!"); conditionallyUpdateScanResults(intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, true /* defaultValue */)); updateSavedWifiEntries(); updateSubscriptionWifiEntries(); } @WorkerThread @Override protected void handleConfiguredNetworksChangedAction(@Nullable Intent intent) { checkNotNull(intent, "Intent cannot be null!"); updateStandardWifiEntryConfigs(mWifiManager.getConfiguredNetworks()); updatePasspointWifiEntryConfigs(mWifiManager.getPasspointConfigurations()); updateSavedWifiEntries(); updateSubscriptionWifiEntries(); } @WorkerThread @Override protected void handleNetworkScoreCacheUpdated() { for (StandardWifiEntry entry : mStandardWifiEntryCache) { entry.onScoreCacheUpdated(); } for (PasspointWifiEntry entry : mPasspointWifiEntryCache.values()) { entry.onScoreCacheUpdated(); } } private void updateSavedWifiEntries() { synchronized (mLock) { mSavedWifiEntries.clear(); mSavedWifiEntries.addAll(mStandardWifiEntryCache); Collections.sort(mSavedWifiEntries); if (isVerboseLoggingEnabled()) { Log.v(TAG, "Updated SavedWifiEntries: " + Arrays.toString(mSavedWifiEntries.toArray())); } } notifyOnSavedWifiEntriesChanged(); } private void updateSubscriptionWifiEntries() { synchronized (mLock) { mSubscriptionWifiEntries.clear(); mSubscriptionWifiEntries.addAll(mPasspointWifiEntryCache.values()); Collections.sort(mSubscriptionWifiEntries); if (isVerboseLoggingEnabled()) { Log.v(TAG, "Updated SubscriptionWifiEntries: " + Arrays.toString(mSubscriptionWifiEntries.toArray())); } } notifyOnSubscriptionWifiEntriesChanged(); } private void updateStandardWifiEntryScans(@NonNull List<ScanResult> scanResults) { checkNotNull(scanResults, "Scan Result list should not be null!"); // Group scans by StandardWifiEntry key final Map<ScanResultKey, List<ScanResult>> scanResultsByKey = scanResults.stream() .collect(Collectors.groupingBy(StandardWifiEntry.ScanResultKey::new)); // Iterate through current entries and update each entry's scan results mStandardWifiEntryCache.forEach(entry -> { // Update scan results if available, or set to null. entry.updateScanResultInfo( scanResultsByKey.get(entry.getStandardWifiEntryKey().getScanResultKey())); }); } private void updatePasspointWifiEntryScans(@NonNull List<ScanResult> scanResults) { checkNotNull(scanResults, "Scan Result list should not be null!"); Set<String> seenKeys = new TreeSet<>(); List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> matchingWifiConfigs = mWifiManager.getAllMatchingWifiConfigs(scanResults); for (Pair<WifiConfiguration, Map<Integer, List<ScanResult>>> pair : matchingWifiConfigs) { final WifiConfiguration wifiConfig = pair.first; final String key = uniqueIdToPasspointWifiEntryKey(wifiConfig.getKey()); seenKeys.add(key); // Skip in case we don't have a PasspointWifiEntry for the returned unique identifier. if (!mPasspointWifiEntryCache.containsKey(key)) { continue; } mPasspointWifiEntryCache.get(key).updateScanResultInfo(wifiConfig, pair.second.get(WifiManager.PASSPOINT_HOME_NETWORK), pair.second.get(WifiManager.PASSPOINT_ROAMING_NETWORK)); } for (PasspointWifiEntry entry : mPasspointWifiEntryCache.values()) { if (!seenKeys.contains(entry.getKey())) { // No AP in range; set scan results and connection config to null. entry.updateScanResultInfo(null /* wifiConfig */, null /* homeScanResults */, null /* roamingScanResults */); } } } /** * Conditionally updates the WifiEntry scan results based on the current wifi state and * whether the last scan succeeded or not. */ @WorkerThread private void conditionallyUpdateScanResults(boolean lastScanSucceeded) { if (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) { updateStandardWifiEntryScans(Collections.emptyList()); updatePasspointWifiEntryScans(Collections.emptyList()); return; } long scanAgeWindow = mMaxScanAgeMillis; if (lastScanSucceeded) { // Scan succeeded, cache new scans mScanResultUpdater.update(mWifiManager.getScanResults()); } else { // Scan failed, increase scan age window to prevent WifiEntry list from // clearing prematurely. scanAgeWindow += mScanIntervalMillis; } updateStandardWifiEntryScans(mScanResultUpdater.getScanResults(scanAgeWindow)); updatePasspointWifiEntryScans(mScanResultUpdater.getScanResults(scanAgeWindow)); } private void updateStandardWifiEntryConfigs(@NonNull List<WifiConfiguration> configs) { checkNotNull(configs, "Config list should not be null!"); // Group configs by StandardWifiEntry key final Map<StandardWifiEntryKey, List<WifiConfiguration>> wifiConfigsByKey = configs.stream() .filter(config -> !config.carrierMerged) .collect(Collectors.groupingBy(StandardWifiEntryKey::new)); // Iterate through current entries and update each entry's config mStandardWifiEntryCache.removeIf(entry -> { // Update config if available, or set to null (unsaved) entry.updateConfig(wifiConfigsByKey.remove(entry.getStandardWifiEntryKey())); // Entry is now unsaved, remove it. return !entry.isSaved(); }); // Create new entry for each unmatched config for (StandardWifiEntryKey key : wifiConfigsByKey.keySet()) { mStandardWifiEntryCache.add(new StandardWifiEntry(mContext, mMainHandler, key, wifiConfigsByKey.get(key), null, mWifiManager, mWifiNetworkScoreCache, true /* forSavedNetworksPage */)); } } @WorkerThread private void updatePasspointWifiEntryConfigs(@NonNull List<PasspointConfiguration> configs) { checkNotNull(configs, "Config list should not be null!"); final Map<String, PasspointConfiguration> passpointConfigsByKey = configs.stream().collect(toMap( (config) -> uniqueIdToPasspointWifiEntryKey(config.getUniqueId()), Function.identity())); // Iterate through current entries and update each entry's config or remove if no config // matches the entry anymore. mPasspointWifiEntryCache.entrySet().removeIf((entry) -> { final PasspointWifiEntry wifiEntry = entry.getValue(); final String key = wifiEntry.getKey(); final PasspointConfiguration cachedConfig = passpointConfigsByKey.remove(key); if (cachedConfig != null) { wifiEntry.updatePasspointConfig(cachedConfig); return false; } else { return true; } }); // Create new entry for each unmatched config for (String key : passpointConfigsByKey.keySet()) { mPasspointWifiEntryCache.put(key, new PasspointWifiEntry(mContext, mMainHandler, passpointConfigsByKey.get(key), mWifiManager, mWifiNetworkScoreCache, true /* forSavedNetworksPage */)); } } /** * Posts onSavedWifiEntriesChanged callback on the main thread. */ @WorkerThread private void notifyOnSavedWifiEntriesChanged() { if (mListener != null) { mMainHandler.post(mListener::onSavedWifiEntriesChanged); } } /** * Posts onSubscriptionWifiEntriesChanged callback on the main thread. */ @WorkerThread private void notifyOnSubscriptionWifiEntriesChanged() { if (mListener != null) { mMainHandler.post(mListener::onSubscriptionWifiEntriesChanged); } } /** * Listener for changes to the list of saved and subscription WifiEntries * * These callbacks must be run on the MainThread. */ public interface SavedNetworkTrackerCallback extends BaseWifiTracker.BaseWifiTrackerCallback { /** * Called when there are changes to * {@link #getSavedWifiEntries()} */ @MainThread void onSavedWifiEntriesChanged(); /** * Called when there are changes to * {@link #getSubscriptionWifiEntries()} */ @MainThread void onSubscriptionWifiEntriesChanged(); } }
39.945355
100
0.679754
89722e6ec23e5a8d87ec77e7766fbe8c03d97faf
2,064
/*- * ============LICENSE_START======================================================= * ONAP : APPC * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Copyright (C) 2017 Amdocs * ============================================================================= * 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. * * ============LICENSE_END========================================================= */ package org.onap.appc.validationpolicy; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URISyntaxException; public class MockRequestValidationPolicy extends RequestValidationPolicy { @Override protected String getPolicyJson(){ String policyJson =null; try{ policyJson = readInput("/org/onap/appc/validationpolicy/validation-policy.json"); } catch (Exception e){ throw new RuntimeException(e); } return policyJson; } private String readInput(String inputFile) throws URISyntaxException, IOException { File file = new File(this.getClass().getResource(inputFile).toURI()); byte[] bFile = new byte[(int) file.length()]; FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(bFile); fileInputStream.close(); return new String(bFile); } }
36.857143
93
0.569283
ab0c2c836f1b308102b2b0290e51f263dfd139d3
705
package com.moment.common.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; public class ConfigUtil { private static Properties pro; static{ //InputStream input=ConfigUtil.class //.getResourceAsStream("/conf/config.properties"); InputStream input=ConfigUtil.class.getClassLoader() .getResourceAsStream("config.properties"); pro=new Properties(); try { pro.load(new InputStreamReader(input,"UTF-8")); input.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); // 注释 } } public static String getValue(String key){ return pro.getProperty(key); } }
23.5
54
0.72766
698aad3f28e390a47acd3f7e5166f86c2245dd98
2,403
package com.elderbyte.kafka.producer; import com.elderbyte.kafka.messages.InvalidMessageException; import com.elderbyte.messaging.annotations.MessageHeader; import com.elderbyte.messaging.annotations.MessageKey; import com.elderbyte.messaging.annotations.Tombstone; import org.junit.Test; import static org.junit.Assert.*; public class AnnotationKafkaMessageBuilderTest { public static class MessageBlob { @MessageKey public String id; @MessageHeader public String test; @MessageHeader("yes.yes") public int age; public String ignore; } @Tombstone public static class MessageBlobTomb { @MessageKey public String id; @MessageHeader public String test; @MessageHeader("yes.yes") public int age; public String ignore; } public static class MessageBlobNoKey { public String id; @MessageHeader public String test; @MessageHeader("yes.yes") public int age; public String ignore; } @Test(expected = InvalidMessageException.class) public void build_key_null_fail() { var obj = new MessageBlob(); AnnotationKafkaMessageBuilder.build(obj); } @Test(expected = InvalidMessageException.class) public void build_missing_key() { var obj = new MessageBlobNoKey(); AnnotationKafkaMessageBuilder.build(obj); } @Test public void build_good() { var obj = new MessageBlob(); obj.id = "jup"; var msg = AnnotationKafkaMessageBuilder.build(obj); assertEquals("0", msg.getHeaders().get("yes.yes")); } @Test public void build_2() { var obj = new MessageBlob(); obj.id = "jup"; obj.test = "mock"; obj.age = 99; var msg = AnnotationKafkaMessageBuilder.build(obj); assertEquals("mock", msg.getHeaders().get("test")); assertEquals("99", msg.getHeaders().get("yes.yes")); } @Test public void build_tomb() { var obj = new MessageBlobTomb(); obj.id = "jup"; obj.test = "mock"; obj.age = 99; var msg = AnnotationKafkaMessageBuilder.build(obj); assertEquals("mock", msg.getHeaders().get("test")); assertEquals("99", msg.getHeaders().get("yes.yes")); assertNull(msg.getValue()); } }
24.272727
60
0.622971
bbcb126df6e9b8668dc98b620e2944317c6b1b50
4,440
package neo4jTraversal; import java.util.ArrayList; import java.util.HashMap; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.PathExpander; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.traversal.BranchState; import neo4jDatabase.DBUtility; import neo4jEnum.NodeLabels; import neo4jEnum.RelTypes; import neo4jGateSets.ANDSet; import neo4jGateSets.GateSet; import neo4jGateSets.MOONSet; import neo4jGateSets.NOTSet; import neo4jGateSets.ORSet; import neo4jGateSets.ResultGateSet; import neo4jGateSets.ConnectorGateSet; import neo4jGateSets.XORSet; import neo4jUtility.PrintUtility; public class CFTPathExpanderSplit implements PathExpander<TraversalState> { @Override public Iterable<Relationship> expand(Path path, BranchState<TraversalState> branchState) { ArrayList<Relationship> rels = new ArrayList<>(); if (!MainTraversal.cycleFound()) { Node endNode = path.endNode(); TraversalState ts = null; GateSet nextGateSet = null; if (branchState.getState() == null) { if (endNode.hasLabel(NodeLabels.CFT_Outport) || endNode.hasLabel(NodeLabels.CFT_Inport_Instance)) { ResultGateSet resultSet = new ResultGateSet(endNode); MainTraversal.addResultGateSet(endNode, resultSet); nextGateSet = resultSet; ts = new TraversalState(nextGateSet); ts.addNodeToSimple(endNode); for (Relationship rel : endNode.getRelationships(RelTypes.Failure_Propagation, Direction.INCOMING)) { rels.add(rel); } } else { PrintUtility.printError("Invalid Label! The Traversal cannot be started with this Node."); } } else { ts = new TraversalState(branchState.getState()); MainTraversal.cycleFound(ts.addNodeToSimple(endNode)); if (endNode.hasLabel(NodeLabels.CFT_Outport)) { // Handled by the Evaluator. } else { if (endNode.hasLabel(NodeLabels.CFT_Inport_Instance)) { PrintUtility.printError("Invalid Label! The Traversal cannot continue with this Node."); } else { if (endNode.hasLabel(NodeLabels.CFT_Basic_Event)) { ts.addNodeToLastGateSet(endNode); } else { if (endNode.hasLabel(NodeLabels.CFT_Outport_Instance)) { HashMap<Node, Node> nextInportMap = new HashMap<Node, Node>(); Node outport = endNode.getSingleRelationship(RelTypes.Is_Instance_Of, Direction.OUTGOING).getEndNode(); rels.add(endNode.getSingleRelationship(RelTypes.Is_Instance_Of, Direction.OUTGOING)); // Add Relationship to Outport for (Node inportInstance : DBUtility.getInportInstances(endNode)) { // Map Inports to InportInstances nextInportMap.put(inportInstance.getSingleRelationship(RelTypes.Is_Instance_Of, Direction.OUTGOING).getEndNode(), inportInstance); } nextGateSet = new ConnectorGateSet(endNode, nextInportMap); nextGateSet.addNode(outport); ts.addGateSetToLastGateSet(nextGateSet); } else { if (endNode.hasLabel(NodeLabels.CFT_Inport)) { ts.addNodeToLastGateSet(endNode); } else { if (endNode.hasLabel(NodeLabels.CFT_AND_Gate)) { nextGateSet = new ANDSet(endNode); } else { if (endNode.hasLabel(NodeLabels.CFT_OR_Gate)) { nextGateSet = new ORSet(endNode); } else { if (endNode.hasLabel(NodeLabels.CFT_MOON_Gate)) { nextGateSet = new MOONSet(endNode); } else { if (endNode.hasLabel(NodeLabels.CFT_XOR_Gate)) { nextGateSet = new XORSet(endNode); } else { if (endNode.hasLabel(NodeLabels.CFT_NOT_Gate)) { nextGateSet = new NOTSet(endNode); } else { PrintUtility.printError("Invalid Label! The Traversal cannot continue with this Node."); } } } } } ts.addGateSetToLastGateSet(nextGateSet); for (Relationship rel : endNode.getRelationships(RelTypes.Failure_Propagation, Direction.INCOMING)) { rels.add(rel); } } } } } } } if (nextGateSet != null) { ts.setLastGateSet(nextGateSet); } branchState.setState(ts); } return rels; } @Override public PathExpander<TraversalState> reverse() { return null; } }
27.407407
138
0.673423