code
stringlengths
73
34.1k
label
stringclasses
1 value
public void registerTemplateEngine(Class<? extends TemplateEngine> engineClass) { if (templateEngine != null) { log.debug("Template engine already registered, ignoring '{}'", engineClass.getName()); return; } try { TemplateEngine engine = engineClass.newInsta...
java
public static String getPippoVersion() { // and the key inside the properties file. String pippoVersionPropertyKey = "pippo.version"; String pippoVersion; try { Properties prop = new Properties(); URL url = ClasspathUtils.locateOnClasspath(PippoConstants.LOCATIO...
java
@Override public Object layout(Map model, String templateName, boolean inheritModel) throws IOException, ClassNotFoundException { Map submodel = inheritModel ? forkModel(model) : model; URL resource = engine.resolveTemplate(templateName); PippoGroovyTemplate template = (PippoGroo...
java
public static EmbeddedCacheManager create(long idleTime) { Configuration configuration = new ConfigurationBuilder() .expiration().maxIdle(idleTime, TimeUnit.SECONDS) .build(); return new DefaultCacheManager(configuration); }
java
public static EmbeddedCacheManager create(String file) { try { return new DefaultCacheManager(file); } catch (IOException ex) { log.error("", ex); throw new PippoRuntimeException(ex); } }
java
public Response bind(String name, Object model) { getLocals().put(name, model); return this; }
java
public Response removeCookie(String name) { Cookie cookie = new Cookie(name, ""); cookie.setSecure(true); cookie.setMaxAge(0); addCookie(cookie); return this; }
java
public Response noCache() { checkCommitted(); // no-cache headers for HTTP/1.1 header(HttpConstants.Header.CACHE_CONTROL, "no-store, no-cache, must-revalidate"); // no-cache headers for HTTP/1.1 (IE) header(HttpConstants.Header.CACHE_CONTROL, "post-check=0, pre-check=0"); ...
java
public String getContentType() { String contentType = getHeader(HttpConstants.Header.CONTENT_TYPE); if (contentType == null) { contentType = httpServletResponse.getContentType(); } return contentType; }
java
public Response contentType(String contentType) { checkCommitted(); header(HttpConstants.Header.CONTENT_TYPE, contentType); httpServletResponse.setContentType(contentType); return this; }
java
public static String getHashSHA256(String text) { byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1); return getHashSHA256(bytes); }
java
public static String getHashSHA1(String text) { byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1); return getHashSHA1(bytes); }
java
public static String getHashMD5(String text) { byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1); return getHashMD5(bytes); }
java
public static String getHashMD5(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes, 0, bytes.length); byte[] digest = md.digest(); return toHex(digest); } catch (NoSuchAlgorithmException t) { throw new Ru...
java
public static String generateSecretKey() { return hmacDigest(UUID.randomUUID().toString(), UUID.randomUUID().toString(), HMAC_SHA256); }
java
public static MongoClient create(final PippoSettings settings) { String host = settings.getString(HOST, "mongodb://localhost:27017"); return create(host); }
java
public static MongoClient create(String hosts) { MongoClientURI connectionString = new MongoClientURI(hosts); return new MongoClient(connectionString); }
java
protected void onPreDispatch(Request request, Response response) { application.getRoutePreDispatchListeners().onPreDispatch(request, response); }
java
protected void onRouteDispatch(Request request, Response response) { final String requestPath = request.getPath(); final String requestMethod = request.getMethod(); if (shouldIgnorePath(requestPath)) { // NOT FOUND (404) RouteContext routeContext = routeContextFactory.cr...
java
protected void onPostDispatch(Request request, Response response) { application.getRoutePostDispatchListeners().onPostDispatch(request, response); }
java
private void processFlash(RouteContext routeContext) { Flash flash = null; if (routeContext.hasSession()) { // get flash from session flash = routeContext.removeSession("flash"); // put an empty flash (outgoing flash) in session; defense against session.get("flash") ...
java
protected Map<String, Object> prepareTemplateBindings(int statusCode, RouteContext routeContext) { Map<String, Object> locals = new LinkedHashMap<>(); locals.put("applicationName", application.getApplicationName()); locals.put("applicationVersion", application.getApplicationVersion()); l...
java
protected Error prepareError(int statusCode, RouteContext routeContext) { String messageKey = "pippo.statusCode" + statusCode; Error error = new Error(); error.setStatusCode(statusCode); error.setStatusMessage(application.getMessages().get(messageKey, routeContext)); error.setRe...
java
public String getParameterName() { if (parameterName == null) { Parameter parameter = getParameter(); if (parameter.isNamePresent()) { parameterName = parameter.getName(); } } return parameterName; }
java
private Map<String, Properties> loadRegisteredMessageResources() { Map<String, Properties> internalMessages = loadRegisteredMessageResources("pippo/pippo-messages%s.properties"); Map<String, Properties> applicationMessages = loadRegisteredMessageResources("conf/messages%s.properties"); Map<Strin...
java
private Map<String, Properties> loadRegisteredMessageResources(String name) { Map<String, Properties> messageResources = new TreeMap<>(); // Load default messages Properties defaultMessages = loadMessages(String.format(name, "")); if (defaultMessages == null) { log.error("Co...
java
private Properties loadMessages(String fileOrUrl) { URL url = ClasspathUtils.locateOnClasspath(fileOrUrl); if (url != null) { try (InputStreamReader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) { Properties messages = new Properties(); ...
java
public String getSubmittedFileName() { // TODO this method also introduced in servlet 3.1 specification (delegate to part when I adopt servlet 3.1) if (submittedFileName == null) { String header = part.getHeader(HttpConstants.Header.CONTENT_DISPOSITION); if (header == null) { ...
java
public void write(File file) throws IOException { try (InputStream inputStream = getInputStream()) { IoUtils.copy(inputStream, file); } }
java
protected Cache<String, SessionData> create(String name, long idleTime) { return Caching .getCachingProvider() .getCacheManager() .createCache( name, new MutableConfiguration<String, SessionData>() ...
java
public static String getPrettyPath(List<Puzzle> path, int size) { // Print each row of all states StringBuffer output = new StringBuffer(); for (int y = 0; y < size; y++) { String row = ""; for (Puzzle state : path) { int[][] board = state.getMatrixBoard()...
java
public static Maze2D read(File file) throws IOException { ArrayList<String> array = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { array.add(line); } br.close(); ...
java
public void updateLocation(Point p, Symbol symbol) { int row = p.y; int column = p.x; this.maze[row][column] = symbol.value(); }
java
public void updateRectangle(Point a, Point b, Symbol symbol) { int xfrom = (a.x < b.x) ? a.x : b.x; int xto = (a.x > b.x) ? a.x : b.x; int yfrom = (a.y < b.y) ? a.y : b.y; int yto = (a.y > b.y) ? a.y : b.y; for (int x = xfrom; x <= xto; x++) { for (int y = yfrom; y <=...
java
public void putObstacleRectangle(Point a, Point b) { updateRectangle(a, b, Symbol.OCCUPIED); }
java
public void removeObstacleRectangle(Point a, Point b) { updateRectangle(a, b, Symbol.EMPTY); }
java
public String getReplacedMazeString(List<Map<Point, Character>> replacements) { String[] stringMaze = toStringArray(); for (Map<Point, Character> replacement : replacements) { for (Point p : replacement.keySet()) { int row = p.y; int column = p.x; ...
java
public String getStringMazeFilled(Collection<Point> points, char symbol) { Map<Point, Character> replacements = new HashMap<Point, Character>(); for (Point p : points) { replacements.put(p, symbol); } return getReplacedMazeString(Collections.singletonList(replacements)); ...
java
public boolean pointInBounds(Point loc) { return loc.x >= 0 && loc.x < this.columns && loc.y >= 0 && loc.y < this.rows; }
java
public Collection<Point> validLocationsFrom(Point loc) { Collection<Point> validMoves = new HashSet<Point>(); // Check for all valid movements for (int row = -1; row <= 1; row++) { for (int column = -1; column <= 1; column++) { try { if (isFree(new...
java
public Set<Point> diff(Maze2D to) { char[][] maze1 = this.getMazeCharArray(); char[][] maze2 = to.getMazeCharArray(); Set<Point> differentLocations = new HashSet<Point>(); for (int row = 0; row < this.rows; row++) { for (int column = 0; column < this.columns; column++) { ...
java
public static Maze2D empty(int size) { char[][] maze = new char[size][size]; for (int i = 0; i < size; i++) { Arrays.fill(maze[i], Symbol.EMPTY.value()); } maze[0][0] = Symbol.START.value(); maze[size][size] = Symbol.GOAL.value(); return new Maze2D(maze); ...
java
public Entry<T> enqueue(T value, double priority) { checkPriority(priority); /* Create the entry object, which is a circularly-linked list of length * one. */ Entry<T> result = new Entry<T>(value, priority); /* Merge this singleton list with the tree list. */ ...
java
public static <T> FibonacciHeap<T> merge(FibonacciHeap<T> one, FibonacciHeap<T> two) { /* Create a new FibonacciHeap to hold the result. */ FibonacciHeap<T> result = new FibonacciHeap<T>(); /* Merge the two Fibonacci heap root lists together. This helper function * also computes the m...
java
public Entry<T> dequeueMin() { /* Check for whether we're empty. */ if (isEmpty()) throw new NoSuchElementException("Heap is empty."); /* Otherwise, we're about to lose an element, so decrement the number of * entries in this heap. */ --mSize; /* G...
java
private void decreaseKeyUnchecked(Entry<T> entry, double priority) { /* First, change the node's priority. */ entry.mPriority = priority; /* If the node no longer has a higher priority than its parent, cut it. * Note that this also means that if we try to run a delete operation ...
java
private void cutNode(Entry<T> entry) { /* Begin by clearing the node's mark, since we just cut it. */ entry.mIsMarked = false; /* Base case: If the node has no parent, we're done. */ if (entry.mParent == null) return; /* Rewire the node's siblings around it, if it has any sibli...
java
public static ScalarOperation<Double> doubleMultiplicationOp() { return new ScalarOperation<Double>(new ScalarFunction<Double>() { @Override public Double scale(Double a, double b) { return a * b; } }, 1d); }
java
public Iterable<N> expandTransitionsChanged(N begin, Iterable<Transition<A, S>> transitions){ Collection<N> nodes = new ArrayList<N>(); for (Transition<A, S> transition : transitions) { S state = transition.getState(); //if v != start if (!state.equals(begin.state()))...
java
private Map<Transition<A, S>, N> predecessorsMap(S current){ //Map<Transition, Node> containing predecessors relations Map<Transition<A, S>, N> mapPredecessors = new HashMap<Transition<A, S>, N>(); //Fill with non-null pairs of <Transition, Node> for (Transition<A, S> predecessor : prede...
java
public N makeNode(N from, Transition<A, S> transition){ return nodeFactory.makeNode(from, transition); }
java
public void updateKey(N node){ node.getKey().update(node.getG(), node.getV(), heuristicFunction.estimate(node.state()), epsilon, add, scale); }
java
private static Graph buildGraph() { Graph g = new TinkerGraph(); //add vertices Vertex v1 = g.addVertex("v1"); Vertex v2 = g.addVertex("v2"); Vertex v3 = g.addVertex("v3"); Vertex v4 = g.addVertex("v4"); Vertex v5 = g.addVertex("v5"); Vertex v6 = g.addVert...
java
public static <A,S> Transition<A,S> create(S fromState, A action, S toState){ return new Transition<A, S>(fromState, action, toState); }
java
public static <S> Transition<Void,S> create(S fromState, S toState){ return new Transition<Void, S>(fromState, null, toState); }
java
public static void printSearch(Iterator<? extends Node<?,Point,?>> it, Maze2D maze) throws InterruptedException { Collection<Point> explored = new HashSet<Point>(); while (it.hasNext()) { Node<?,Point,?> currentNode = it.next(); if (currentNode.previousNode() != null) { ...
java
public static String getMazeStringSolution(Maze2D maze, Collection<Point> explored, Collection<Point> path) { List<Map<Point, Character>> replacements = new ArrayList<Map<Point, Character>>(); Map<Point, Character> replacement = new HashMap<Point, Character>(); for (Point p : explored) { ...
java
public static void main(String[] args){ /* SearchProblem is the structure used by Hipster to store all the information about the search query, like: start, goals, transition function, cost function, etc. Once created it is used to instantiate the search iterators...
java
@Override public Iterable<GraphEdge<V, E>> edges() { return F.map(vedges(), new Function<Map.Entry<V, GraphEdge<V, E>>, GraphEdge<V, E>>() { @Override public GraphEdge<V, E> apply(Map.Entry<V, GraphEdge<V, E>> entry) { return entry.getValue(); } })...
java
public SearchResult search(final S goalState){ return search(new Predicate<N>() { @Override public boolean apply(N n) { if (goalState != null) { return n.state().equals(goalState); } return false; } }...
java
public SearchResult search(Predicate<N> condition){ int iteration = 0; Iterator<N> it = iterator(); long begin = System.currentTimeMillis(); N currentNode = null; while(it.hasNext()){ iteration++; currentNode = it.next(); if (condition.apply(cu...
java
public static <S, N extends Node<?,S,N>> List<S> recoverStatePath(N node){ List<S> states = new LinkedList<S>(); for(N n : node.path()){ states.add(n.state()); } return states; }
java
public static <A, S, C extends Comparable<C>, N extends CostNode<A, S, C, N>> BellmanFord<A, S, C, N> createBellmanFord( SearchProblem<A, S, N> components) { return new BellmanFord<A, S, C, N>(components.getInitialNode(), components.getExpander()); }
java
public static <A, S, N extends Node<A, S, N>> BreadthFirstSearch<A, S, N> createBreadthFirstSearch( SearchProblem<A, S, N> components) { return new BreadthFirstSearch<A, S, N>(components.getInitialNode(), components.getExpander()); }
java
public static <A, S, N extends Node<A, S, N>> DepthFirstSearch<A, S, N> createDepthFirstSearch( SearchProblem<A, S, N> components) { return new DepthFirstSearch<A, S, N>(components.getInitialNode(), components.getExpander()); }
java
public static <A, S, N extends Node<A, S, N>> DepthLimitedSearch<A, S, N> createDepthLimitedSearch( SearchProblem<A, S, N> components, int depth) { return new DepthLimitedSearch<A, S, N>(components.getInitialNode(), components.getFinalNode(), components.getExpander(), depth); }
java
public static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> HillClimbing<A, S, C, N> createHillClimbing( SearchProblem<A, S, N> components, boolean enforced) { return new HillClimbing<A, S, C, N>(components.getInitialNode(), components.getExpander(), enforced); }
java
public static <A, S, N extends HeuristicNode<A, S, Double, N>> AnnealingSearch<A, S, N> createAnnealingSearch( SearchProblem<A, S, N> components, Double alpha, Double minTemp, AcceptanceProbability acceptanceProbability, SuccessorFinder<A, S, N> successorFinder) { return new AnnealingSearch<A, S, N>(componen...
java
public static <A, S, C extends Comparable<C>, N extends HeuristicNode<A, S, C, N>> MultiobjectiveLS<A, S, C, N> createMultiobjectiveLS( SearchProblem<A, S, N> components) { return new MultiobjectiveLS<A, S, C, N>(components.getInitialNode(), components.getExpander()); }
java
public static HeuristicFunction<City, Double> heuristicFunction(){ return new HeuristicFunction<City, Double>() { @Override public Double estimate(City state) { return heuristics().get(state); } }; }
java
public static <S> UnweightedNode<Void,S> newNodeWithoutAction(UnweightedNode<Void,S> previousNode, S state){ return new UnweightedNode<Void, S>(previousNode, state, null); }
java
public static <T extends GraphNode<T>> T getFirstChild(T node) { return hasChildren(node) ? node.getChildren().get(0) : null; }
java
public static <T extends GraphNode<T>> T getLastChild(T node) { return hasChildren(node) ? node.getChildren().get(node.getChildren().size() - 1) : null; }
java
public static <T extends GraphNode<T>> int countAllDistinct(T node) { if (node == null) return 0; return collectAllNodes(node, new HashSet<T>()).size(); }
java
public static <T extends GraphNode<T>, C extends Collection<T>> C collectAllNodes(T node, C collection) { // we don't recurse if the collecion already contains the node // this costs a bit of performance but prevents infinite recursion in the case of graph cycles checkArgNotNull(collection, "col...
java
public static <T extends GraphNode<T>> String printTree(T node, Formatter<T> formatter) { checkArgNotNull(formatter, "formatter"); return printTree(node, formatter, Predicates.<T>alwaysTrue(), Predicates.<T>alwaysTrue()); }
java
private static <T extends GraphNode<T>> StringBuilder printTree(T node, Formatter<T> formatter, String indent, StringBuilder sb, Predicate<T> nodeFilter, ...
java
public static boolean isBoxedType(Class<?> primitive, Class<?> boxed) { return (primitive.equals(boolean.class) && boxed.equals(Boolean.class)) || (primitive.equals(byte.class) && boxed.equals(Byte.class)) || (primitive.equals(char.class) && boxed.equals(Character.class)) || ...
java
public static Constructor findConstructor(Class<?> type, Object[] args) { outer: for (Constructor constructor : type.getConstructors()) { Class<?>[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length != args.length) continue; for (int i = 0; i < args....
java
public static String humanize(long value) { if (value < 0) { return '-' + humanize(-value); } else if (value > 1000000000000000000L) { return Double.toString( (value + 500000000000000L) / 1000000000000000L * 1000000000000000L / 1000000000000000000.0) + 'E'; ...
java
@Override protected Rule fromStringLiteral(String string) { return string.endsWith(" ") ? Sequence(String(string.substring(0, string.length() - 1)), WhiteSpace()) : String(string); }
java
static Matcher findProperLabelMatcher(MatcherPath path, int errorIndex) { try { return findProperLabelMatcher0(path, errorIndex); } catch(RuntimeException e) { if (e == UnderneathTestNot) return null; else throw e; } }
java
public static String printParseErrors(List<ParseError> errors) { checkArgNotNull(errors, "errors"); StringBuilder sb = new StringBuilder(); for (ParseError error : errors) { if (sb.length() > 0) sb.append("---\n"); sb.append(printParseError(error)); } retu...
java
public static String printParseError(ParseError error, Formatter<InvalidInputError> formatter) { checkArgNotNull(error, "error"); checkArgNotNull(formatter, "formatter"); String message = error.getErrorMessage() != null ? error.getErrorMessage() : error instanceof InvalidInputErr...
java
public static String repeat(char c, int n) { char[] array = new char[n]; Arrays.fill(array, c); return String.valueOf(array); }
java
public static boolean startsWith(String string, String prefix) { return string != null && (prefix == null || string.startsWith(prefix)); }
java
private static int getLine0(int[] newlines, int index) { int j = Arrays.binarySearch(newlines, index); return j >= 0 ? j : -(j + 1); }
java
public boolean enterFrame() { if (level++ > 0) { if (stack == null) stack = new LinkedList<T>(); stack.add(get()); } return set(initialValueFactory.create()); }
java
public static Matcher unwrap(Matcher matcher) { if (matcher instanceof MemoMismatchesMatcher) { MemoMismatchesMatcher memoMismatchesMatcher = (MemoMismatchesMatcher) matcher; return unwrap(memoMismatchesMatcher.inner); } return matcher; }
java
public String[] getLabels(Matcher matcher) { if ((matcher instanceof AnyOfMatcher) && ((AnyOfMatcher)matcher).characters.toString().equals(matcher.getLabel())) { AnyOfMatcher cMatcher = (AnyOfMatcher) matcher; if (!cMatcher.characters.isSubtractive()) { String[] labels = ...
java
public static Matcher unwrap(Matcher matcher) { if (matcher instanceof VarFramingMatcher) { VarFramingMatcher varFramingMatcher = (VarFramingMatcher) matcher; return unwrap(varFramingMatcher.inner); } return matcher; }
java
public static Class<?> findLoadedClass(String className, ClassLoader classLoader) { checkArgNotNull(className, "className"); checkArgNotNull(classLoader, "classLoader"); try { Class<?> classLoaderBaseClass = Class.forName("java.lang.ClassLoader"); Method findLoadedClassMe...
java
public static boolean isAssignableTo(String classInternalName, Class<?> type) { checkArgNotNull(classInternalName, "classInternalName"); checkArgNotNull(type, "type"); return type.isAssignableFrom(getClassForInternalName(classInternalName)); }
java
public static <T extends TreeNode<T>> T getRoot(T node) { if (node == null) return null; if (node.getParent() != null) return getRoot(node.getParent()); return node; }
java
public static <T extends MutableTreeNode<T>> void addChild(T parent, T child) { checkArgNotNull(parent, "parent"); parent.addChild(parent.getChildren().size(), child); }
java
public static <T extends MutableTreeNode<T>> void removeChild(T parent, T child) { checkArgNotNull(parent, "parent"); int index = parent.getChildren().indexOf(child); checkElementIndex(index, parent.getChildren().size()); parent.removeChild(index); }
java
Rule ArrayCreatorRest() { return Sequence( LBRK, FirstOf( Sequence(RBRK, ZeroOrMore(Dim()), ArrayInitializer()), Sequence(Expression(), RBRK, ZeroOrMore(DimExpr()), ZeroOrMore(Dim())) ) ); }
java
public T getAndSet(T value) { T t = this.value; this.value = value; return t; }
java
private static void verify(char[][] strings) { int length = strings.length; for (int i = 0; i < length; i++) { char[] a = strings[i]; inner: for (int j = i + 1; j < length; j++) { char[] b = strings[j]; if (b.length < a.length) continue...
java
public static <V> Node<V> findNode(Node<V> parent, Predicate<Node<V>> predicate) { checkArgNotNull(predicate, "predicate"); if (parent != null) { if (predicate.apply(parent)) return parent; if (hasChildren(parent)) { Node<V> found = findNode(parent.getChildren(), ...
java