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
54a1f8ddd69a76e5f29087d58b4769a69fdd8e81
1,614
package designPatterns.builder; import java.util.ArrayList; import java.util.Collections; public class HtmlElement { public String name, text; // this is a recursive structure public ArrayList<HtmlElement> elements = new ArrayList<>(); // utility helpers private final int indentSize = 2; private final String newLine = System.lineSeparator(); public HtmlElement() { } public HtmlElement(String name, String text) { this.name = name; this.text = text; } private String toStringImpl(int indent) { StringBuilder sb = new StringBuilder(); // we want to get the indentation correct thus the use of Collections String i = String.join("", Collections.nCopies(indent * indent, " ")); // this is were tags are appended sb.append(String.format("%s<%s>%s", i, name, newLine)); // if there is text it's appended if (text != null && !text.isEmpty()) { // with a new line sb.append(String.join("", Collections.nCopies(indentSize*(indent+1), " "))) .append(text) .append(newLine); } // check recursively for the elements inside the tags // and their children and they get printed as well for (HtmlElement e: elements) { sb.append(e.toStringImpl(indent + 1)); } // the closing tags are appended sb.append(String.format("%s</%s>%s", i, name, newLine)); return sb.toString(); } @Override public String toString() { return toStringImpl(0); } }
31.038462
87
0.599133
07a4bd640e4d5ef13e0d28b0bcd0c1a7b7b9650d
2,006
package ub.edu.view; import ub.edu.controller.IController; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * Formulari amb el detall d'un post. Aquesta classe hereta de JDialog */ public class FerPost extends JDialog { // Atributos private JTextArea AreaMissatge; private JButton sendButton; private JButton cancelButton; private JPanel jpanel; /** * Constructor de la classe FormEpisodi que crida initComponents() * @param owner Owner * @param controller ControladorGUI */ protected FerPost(Frame owner, IController controller) { setContentPane(jpanel); setModal(true); getRootPane().setDefaultButton(cancelButton); initComponents(); setResizable(true); setTitle("FER POST"); this.setLocationRelativeTo(null); } /** * Mètodo que inicializa todos los componentes de la GUI de FormPost */ private void initComponents() { setSize(250,300); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); sendButton.addActionListener(e -> onPost()); cancelButton.addActionListener(e -> onCancel()); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onCancel(); } }); // call onCancel() on ESCAPE jpanel.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); AreaMissatge.requestFocusInWindow(); } /** * Método que se llama cuando cerramos una ventana usando la "x" */ private void onCancel() { dispose(); } /** * Metodo para mostrar un post */ private void onPost() { String estat = AreaMissatge.getText(); JOptionPane.showMessageDialog(jpanel, estat); dispose(); } }
28.253521
149
0.647059
062536aa1626aec961380642c1d53b9638fc25b8
395
//------------------------------------------------------------------------------ // Copyright Siemens Switzerland Ltd., 2014 //------------------------------------------------------------------------------ package patterns.observer.headfirst.weatherstation; /** * @author z003d3hv * */ public interface Observer { public void update(float temperature, float humidity, float pressure); }
26.333333
80
0.443038
3030346acb879f089f5925d25b5d00a8569783b8
7,579
/* * Copyright 2021 4Paradigm * * 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._4paradigm.openmldb.test_common.restful.util; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import lombok.extern.slf4j.Slf4j; import org.apache.http.message.BasicNameValuePair; import sun.misc.BASE64Encoder; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @Slf4j public class Tool { public static final Pattern PATTERN = Pattern.compile("<(.*?)>"); public static void genStr(String str, Map<String, List<String>> map, List<String> list){ Matcher matcher = PATTERN.matcher(str); if (matcher.find()){ String replace = matcher.group(); String key = matcher.group(1); List<String> params = map.get(key); for(String param:params){ String newStr = str.replace(replace,param); genStr(newStr,map,list); } }else{ list.add(str); } } /** * 验证一个字符串是不是json格式 * @param test * @return 如果是返回true,否则返回false */ public final static boolean isJSONValid(String test) { try { JsonElement jsonElement = new JsonParser().parse(test); return jsonElement.isJsonObject() || jsonElement.isJsonArray(); } catch (Exception ex) { return false; } } public static String base64(String md5Str,boolean isUpper){ log.info(md5Str); byte[] b = null; String s = null; try { if(isUpper) { b = md5Str.toUpperCase().getBytes(); }else { b= md5Str.toLowerCase().getBytes(); } } catch (Exception e) { e.printStackTrace(); } if (b != null) { s = new BASE64Encoder().encode(b); } return s; } public static String md5(String s){ char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; try { byte[] btInput = s.getBytes(); // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(btInput); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str).toLowerCase(); } catch (Exception e) { log.error(e.getMessage()); return null; } } public static Properties getProperties(String path,Class c){ Properties ps = new Properties(); try { ps.load(c.getClassLoader().getResourceAsStream(path)); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); } return ps; } public static List<BasicNameValuePair> getBasicNameValuePair(Map<String,Object>dataMap){ List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>(); for (String key:dataMap.keySet()){ BasicNameValuePair nv = new BasicNameValuePair(key,String.valueOf(dataMap.get(key))); nvps.add(nv); } return nvps; } public static String strTime(String format,long time){ SimpleDateFormat strFormat = new SimpleDateFormat(format); if(time == 0){ time = new Date().getTime(); } return strFormat.format(time); } public static <T>String ArrToString(T[] arr){ String str = ""; for (int i=0;i<arr.length;i++) { str += arr[i]+","; } return str; } public static String getUri(String urlString) throws MalformedURLException { if(urlString.endsWith("/")){ urlString = urlString.substring(0,urlString.length()-1); } URL url = new URL(urlString); return url.getPath(); } /* public static String getShortClassName(String longName){ String[] clsname = longName.split("\\."); return clsname[clsname.length-1]; } */ /** * 根据 参数C,返回对应类型的 in对象, * * @param c * @param in * @return */ public static Object converter(Class c, String in) { if(in.equals("null")){ return null; } if (c == String.class) { return in; } if (c == int.class) { int index = in.lastIndexOf('.'); if (index != -1) return Integer.parseInt(in.substring(0, index)); return Integer.parseInt(in); } if (c == long.class) { return Long.parseLong(in); } if (c == double.class) { return Double.parseDouble(in); } if (c == float.class) { return Float.parseFloat(in); } if (c == Boolean.class) { return Boolean.parseBoolean(in); } if (c == boolean.class) { return Boolean.parseBoolean(in); } if (c == int[].class) { if(in.equals("null")) { return null; } else { return StringArrayToIntArray(in.split(",", -1)); } } if (c == String[].class) { if(in.equals("null")) { return null; } else { return in.split(",", -1); } } return null; } public static int [] StringArrayToIntArray(String[] src){ int len = src.length; System.out.print(src); int [] result = new int[len]; for (int i=0;i<len;i++){ result[i] = Integer.valueOf(src[i]); } System.out.print(result); return result; } public static String uuid(){ String uuid = UUID.randomUUID().toString().replaceAll("-", ""); return uuid; } private static final String PROJECT_NAME="InterfaceAutoTestFinance/"; public static String getModelName(Class c){ String classPath = c.getResource("").getPath(); String[] ss = classPath.split(PROJECT_NAME); String modelName = ss[1].substring(0,ss[1].indexOf("/")); return modelName; } public static void setModelName(Class c){ String modelName = getModelName(c); System.setProperty("model.name",modelName); } public static void main(String [] args) throws MalformedURLException { // System.out.println(isJSONValid("{\"x\":\"b\"}")); System.out.println(uuid()); } }
28.81749
97
0.546906
84f10ee1bc3aae30ccf4df25e97308bae2591121
2,657
/* * * Copyright (c) )2022 Marco Marini, marco.marini@mmarini.org * * 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. * * END OF TERMS AND CONDITIONS * */ package org.mmarini.wheelly.model; import java.awt.geom.Point2D; import static java.lang.Math.*; import static org.mmarini.wheelly.model.Utils.direction; import static org.mmarini.wheelly.model.Utils.normalizeDegAngle; /** * */ public interface RobotAsset { /** * Returns the direction of robot DEG */ int getRobotDeg(); /** * Returns the direction of location from the robot DEG * * @param location the location */ default int getRobotDeg(Point2D location) { return (int) round(toDegrees(direction(getRobotLocation(), location))); } /** * Returns the distance of a location from the robot * * @param location the location */ default double getRobotDistance(Point2D location) { return getRobotLocation().distance(location); } /** * Returns the robot location */ Point2D getRobotLocation(); /** * Returns the direction of robot RAD */ default double getRobotRad() { return toRadians(getRobotDeg()); } /** * Returns the direction of a location relative to head of robot DEG * * @param location the location */ default int getRobotRelativeDeg(Point2D location) { return normalizeDegAngle(getRobotDeg(location) - getRobotDeg()); } default boolean isHeadingTo(Point2D location, int epsilon) { return abs(getRobotRelativeDeg(location)) <= epsilon; } }
29.197802
79
0.694016
6bc5f1043c911d41d3ede882a43117d8749eb267
4,265
/* * Copyright 2012 The Netty Project * * The Netty Project 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 com.ai.cloud.io.netty.handler.codec.http; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.List; /** * Creates an URL-encoded URI from a path string and key-value parameter pairs. * This encoder is for one time use only. Create a new instance for each URI. * * <pre> * {@link QueryStringEncoder} encoder = new {@link QueryStringEncoder}("/hello"); * encoder.addParam("recipient", "world"); * assert encoder.toString().equals("/hello?recipient=world"); * </pre> * @see QueryStringDecoder */ public class QueryStringEncoder { private final Charset charset; private final String uri; private final List<Param> params = new ArrayList<Param>(); /** * Creates a new encoder that encodes a URI that starts with the specified * path string. The encoder will encode the URI in UTF-8. */ public QueryStringEncoder(String uri) { this(uri, HttpConstants.DEFAULT_CHARSET); } /** * Creates a new encoder that encodes a URI that starts with the specified * path string in the specified charset. */ public QueryStringEncoder(String uri, Charset charset) { if (uri == null) { throw new NullPointerException("getUri"); } if (charset == null) { throw new NullPointerException("charset"); } this.uri = uri; this.charset = charset; } /** * Adds a parameter with the specified name and value to this encoder. */ public void addParam(String name, String value) { if (name == null) { throw new NullPointerException("name"); } params.add(new Param(name, value)); } /** * Returns the URL-encoded URI object which was created from the path string * specified in the constructor and the parameters added by * {@link #addParam(String, String)} getMethod. */ public URI toUri() throws URISyntaxException { return new URI(toString()); } /** * Returns the URL-encoded URI which was created from the path string * specified in the constructor and the parameters added by * {@link #addParam(String, String)} getMethod. */ @Override public String toString() { if (params.isEmpty()) { return uri; } else { StringBuilder sb = new StringBuilder(uri).append('?'); for (int i = 0; i < params.size(); i++) { Param param = params.get(i); sb.append(encodeComponent(param.name, charset)); if (param.value != null) { sb.append('='); sb.append(encodeComponent(param.value, charset)); } if (i != params.size() - 1) { sb.append('&'); } } return sb.toString(); } } private static String encodeComponent(String s, Charset charset) { // TODO: Optimize me. try { return URLEncoder.encode(s, charset.name()).replace("+", "%20"); } catch (UnsupportedEncodingException ignored) { throw new UnsupportedCharsetException(charset.name()); } } private static final class Param { final String name; final String value; Param(String name, String value) { this.value = value; this.name = name; } } }
32.067669
81
0.621336
2ab065952379c05c8e32c2ef3826513bea1cb030
3,107
package io.github.yezhihao.protostar.schema; import io.github.yezhihao.protostar.PrepareLoadStrategy; import io.github.yezhihao.protostar.Schema; import io.github.yezhihao.protostar.field.BasicField; import io.github.yezhihao.protostar.util.IntTool; import io.github.yezhihao.protostar.util.KeyValuePair; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Map.Entry; public abstract class MapSchema<K, V> extends BasicField<Entry<K, V>> { public final Logger log = LoggerFactory.getLogger(this.getClass().getSimpleName()); public final Schema<K> keySchema; public final int lengthUnit; public final IntTool intTool; public final Map<K, Schema> valueSchema; public MapSchema(Schema<K> keySchema, int lengthUnit) { this.keySchema = keySchema; this.lengthUnit = lengthUnit; this.intTool = IntTool.getInstance(lengthUnit); PrepareLoadStrategy<K> loadStrategy = new PrepareLoadStrategy<>(); addSchemas(loadStrategy); this.valueSchema = loadStrategy.build(); } protected abstract void addSchemas(PrepareLoadStrategy<K> schemaRegistry); @Override public KeyValuePair<K, V> readFrom(ByteBuf input) { K key = keySchema.readFrom(input); KeyValuePair<K, V> result = new KeyValuePair<>(key); int length = intTool.read(input); if (length > 0) { int writerIndex = input.writerIndex(); input.writerIndex(input.readerIndex() + length); Schema<V> schema = valueSchema.get(key); if (schema != null) { V value = schema.readFrom(input, length); result.setValue(value); } else { byte[] bytes = new byte[length]; input.readBytes(bytes); result.setValue((V) bytes); } input.writerIndex(writerIndex); } else if (length < 0) { Schema<V> schema = valueSchema.get(key); if (schema != null) { V value = schema.readFrom(input); result.setValue(value); } else { byte[] bytes = new byte[input.readableBytes()]; input.readBytes(bytes); result.setValue((V) bytes); } } return result; } @Override public void writeTo(ByteBuf output, Entry<K, V> entry) { if (entry == null) return; K key = entry.getKey(); keySchema.writeTo(output, key); Schema schema = valueSchema.get(key); if (schema != null) { int begin = output.writerIndex(); intTool.write(output, 0); Object value = entry.getValue(); if (value != null) { schema.writeTo(output, value); int length = output.writerIndex() - begin - lengthUnit; intTool.set(output, begin, length); } } else { log.warn("未注册的信息:ID[{}], Value[{}]", key, entry.getValue()); } } }
34.142857
87
0.594786
9700f6d2429a64f7649c4148913ccd9d51b215a8
15,198
package com.ztory.lib.reflective; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /** * Reflective functionality leverages Java-Reflection functionality to provide easy to use tools * for data consumption and manipulation. * Created by jonruna on 16/04/16. */ public class Reflective { private static final List<Class<?>> sWrapperClasses = new ArrayList<>(9); private static final List<Class<?>> sPrimitiveClasses = new ArrayList<>(9); private static final Map<Class<?>, Object> sDefaultValues = new HashMap<>(8); static { sWrapperClasses.add(Integer.class); sWrapperClasses.add(Boolean.class); sWrapperClasses.add(Long.class); sWrapperClasses.add(Float.class); sWrapperClasses.add(Double.class); sWrapperClasses.add(Byte.class); sWrapperClasses.add(Character.class); sWrapperClasses.add(Short.class); sWrapperClasses.add(Void.class); sPrimitiveClasses.add(int.class); sPrimitiveClasses.add(boolean.class); sPrimitiveClasses.add(long.class); sPrimitiveClasses.add(float.class); sPrimitiveClasses.add(double.class); sPrimitiveClasses.add(byte.class); sPrimitiveClasses.add(char.class); sPrimitiveClasses.add(short.class); sPrimitiveClasses.add(void.class); sDefaultValues.put(int.class, 0); sDefaultValues.put(boolean.class, false); sDefaultValues.put(long.class, 0L); sDefaultValues.put(float.class, 0.0f); sDefaultValues.put(double.class, 0.0d); sDefaultValues.put(byte.class, (byte) 0); sDefaultValues.put(char.class, '\u0000'); sDefaultValues.put(short.class, (short) 0); } public static final int INTEGER_INDEX = 0, BOOLEAN_INDEX = 1, LONG_INDEX = 2, FLOAT_INDEX = 3, DOUBLE_INDEX = 4, BYTE_INDEX = 5, CHARACTER_INDEX = 6, SHORT_INDEX = 7, VOID_INDEX = 8; public static final ReflectiveKeyParser LOWERCASE_UNDERSCORE = new ReflectiveKeyParser() { @Override public String getParsedKey(int startOffset, String key) { return Reflective.getKeyLowerCaseWithUnderscore(startOffset, key); } }; public static final ReflectiveKeyParser CAMELCASE = new ReflectiveKeyParser() { @Override public String getParsedKey(int startOffset, String key) { String returnKey = key.substring(startOffset); String lowerCaseFirstChar = String.valueOf(returnKey.charAt(0)) .toLowerCase(Locale.ENGLISH); returnKey = lowerCaseFirstChar + returnKey.substring(1); return returnKey; } }; private static final char UNDERSCORE = '_'; /** * Test if supplied primitiveIndex is of a type that can be represented as a Number. * @param primitiveIndex int value was returned from calling getPrimitiveWrapperIndex() or * getPrimitiveIndex() * @return true if the index corresponds to a data type that can be represented as a Number, * otherwise returns false. */ public static boolean isPrimitiveIndexNumber(int primitiveIndex) { switch (primitiveIndex) { case INTEGER_INDEX: return true; case LONG_INDEX: return true; case FLOAT_INDEX: return true; case DOUBLE_INDEX: return true; case BYTE_INDEX: return true; case SHORT_INDEX: return true; } return false; } /** * Returns the default value for the supplied primitive Class parameter, will return null for * all other Classes. * @param clazz Class to get default value for * @return default value Class */ public static Object getPrimitiveDefaultValue(final Class<?> clazz) { return sDefaultValues.get(clazz); } /** * Returns -1 if supplied class is not a primitive-wrapper-class. * Will return a positive-integer that is equal to one of the following constants: * INTEGER_INDEX * BOOLEAN_INDEX * LONG_INDEX * FLOAT_INDEX * DOUBLE_INDEX * BYTE_INDEX * CHARACTER_INDEX * SHORT_INDEX * VOID_INDEX * @param clazz Class to test if it is a primitive-wrapper-class * @return -1 for no match, 0 or greater int if there is a match */ public static int getPrimitiveWrapperIndex(final Class<?> clazz) { return sWrapperClasses.indexOf(clazz); } /** * Returns -1 if supplied class is not a primitive-class. * Will return a positive-integer that is equal to one of the following constants: * INTEGER_INDEX * BOOLEAN_INDEX * LONG_INDEX * FLOAT_INDEX * DOUBLE_INDEX * BYTE_INDEX * CHARACTER_INDEX * SHORT_INDEX * VOID_INDEX * @param clazz Class to test if it is a primitive-class * @return -1 for no match, 0 or greater int if there is a match */ public static int getPrimitiveIndex(final Class<?> clazz) { return sPrimitiveClasses.indexOf(clazz); } public static <T> void checkReflectiveRequired( Class<T> clazz, List<T> objects ) throws ReflectiveRequiredException { for (T iterObject : objects) { checkReflectiveRequired(clazz, iterObject); } } private static <T> void checkReflectiveRequiredObject( Class<T> clazz, Object object ) throws ReflectiveRequiredException { checkReflectiveRequired(clazz, (T) object); } /** * NOTE THAT ANNOTATIONS ARE NOT INHERITED BY SUBCLASSES! * Easy fix is to use base-interface/class for validation and subclass for logic. * * Validates data in object with the methods from clazz that have the * ReflectiveRequired annotation. * @param clazz Class containing ReflectiveRequired annotated methods * @param object subclass of Class that will have its ReflectiveRequired methods validated * @param <T> Type of clazz and object * @throws ReflectiveRequiredException if a ReflectiveRequired method returns null or any other * exception is thrown when executing method.invoke(object) */ public static <T> void checkReflectiveRequired( Class<T> clazz, T object ) throws ReflectiveRequiredException { ReflectiveRequired aRequired; ReflectiveType aType; for (Method iterMethod : clazz.getMethods()) { if ((aRequired = iterMethod.getAnnotation(ReflectiveRequired.class)) != null) { Object returnObject = null; try { returnObject = iterMethod.invoke(object); /* "Class", clazz, "Method", iterMethod.getName(), "ReflectiveRequired", aRequired, "hasMinimumNumber", aRequired.hasMinimumNumber(), "minimumNumber", aRequired.minimumNumber(), "returnObject", returnObject */ if (returnObject == null) { throw new ReflectiveRequiredException( "ReflectiveRequired method " + iterMethod.getName() + " returned null!" ); } else if ( aRequired.hasMinimumNumber() && returnObject instanceof Number && ((Number) returnObject).doubleValue() < aRequired.minimumNumber() ) { throw new ReflectiveRequiredException( "ReflectiveRequired method " + iterMethod.getName() + " returned " + returnObject + ". Minimum value is: " + aRequired.minimumNumber() ); } else if ((aType = iterMethod.getAnnotation(ReflectiveType.class)) != null) { if (returnObject instanceof List) { checkReflectiveRequired(aType.value(), (List) returnObject); } else { checkReflectiveRequiredObject(aType.value(), returnObject); } } } catch (ReflectiveRequiredException e) { throw e; } catch (Exception e) { throw new ReflectiveRequiredException( "ReflectiveRequired method " + iterMethod.getName() + " returned: " + returnObject, e ); } } else if ((aType = iterMethod.getAnnotation(ReflectiveType.class)) != null) { // For non required return-types we still validate nested ReflectiveType instances Object returnObject = null; try { returnObject = iterMethod.invoke(object); if (returnObject != null) { if (returnObject instanceof List) { checkReflectiveRequired(aType.value(), (List) returnObject); } else { checkReflectiveRequiredObject(aType.value(), returnObject); } } } catch (ReflectiveRequiredException e) { throw e; } catch (Exception e) { throw new ReflectiveRequiredException( "ReflectiveRequired method " + iterMethod.getName() + " returned: " + returnObject, e ); } } } } /** * Creates a clazz proxy-instance with a ReflectiveInvocationHandler. * @param clazz Class of return data * @param invocationHandler InvocationHandler that will handle method invokes. * @param <T> Type of returned data * @return a <T> proxy-instance with its values backed by a Map instance */ @SuppressWarnings("unchecked") public static <T> T getReflectiveInstance( Class<T> clazz, InvocationHandler invocationHandler ) { return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[] { clazz }, invocationHandler ); } /** * Creates a clazz proxy-instance with a ReflectiveInvocationHandler. * @param clazz Class of return data * @param valueMap Map that holds the key/value pairs that the proxy-instance will interact on. * @param <T> Type of returned data * @return a <T> proxy-instance with its values backed by a Map instance */ @SuppressWarnings("unchecked") public static <T> T getReflectiveInstance( Class<T> clazz, final Map<String, Object> valueMap, ReflectiveKeyParser keyParser, Map<String, String> customKeyMap ) { return getReflectiveInstance( clazz, new ReflectiveInvocationHandler( getReflectiveNamespaceSafe(clazz), valueMap, keyParser, customKeyMap ) ); } /** * Creates a clazz proxy-instance with a ReflectiveInvocationHandler. * @param clazz Class of return data * @param valueJSON JSONObject that holds the key/value pairs that the proxy-instance will interact on. * @param <T> Type of returned data * @return a <T> proxy-instance with its values backed by a JSONObject instance */ @SuppressWarnings("unchecked") public static <T> T getReflectiveInstance( Class<T> clazz, final JSONObject valueJSON, ReflectiveKeyParser keyParser, Map<String, String> customKeyMap ) { return getReflectiveInstance( clazz, new ReflectiveInvocationHandler( getReflectiveNamespaceSafe(clazz), valueJSON, keyParser, customKeyMap ) ); } public static <T> List<T> getMultiReflectiveInstances( Class<T> clazz, JSONArray JSONArrayValues, ReflectiveKeyParser keyParser, Map<String, String> customKeyMap ) throws JSONException { List<T> returnList = new ArrayList<>(JSONArrayValues.length()); for (int i = 0; i < JSONArrayValues.length(); i++) { returnList.add( getReflectiveInstance( clazz, JSONArrayValues.getJSONObject(i), keyParser, customKeyMap ) ); } return returnList; } public static <T> String getReflectiveNamespaceSafe(Class<T> clazz) { ReflectiveNamespace reflectiveNamespace = clazz.getAnnotation(ReflectiveNamespace.class); if (reflectiveNamespace != null) { return reflectiveNamespace.value(); } else { return null; } } /** * Will convert a camel-case-key to a lowercase-with-underscore-key. * Example: CamelCaseKey -> camel_case_key * @param startOffset startOffset to be used on supplied keyName * @param keyName key-name in its raw form * @return a lowercase-with-underscore String from the keyName using the startOffset as the * number of characters to strip from keyName in the returned String. */ public static String getKeyLowerCaseWithUnderscore(int startOffset, String keyName) { int splitCount = 0; for (int i = 1 + startOffset; i < keyName.length(); i++) { if (Character.isUpperCase(keyName.charAt(i))) { splitCount++; } } if (splitCount == 0) { return keyName.substring(startOffset).toLowerCase(Locale.ENGLISH); } StringBuilder sb = new StringBuilder(keyName.length() - startOffset + splitCount); int lastOffset = startOffset; for (int i = 1 + startOffset; i < keyName.length(); i++) { if (Character.isUpperCase(keyName.charAt(i))) { sb.append(keyName, lastOffset, i); sb.append(UNDERSCORE); lastOffset = i; } } sb.append(keyName, lastOffset, keyName.length()); return sb.toString().toLowerCase(Locale.ENGLISH); } }
37.068293
107
0.577642
50a2b70b8f97afd1c427b0e6e6244303805111d7
497
import org.apache.commons.io.FileUtils; import play.Application; import play.GlobalSettings; import java.io.File; import java.io.IOException; /** * Created by anthony on 7/10/15. */ public class Global extends GlobalSettings { public void onStart(Application app) { try { FileUtils.deleteDirectory(new File("/tmp/box")); } catch (IOException e) { System.out.println("Cannot make temporary directory"); System.exit(-2); } } }
23.666667
66
0.645875
244fde0d5fd140d74e8ac516bc4761d3f46a0183
6,191
package master2019.flink.YellowTaxiTrip; import master2019.flink.YellowTaxiTrip.utils.DatasetReader; import org.apache.flink.api.java.tuple.Tuple; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.tuple.Tuple5; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.core.fs.FileSystem; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.WindowFunction; import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.util.Collector; import java.util.Iterator; import java.util.NoSuchElementException; /** * In this class the Large trips program has to be implemented. * <p> * Goal: Reports the vendors that do 5 or more trips during 3 hours that take at least 20 * minutes. * <p> * Expected output: VendorID, day, numberOfTrips, tpep_pickup_datetime, tpep_dropoff_datetime */ public class LargeTrips { private final static String FILE_NAME = "largeTrips.csv"; private final static int MIN_TRIP_TIME = 20 * 60 * 1000; // 20 minutes public static void main(final String[] args) throws NoSuchElementException { // Get params from command line final ParameterTool params = ParameterTool.fromArgs(args); final String inputPath = params.get("input"); final String outputPath = params.get("output"); if (inputPath == null || outputPath == null) { System.err.print("Could not read input and output path from arguments.\n Check you are passing them as arguments with --input and --output"); return; } final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // ID, initDate, endDate final DataStream<Tuple3<Integer, String, String>> largeTripsDataset = DatasetReader.getLargeTripsParameters(env, inputPath); final DataStream<Tuple5<Integer, String, Integer, String, String>> selected_trips_per_vendorID = largeTripsDataset // First filter by Trips > 20 minutes .filter(row -> { long initTime = DatasetReader.dateStringToDate(row.f1).getTime(); long endTime = DatasetReader.dateStringToDate(row.f2).getTime(); return (endTime - initTime) >= MIN_TRIP_TIME; }) // Assign trip start time as timestamp .assignTimestampsAndWatermarks( new AscendingTimestampExtractor<Tuple3<Integer, String, String>>() { @Override public long extractAscendingTimestamp(final Tuple3<Integer, String, String> row) { return DatasetReader.dateStringToDate(row.f1).getTime(); } } ) // Key By vendor Id .keyBy(0) // Time window of 3 hours .window(TumblingEventTimeWindows.of(Time.hours(3))) // Sum number of trips in the window of three hours, get first pickup date and last dropoff date and save the day .apply(new WindowFunction<Tuple3<Integer, String, String>, Tuple5<Integer, String, Integer, String, String>, Tuple, TimeWindow>() { @Override public void apply(final Tuple key, final TimeWindow window, final Iterable<Tuple3<Integer, String, String>> input, final Collector<Tuple5<Integer, String, Integer, String, String>> out) { final Iterator<Tuple3<Integer, String, String>> iterator = input.iterator(); String firstPickupDate = "", lastDropoffDate = ""; Integer vendorID = 0, numberOfTrips = 0; // Boolean for detecting if the element is the first item to save id and initDate boolean firstItem = true; while (iterator.hasNext()) { final Tuple3<Integer, String, String> next = iterator.next(); // If first element save vendorId and pickupdate if (firstItem) { vendorID = next.f0; firstPickupDate = next.f1; firstItem = false; } // If last element save dropoff date if (!iterator.hasNext()) { lastDropoffDate = next.f2; } numberOfTrips++; } final String day = firstPickupDate.split(" ")[0]; out.collect(new Tuple5<Integer, String, Integer, String, String>(vendorID, day, numberOfTrips, firstPickupDate, lastDropoffDate)); } }) // Filter vendorId with 5 trips or more .filter(row -> row.f2 >= 5); // Write to output file selected_trips_per_vendorID .writeAsCsv(outputPath + "/" + FILE_NAME, FileSystem.WriteMode.OVERWRITE) .setParallelism(1); // If verbose mode is activated execute is not necessary final boolean verboseMode = true; // Show first 20 results sorted by vendorIDby console if (verboseMode) { try { env.execute(); selected_trips_per_vendorID.print(); } catch (final Exception e) { e.printStackTrace(); } } else { try { env.execute(); } catch (final Exception e) { e.printStackTrace(); } } } }
47.623077
154
0.588435
07b9ba3a38c35b7cfbedfd380fc1ca705c5fa675
390
package day11; public class Seat extends Tile { private boolean isOccupied; public Seat(Position position) { super(position); } public boolean isOccupied() { return isOccupied; } public void setOccupied(boolean occupied) { this.isOccupied = occupied; } public void toggleOccupation() { isOccupied = !isOccupied; } }
16.956522
47
0.625641
3232b851ba5ad16af187b896facc3096a90808a8
6,866
package sample; import javafx.application.Platform; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.ScatterChart; import javafx.scene.chart.XYChart; import javafx.scene.control.Label; /** * Background communication /w MotorDaemon for real-time informations */ public class BackgroundCommunication extends Thread { private static BackgroundCommunication instance = null; private BackgroundCommunication() { control = Communication.getInstance(); } private Communication control; private boolean motordaemonIsOnline = false; private final NumberAxis xAxisLeft = new NumberAxis(); private final NumberAxis yAxisLeft = new NumberAxis(); private final NumberAxis xAxisRight = new NumberAxis(); private final NumberAxis yAxisRight = new NumberAxis(); private final NumberAxis xAxisTraj = new NumberAxis(); private final NumberAxis yAxisTraj = new NumberAxis(); private LineChart<Number, Number> left_graph; private LineChart<Number, Number> right_graph; private ScatterChart<Number, Number> traj_graph; private XYChart.Series<Number, Number> leftSeries = new XYChart.Series<Number, Number>(); private XYChart.Series<Number, Number> rightSeries = new XYChart.Series<Number, Number>(); private XYChart.Series<Number, Number> trajSeries = new XYChart.Series<Number, Number>(); private XYChart.Series<Number, Number> leftSeriesConsigne = new XYChart.Series<Number, Number>(); private XYChart.Series<Number, Number> rightSeriesConsigne = new XYChart.Series<Number, Number>(); private XYChart.Series<Number, Number> trajSeriesConsigne = new XYChart.Series<Number, Number>(); private boolean speedPrinting = false; private boolean curvePrinting = false; private boolean go = false; private int curveValue = 0; private long startTime = -1; public static BackgroundCommunication getInstance() { if(instance == null) instance = new BackgroundCommunication(); return instance; } @Override public void run() { while(motordaemonIsOnline) { if(curvePrinting) { Double[] p = control.getPosition(); if(p != null) { trajSeries.getData().add(new XYChart.Data<Number, Number>(p[0], p[1])); trajSeriesConsigne.getData().add(new XYChart.Data<Number, Number>(p[0], curveValue+Math.sqrt(Math.abs(curveValue - (p[0])*(p[0]))))); } else { System.err.println("Did not receive response to p"); } } if(speedPrinting) { Long[] sv = control.getSpeedValues(); if(sv != null) { if(startTime < 0) startTime = sv[0]; leftSeries.getData().add(new XYChart.Data<Number, Number>(sv[0]-startTime,sv[2])); leftSeriesConsigne.getData().add(new XYChart.Data<Number, Number>(sv[0]-startTime,sv[1])); rightSeries.getData().add(new XYChart.Data<Number, Number>(sv[0]-startTime,sv[4])); rightSeriesConsigne.getData().add(new XYChart.Data<Number, Number>(sv[0]-startTime,sv[3])); } else { System.err.println("Did not receive response to sv"); } } if(go) { if(!control.isMoving()) { go = false; if(curvePrinting) stopCurvePrinting(); else if(speedPrinting) stopSpeedPrinting(); } } try { Thread.sleep(70); } catch (InterruptedException e) { e.printStackTrace(); } } } public void setMotordaemonIsOnline(boolean state) { this.motordaemonIsOnline = state; } public void setGraphs(LineChart<Number, Number> left, LineChart<Number, Number> right, ScatterChart<Number, Number> traj) { this.left_graph = left; this.right_graph = right; this.traj_graph = traj; traj_graph.getXAxis().setAutoRanging(false); traj_graph.getYAxis().setAutoRanging(false); ((NumberAxis)traj_graph.getXAxis()).setUpperBound(1000); ((NumberAxis)traj_graph.getXAxis()).setLowerBound(-1000); ((NumberAxis)traj_graph.getYAxis()).setUpperBound(1200); ((NumberAxis)traj_graph.getYAxis()).setLowerBound(0); } private void startSpeedPrinting() { leftSeries = new XYChart.Series<Number, Number>(); rightSeries = new XYChart.Series<Number, Number>(); leftSeriesConsigne = new XYChart.Series<Number, Number>(); rightSeriesConsigne = new XYChart.Series<Number, Number>(); speedPrinting = true; } private void stopSpeedPrinting() { speedPrinting = false; startTime = -1; Platform.runLater(() -> { traj_graph.getData().clear(); left_graph.getData().clear(); left_graph.getData().add(leftSeries); left_graph.getData().add(leftSeriesConsigne); right_graph.getData().clear(); right_graph.getData().add(rightSeries); right_graph.getData().add(rightSeriesConsigne); }); } private void startCurvePrinting() { leftSeries = new XYChart.Series<Number, Number>(); rightSeries = new XYChart.Series<Number, Number>(); leftSeriesConsigne = new XYChart.Series<Number, Number>(); rightSeriesConsigne = new XYChart.Series<Number, Number>(); trajSeries = new XYChart.Series<Number, Number>(); trajSeriesConsigne = new XYChart.Series<Number, Number>(); speedPrinting = true; curvePrinting = true; } private void stopCurvePrinting() { speedPrinting = false; curvePrinting = false; startTime = -1; Platform.runLater(() -> { left_graph.getData().clear(); left_graph.getData().add(leftSeries); left_graph.getData().add(leftSeriesConsigne); right_graph.getData().clear(); right_graph.getData().add(rightSeries); right_graph.getData().add(rightSeriesConsigne); traj_graph.getData().clear(); traj_graph.getData().add(trajSeries); traj_graph.getData().add(trajSeriesConsigne); }); } public void curveSet(int curve) { this.curveValue = curve; } public void launchPrinting(boolean curve) { if(curve) startCurvePrinting(); else startSpeedPrinting(); go = true; } }
34.159204
153
0.603991
419f57670cf9663a661a56338411f52935471ab1
2,320
package medigram.medigram; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import io.searchbox.annotations.JestId; public class CareProvider extends User implements Serializable { private PatientList patientList = new PatientList(); private String userType = "CareProvider"; @JestId private String jestID; /** * Initializes a care provider * @param userID The user's unique ID * @param emailAddress The user's e-mail address * @param phoneNumber The user's phone number */ public CareProvider(String userID, String emailAddress, String phoneNumber){ this.userID = userID; this.emailAddress = emailAddress; this.phoneNumber = phoneNumber; } /** * @return the patient list the care provider is assigned to */ public PatientList getAssignedPatients() {return patientList;} /** * assign a patient to care provider * @param patient */ public void assignPatient(Patient patient){ patientList.addPatient(patient); } /** * unassign a patient from a care provider * @param patient */ public void unassignPatient(Patient patient){ patientList.deletePatient(patient); } /** * check if a patient is assigned to care provider by user id * @param userID * @return true if patient is assigned to the care provider, false otherwise */ public Boolean patientAssigned(String userID) { return patientList.patientUserIDExist(userID); } /** * check if a patient is assigned to care provider by patient object * @param patient * @return true if patient is assigned to the care provider, false otherwise */ public Boolean patientAssigned(Patient patient){ return patientList.patientUserIDExist(patient.getUserID()); } /** * check the user's role * @return type of user */ public String checkUserType(){ return this.userType; } /** * get jestID of care provider * @return jestID */ public String getJestID() { return jestID; } /** * set jestID of care provider * @param jestID */ public void setJestID(String jestID) { this.jestID = jestID; } }
24.680851
80
0.646552
d330dd949547ec05cc5df296e1a5f830bd10b394
2,062
/* * Copyright 2021 IBM Corporation * * 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.ibm.streams.operator.internal.object; import com.ibm.streams.operator.Tuple; import com.ibm.streams.operator.internal.network.LittleEndianTupleDecoder; import com.ibm.streams.operator.internal.network.TupleDecoder; import com.ibm.streams.operator.internal.runtime.Schema; import java.nio.ByteOrder; /** Tuple object implementation for the com.ibm.streams.operator package. */ public final class OpInputTuple extends ObjectInputTuple { private static final long serialVersionUID = -5623172756970857575L; public OpInputTuple(Schema schema, Object[] values) { super(schema, values); } @Override public Tuple asReadOnlyTuple() { return this; } public static TupleDecoder<Tuple> getTupleDecoder(final Schema schema) { return new ObjectTupleDecoder<Tuple>(schema) { @Override public Tuple newTuple(final Object[] values) { return new OpInputTuple(schema, values); } }; } /** * Get a object based tuple encoder that decodes the serialized form into an <code> * com.ibm.streams.operator.Tuple * </code> * * @param schema Schema of port. * @return Tuple decoder. */ public static TupleDecoder<Tuple> getTupleDecoder( final Schema schema, final ByteOrder byteOrder) { TupleDecoder<Tuple> decoder = getTupleDecoder(schema); if (byteOrder == ByteOrder.LITTLE_ENDIAN) decoder = new LittleEndianTupleDecoder<Tuple>(decoder); return decoder; } }
30.776119
85
0.732784
9ba8f9db4935ac2f67c3b832d9541bfcf285cf0d
893
package com.logzc.webzic.json; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.logzc.common.util.Assert; import com.logzc.webzic.exception.ZicException; import com.logzc.webzic.bean.AppContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A json adapter. * Created by lishuang on 2016/7/27. */ public class JsonUtil { private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); public static String toJson(Object obj) { ObjectMapper objectMapper = AppContext.getBean(ObjectMapper.class); Assert.notNull(objectMapper); try { return objectMapper.writeValueAsString(obj); } catch (JsonProcessingException e) { logger.debug(e.getMessage()); throw new ZicException(e.getMessage()); } } }
25.514286
81
0.712206
01e61ccf0822211803cff44b8537d8c6e628be6c
262
package tw.com.fcb.mimosa.workshop.vaccine.ddd.rest; import java.util.List; import lombok.Data; import tw.com.fcb.mimosa.workshop.vaccine.sharedkernel.Vaccine; @Data public class ResidentInfo { Long id; String nhiNo; String phoneNo; Long residentId; }
18.714286
63
0.770992
31c506ffe342ec9ad20e740a9af6af4e301291bc
5,235
/* * Copyright 2008-2017 by Emeric Vernat * * This file is part of Java Melody. * * 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.bull.javamelody; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; import net.bull.javamelody.internal.common.Parameters; /** * Test unitaire de la classe CustomResourceFilter. * @author Emeric Vernat */ public class TestCustomResourceFilter { private static final String MONITORING_CSS = "monitoring.css"; private static final Map<String, String> CUSTOM_RESOURCES = Collections .singletonMap(MONITORING_CSS, "customMonitoring.css"); private FilterConfig config; private CustomResourceFilter customResourceFilter; /** * Initialisation. */ @Before public void setUp() { init(false); } private void init(boolean useForward) { Utils.initialize(); config = createNiceMock(FilterConfig.class); final List<String> initParameterNames = new ArrayList<String>(); initParameterNames.add(MONITORING_CSS); if (useForward) { initParameterNames.add("useForward"); } expect(config.getInitParameterNames()) .andReturn(Collections.enumeration(initParameterNames)); for (final Map.Entry<String, String> entry : CUSTOM_RESOURCES.entrySet()) { expect(config.getInitParameter(entry.getKey())).andReturn(entry.getValue()); } if (useForward) { expect(config.getInitParameter("useForward")).andReturn("true").anyTimes(); } final ServletContext context = createNiceMock(ServletContext.class); replay(context); Parameters.initialize(context); expect(config.getServletContext()).andReturn(context).anyTimes(); customResourceFilter = new CustomResourceFilter(); } /** * Finalisation. */ @After public void tearDown() { if (customResourceFilter != null) { customResourceFilter.destroy(); } } /** * testRessource. * @throws IOException e * @throws ServletException e */ @Test public void testCustomResource() throws IOException, ServletException { doTestResource(MONITORING_CSS); } /** * testCustomResourceUsingForward. * @throws IOException e * @throws ServletException e */ @Test public void testCustomResourceUsingForward() throws IOException, ServletException { init(true); doTestResource(MONITORING_CSS, true); } /** * testRessource. * @throws IOException e * @throws ServletException e */ @Test public void testResource() throws IOException, ServletException { doTestResource("alert.png"); } /** * testRessource. * @throws IOException e * @throws ServletException e */ @Test public void testNoResource() throws IOException, ServletException { doTestResource(null); } private void doTestResource(String resource) throws IOException, ServletException { doTestResource(resource, false); } private void doTestResource(String resource, boolean useForward) throws IOException, ServletException { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); final RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class); final HttpServletResponse response = createNiceMock(HttpServletResponse.class); final FilterChain chain = createNiceMock(FilterChain.class); expect(request.getParameter("resource")).andReturn(resource); if (CUSTOM_RESOURCES.get(resource) != null) { expect(request.getRequestDispatcher(CUSTOM_RESOURCES.get(resource))) .andReturn(requestDispatcher); if (useForward) { requestDispatcher.forward(request, response); } else { requestDispatcher.include(request, response); } EasyMock.expectLastCall().once(); } replay(config); replay(request); replay(response); replay(chain); replay(requestDispatcher); customResourceFilter.init(config); customResourceFilter.doFilter(request, response, chain); verify(config); verify(request); verify(response); verify(chain); verify(requestDispatcher); } }
29.24581
87
0.731614
9abf42d8d2636acb16d6de49a6aae0d850e0767c
3,642
/* * Copyright 2019 The nity.io gRPC Spring Boot Project 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 io.nity.grpc.client.channel.factory; import io.grpc.ClientInterceptor; import io.grpc.ManagedChannel; import io.nity.grpc.client.channel.DisposableManagedChannel; import io.nity.grpc.client.channel.configurer.GrpcChannelBuilderConfigurer; import io.nity.grpc.client.channel.configurer.GrpcChannelConfigurer; import io.nity.grpc.client.config.GrpcClientProperties; import io.nity.grpc.client.config.GrpcClientPropertiesMap; import org.springframework.context.ApplicationContext; import java.util.List; public class GrpcChannelFactoryFacede implements GrpcChannelFactory { private GrpcClientPropertiesMap clientPropertiesMap; private final GrpcChannelFactory inProcessChannelFactory; private final GrpcChannelFactory simpleChannelFactory; private final GrpcChannelFactory tlsChannelFactory; private final GrpcChannelFactory customChannelFactory; public GrpcChannelFactoryFacede(final ApplicationContext applicationContext, final GrpcClientPropertiesMap clientPropertiesMap, final GrpcChannelBuilderConfigurer channelBuilderConfigurer, final GrpcChannelConfigurer channelConfigurer) { this.clientPropertiesMap = clientPropertiesMap; this.inProcessChannelFactory = new InProcessChannelFactory(clientPropertiesMap, channelBuilderConfigurer, channelConfigurer); this.simpleChannelFactory = new SimpleChannelFactory(clientPropertiesMap, channelBuilderConfigurer, channelConfigurer); this.tlsChannelFactory = new TlsChannelFactory(clientPropertiesMap, channelBuilderConfigurer, channelConfigurer); this.customChannelFactory = applicationContext.getBean(CustomChannelFactory.class); } @Override public ManagedChannel createChannel(final String name, List<ClientInterceptor> interceptors) { GrpcClientProperties clientProperties = clientPropertiesMap.getClient(name); ManagedChannel channel; if (GrpcClientProperties.SERVER_MODEL_IN_PROCESS.equals(clientProperties.getModel())) { channel = inProcessChannelFactory.createChannel(name, interceptors); } else if (GrpcClientProperties.SERVER_MODEL_SIMPLE.equals(clientProperties.getModel())) { channel = simpleChannelFactory.createChannel(name, interceptors); } else if (GrpcClientProperties.SERVER_MODEL_TLS.equals(clientProperties.getModel())) { channel = tlsChannelFactory.createChannel(name, interceptors); } else if (GrpcClientProperties.SERVER_MODEL_CUSTOM.equals(clientProperties.getModel())) { channel = customChannelFactory.createChannel(name, interceptors); } else { throw new RuntimeException("Failed to create GrpcClient for name:" + name); } DisposableManagedChannel disposableManagedChannel = new DisposableManagedChannel(channel); return disposableManagedChannel; } @Override public void close() { } }
47.298701
133
0.760022
8bd1d6d0fe408c8a214003fda0ed85fa3b13f770
1,411
package piftik.github.com.weatherproject.request.parser; import com.google.gson.Gson; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import piftik.github.com.weatherproject.Weather; import piftik.github.com.weatherproject.request.parser.GsonParsing.ResponsGson; public class GsonParser implements IJsonParser { private static final String TAG = GsonParser.class.getSimpleName(); @Override public ArrayList<Weather> extractWeatherFromJson(InputStream pInputStream) throws Exception { ArrayList<Weather> forecasts = new ArrayList<>(); String jsonResponse = null; Gson gson = new Gson(); Reader reader = new InputStreamReader(pInputStream); ResponsGson responsGson= gson.fromJson(reader, ResponsGson.class); String placeOfCit = responsGson.getCity().getName(); String country = responsGson.getCity().getCountry(); for (int i = 0; i < responsGson.getList().size(); i ++) { String dataText = responsGson.getList().get(i).getDt_txt(); String weatherMain = responsGson.getList().get(i).getWeather().get(0).getMain(); double tempInKelvin = responsGson.getList().get(i).getMain().getTemp(); forecasts.add(new Weather(dataText, weatherMain, tempInKelvin, country, placeOfCit)); } return forecasts; } }
37.131579
97
0.705882
e42a72feb1546dc92faae68009cf2ecd4fe561dd
877
package com.prancingdonkey; import com.prancingdonkey.model.Order; import junit.framework.Assert; import org.junit.Test; import org.mule.api.MuleMessage; import org.mule.api.client.MuleClient; import org.mule.tck.junit4.FunctionalTestCase; import static junit.framework.Assert.*; public class BPMFunctionalTestCase extends FunctionalTestCase { @Override protected String getConfigResources() { return "src/main/app/order-backend-bpm-config.xml"; } @Test public void testCanSubmitOrder() throws Exception { MuleClient client = muleContext.getClient(); Order order = new Order(); client.dispatch("jms://order.submit", order, null); MuleMessage result = client.request("jms://topic:events.orders.completed", 15000); assertNotNull(result); assertTrue(result.getPayload() instanceof Order); } }
28.290323
90
0.720639
c6c085e5e12b7871420768d84c10e4144a965511
624
package me.zenisbestwolf.canyoudumbass.Listeners; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import me.zenisbestwolf.canyoudumbass.Main; public class Block implements Listener { private static Main plugin; public Block(Main plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } @EventHandler public void onBreak(BlockBreakEvent e) { e.getPlayer().sendMessage("GOOD JOB FUCKER YOU BROKE: " + e.getBlock().getType().toString()); } }
29.714286
101
0.727564
24a8d3101a75e86156758211006b3e0e9cd06e48
1,731
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ package com.oracle.idcs.oauth.util; public class Constants { // Properties for assertion public final static String CLIENT_ID = "CLIENT_ID"; public final static String IDCS_URL = "IDCS_URL"; public final static String KEY_ID = "KEY_ID"; public final static String AUDIENCE = "AUDIENCE"; public final static String SCOPE = "SCOPE"; public final static String IDDOMAIN = "IDDOMAIN"; // Certificate and keystore properties public final static String KEYSTORE_PATH = "KEYSTORE_PATH"; // Secret Vault for Certificate and keystore properties public final static String SECRET_KEYSTORE_ID = "V_KEYSTORE"; public final static String SECRET_KS_PASS_ID = "V_KS_PASS"; public final static String SECRET_PK_PASS_ID = "V_PK_PASS"; public final static String USE_CACHE_TOKEN = "USE_CACHE_TOKEN"; public final static String PRINCIPAL = "PRINCIPAL"; // Assertions constants public final static String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; public final static String CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; // Auth Provider OCI Values for local environment testing public final static String LOCAL_OCI_PROFILE = "DEFAULT"; // Use DEFAULT value for PROFILE if you don't have a custom profile for OCI CLI locally public final static String LOCAL_OCI_CONFIG_FILE_PATH = "~/.oci/config"; public final static String CACHED_BEARER_TOKEN = "CACHED_BEARER_TOKEN"; }
44.384615
164
0.729636
d7078961c94d7a46555edc7a48a3195e351f1201
969
package vswe.stevescarts.Buttons; import net.minecraft.entity.player.EntityPlayer; import vswe.stevescarts.Modules.ModuleBase; import vswe.stevescarts.Modules.Workers.ModuleComputer; import vswe.stevescarts.Computer.ComputerProg; import vswe.stevescarts.Computer.ComputerTask; import java.util.ArrayList; public class ButtonProgramStart extends ButtonAssembly { public ButtonProgramStart(ModuleComputer module, LOCATION loc) { super(module, loc); } @Override public String toString() { return "Start Program"; } @Override public boolean isVisible() { return super.isVisible() && true; } @Override public boolean isEnabled() { return ((ModuleComputer)module).getCurrentProg() != null; } @Override public void onServerClick(EntityPlayer player, int mousebutton, boolean ctrlKey, boolean shiftKey) { ComputerProg program = ((ModuleComputer)module).getCurrentProg(); if (program != null) { program.start(); } } }
22.534884
101
0.749226
0f6c94e4f8fe994f40088efbfef137d1076f7bbf
4,509
/* * Copyright 2017 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.priam.backup; import com.google.inject.Inject; import com.netflix.priam.config.IConfiguration; import com.netflix.priam.health.InstanceState; import com.netflix.priam.utils.MaxSizeHashMap; import java.io.*; import java.util.LinkedList; import java.util.Map; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Default implementation for {@link IBackupStatusMgr}. This will save the snapshot status in local * file. Created by aagrawal on 7/11/17. */ @Singleton public class FileSnapshotStatusMgr extends BackupStatusMgr { private static final Logger logger = LoggerFactory.getLogger(FileSnapshotStatusMgr.class); private static final int IN_MEMORY_SNAPSHOT_CAPACITY = 60; private final String filename; /** * Constructor to initialize the file based snapshot status manager. * * @param config {@link IConfiguration} of priam to find where file should be saved/read from. * @param instanceState Status of the instance encapsulating health and other metadata of Priam * and Cassandra. */ @Inject public FileSnapshotStatusMgr(IConfiguration config, InstanceState instanceState) { super( IN_MEMORY_SNAPSHOT_CAPACITY, instanceState); // Fetch capacity from properties, if required. this.filename = config.getBackupStatusFileLoc(); init(); } private void init() { // Retrieve entire file and re-populate the list. File snapshotFile = new File(filename); if (!snapshotFile.exists()) { logger.info( "Snapshot status file do not exist on system. Bypassing initilization phase."); return; } try (final ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(snapshotFile))) { backupMetadataMap = (Map<String, LinkedList<BackupMetadata>>) inputStream.readObject(); logger.info( "Snapshot status of size {} fetched successfully from {}", backupMetadataMap.size(), filename); } catch (IOException e) { logger.error( "Error while trying to fetch snapshot status from {}. Error: {}. If this is first time after upgrading Priam, ignore this.", filename, e.getLocalizedMessage()); e.printStackTrace(); } catch (Exception e) { logger.error( "Error while trying to fetch snapshot status from {}. Error: {}.", filename, e.getLocalizedMessage()); e.printStackTrace(); } if (backupMetadataMap == null) backupMetadataMap = new MaxSizeHashMap<>(capacity); } @Override public void save(BackupMetadata backupMetadata) { File snapshotFile = new File(filename); if (!snapshotFile.exists()) snapshotFile.mkdirs(); // Will save entire list to file. try (final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename))) { out.writeObject(backupMetadataMap); out.flush(); logger.info( "Snapshot status of size {} is saved to {}", backupMetadataMap.size(), filename); } catch (IOException e) { logger.error( "Error while trying to persist snapshot status to {}. Error: {}", filename, e.getLocalizedMessage()); } } @Override public LinkedList<BackupMetadata> fetch(String snapshotDate) { // No need to fetch from local machine as it was read once at start. No point reading again // and again. return backupMetadataMap.get(snapshotDate); } }
37.890756
144
0.634952
a4850028b41254222e04e3e8d366c6ef0a3aa1c5
2,094
package org.accela.minesweeper.model.operation; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.Serializable; public class Operation implements Serializable { private static final long serialVersionUID = 1L; public static enum Type { MOUSE_CLICKED, MOUSE_PRESSED, MOUSE_RELEASED, MOUSE_ENTERED, MOUSE_EXITED, MOUSE_DRAGGED, MOUSE_MOVED, MOUSE_MOTION, MOUSE_WHEEL_MOVED, KEY_TYPED, KEY_PRESSED, KEY_RELEASED }; private Type type = null; private MouseEvent mouseEvent = null; private KeyEvent keyEvent = null; private boolean questionMarkEnabled = true; public Operation(Type type, MouseEvent mouseEvent, KeyEvent keyEvent, boolean questionMarkEnabled) { this.type = type; this.mouseEvent = mouseEvent; this.keyEvent = keyEvent; this.questionMarkEnabled = questionMarkEnabled; } public Type getType() { return this.type; } public MouseEvent getMouseEvent() { return this.mouseEvent; } public KeyEvent getKeyEvent() { return this.keyEvent; } public Object getSource() { if (this.mouseEvent != null) { return this.mouseEvent.getSource(); } else if (this.keyEvent != null) { return this.keyEvent.getSource(); } else { assert (false); return null; } } public boolean isQuestionMarkEnabled() { return questionMarkEnabled; } public boolean isLeftMouseBtnDown() { if(null==this.getMouseEvent()) { return false; } return (getMouseEvent().getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == MouseEvent.BUTTON1_DOWN_MASK; } public boolean isRightMouseBtnDown() { if(null==this.getMouseEvent()) { return false; } return (getMouseEvent().getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) == MouseEvent.BUTTON3_DOWN_MASK; } @Override public String toString() { return "Operation [type=" + type + ", mouseEvent=" + mouseEvent + ", keyEvent=" + keyEvent + ", questionMarkEnabled=" + questionMarkEnabled + "]"; } }
19.388889
108
0.680038
291ee7677ced18b9b24f9dbf46edb6ed3a656a53
1,057
package com.chengxiaoxiao.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.omg.CORBA.Request; import com.chengxiaoxiao.domain.Users; import com.chengxiaoxiao.services.UsersServices; public class ResetUserPwd extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); String id = request.getParameter("id"); int eid = Integer.parseInt(id); UsersServices services = new UsersServices(); PrintWriter out = response.getWriter(); if(services.resetUserpwd(eid)) { out.print("{\"status\":\"ok\",\"msg\":\"密码重置成功\"}"); } else { out.print("{\"status\":\"false\",\"msg\":\"密码重置失败\"}"); } } }
22.489362
80
0.733207
b3cdc58a357a08ab478d4957a25f83436b2c9a6e
1,774
package io.thorntail.openshift.ts.healthcheck; import org.arquillian.cube.openshift.impl.client.OpenShiftAssistant; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; import org.arquillian.cube.openshift.impl.enricher.RouteURL; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URL; import java.util.concurrent.TimeUnit; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.containsString; @RunWith(Arquillian.class) public class HealthCheckIT { @RouteURL(value = "${app.name}", path = "/api/greeting") @AwaitRoute private URL greetingUrl; @RouteURL(value = "${app.name}", path = "/api/stop") private String stopUrl; @ArquillianResource private OpenShiftAssistant openShiftAssistant; @Test public void simpleInvocation() { given() .baseUri(greetingUrl.toString()) .when() .get() .then() .statusCode(200) .body(containsString("Hello, World!")); } @Test public void stopServiceAndWaitForRestart() { simpleInvocation(); given() .baseUri(stopUrl) .when() .post() .then() .statusCode(200); await().atMost(5, TimeUnit.MINUTES).untilAsserted(() -> { given() .baseUri(greetingUrl.toString()) .when() .get() .then() .statusCode(503); }); await().atMost(5, TimeUnit.MINUTES).untilAsserted(this::simpleInvocation); } }
27.71875
82
0.624014
1ff18ef1d687473ab70bf7bbeebf7a917a059c76
3,077
package com.github.wgx731.kirby.service.impl; import com.github.wgx731.kirby.helper.ReviewStatisticsCalculator; import com.github.wgx731.kirby.model.Review; import com.github.wgx731.kirby.service.ReviewService; import lombok.Setter; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import org.springframework.util.FileCopyUtils; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.UncheckedIOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.DoubleSummaryStatistics; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import static java.nio.charset.StandardCharsets.UTF_8; /** * Review Service InMemory Implementation */ @Service public class InMemoryReviewServiceImpl implements ReviewService { private ReviewStatisticsCalculator calculator = ReviewStatisticsCalculator .builder() .reviewHistory(new ConcurrentHashMap<>()) .build(); private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-LLLL-dd"); @Value("classpath:template/daily_empty.txt") @Setter private Resource dailyEmptyTemplate; @Value("classpath:template/daily.txt") @Setter private Resource dailyTemplate; String getStringFromResource(Resource resource) { try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) { return FileCopyUtils.copyToString(reader); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public List<Review> addReview(LocalDate date, Review review) { Map<LocalDate, List<Review>> storage = calculator.getReviewHistory(); List<Review> reviews = new ArrayList<>(); if (storage.containsKey(date)) { reviews = storage.get(date); } reviews.add(review); storage.put(date, reviews); return Collections.unmodifiableList(reviews); } @Override public String getDailyReport(LocalDate date, String name) { Optional<DoubleSummaryStatistics> dailySummary = calculator.getDailySummary(date, name); if (dailySummary.isEmpty()) { return String.format( getStringFromResource(dailyEmptyTemplate), date.format(dateFormatter).toUpperCase(Locale.US), name.toUpperCase(Locale.US) ); } DoubleSummaryStatistics statistics = dailySummary.get(); return String.format( getStringFromResource(dailyTemplate), date.format(dateFormatter).toUpperCase(Locale.US), name.toUpperCase(Locale.US), statistics.getCount(), statistics.getMin(), statistics.getMax(), statistics.getAverage() ); } }
33.086022
96
0.705232
296afd46b23722321cf6ef42c8dbf5d24e3e8fd7
192
package com.vmware.data.demo.retail.store.api.order.product; /** * ProductCacheService * * @author Gregory Green */ public interface ProductCacheService { void loadProductsCache(); }
16
60
0.739583
2353d5c3beb4759b9f353170f7c13ed7ca4c7fe6
12,185
/* * validateapi * The validation APIs help you validate data. Check if an E-mail address is real. Check if a domain is real. Check up on an IP address, and even where it is located. All this and much more is available in the validation API. * * OpenAPI spec version: v1 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.cloudmersive.client.model; import java.util.Objects; import java.util.Arrays; import com.cloudmersive.client.model.Timezone; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Result of performing a country validation operation */ @ApiModel(description = "Result of performing a country validation operation") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2021-10-17T20:35:19.004-07:00") public class ValidateCountryResponse { @SerializedName("Successful") private Boolean successful = null; @SerializedName("CountryFullName") private String countryFullName = null; @SerializedName("ISOTwoLetterCode") private String isOTwoLetterCode = null; @SerializedName("FIPSTwoLetterCode") private String fiPSTwoLetterCode = null; @SerializedName("ThreeLetterCode") private String threeLetterCode = null; @SerializedName("IsEuropeanUnionMember") private Boolean isEuropeanUnionMember = null; @SerializedName("Timezones") private List<Timezone> timezones = null; @SerializedName("ISOCurrencyCode") private String isOCurrencyCode = null; @SerializedName("CurrencySymbol") private String currencySymbol = null; @SerializedName("CurrencyEnglishName") private String currencyEnglishName = null; @SerializedName("Region") private String region = null; @SerializedName("Subregion") private String subregion = null; public ValidateCountryResponse successful(Boolean successful) { this.successful = successful; return this; } /** * True if successful, false otherwise * @return successful **/ @ApiModelProperty(value = "True if successful, false otherwise") public Boolean isSuccessful() { return successful; } public void setSuccessful(Boolean successful) { this.successful = successful; } public ValidateCountryResponse countryFullName(String countryFullName) { this.countryFullName = countryFullName; return this; } /** * Full name of the country * @return countryFullName **/ @ApiModelProperty(value = "Full name of the country") public String getCountryFullName() { return countryFullName; } public void setCountryFullName(String countryFullName) { this.countryFullName = countryFullName; } public ValidateCountryResponse isOTwoLetterCode(String isOTwoLetterCode) { this.isOTwoLetterCode = isOTwoLetterCode; return this; } /** * Two-letter ISO 3166-1 country code * @return isOTwoLetterCode **/ @ApiModelProperty(value = "Two-letter ISO 3166-1 country code") public String getIsOTwoLetterCode() { return isOTwoLetterCode; } public void setIsOTwoLetterCode(String isOTwoLetterCode) { this.isOTwoLetterCode = isOTwoLetterCode; } public ValidateCountryResponse fiPSTwoLetterCode(String fiPSTwoLetterCode) { this.fiPSTwoLetterCode = fiPSTwoLetterCode; return this; } /** * Two-letter FIPS 10-4 country code * @return fiPSTwoLetterCode **/ @ApiModelProperty(value = "Two-letter FIPS 10-4 country code") public String getFiPSTwoLetterCode() { return fiPSTwoLetterCode; } public void setFiPSTwoLetterCode(String fiPSTwoLetterCode) { this.fiPSTwoLetterCode = fiPSTwoLetterCode; } public ValidateCountryResponse threeLetterCode(String threeLetterCode) { this.threeLetterCode = threeLetterCode; return this; } /** * Three-letter ISO 3166-1 country code * @return threeLetterCode **/ @ApiModelProperty(value = "Three-letter ISO 3166-1 country code") public String getThreeLetterCode() { return threeLetterCode; } public void setThreeLetterCode(String threeLetterCode) { this.threeLetterCode = threeLetterCode; } public ValidateCountryResponse isEuropeanUnionMember(Boolean isEuropeanUnionMember) { this.isEuropeanUnionMember = isEuropeanUnionMember; return this; } /** * True if this country is currently a member of the European Union (EU), false otherwise * @return isEuropeanUnionMember **/ @ApiModelProperty(value = "True if this country is currently a member of the European Union (EU), false otherwise") public Boolean isIsEuropeanUnionMember() { return isEuropeanUnionMember; } public void setIsEuropeanUnionMember(Boolean isEuropeanUnionMember) { this.isEuropeanUnionMember = isEuropeanUnionMember; } public ValidateCountryResponse timezones(List<Timezone> timezones) { this.timezones = timezones; return this; } public ValidateCountryResponse addTimezonesItem(Timezone timezonesItem) { if (this.timezones == null) { this.timezones = new ArrayList<Timezone>(); } this.timezones.add(timezonesItem); return this; } /** * Time zones (IANA/Olsen) in the country * @return timezones **/ @ApiModelProperty(value = "Time zones (IANA/Olsen) in the country") public List<Timezone> getTimezones() { return timezones; } public void setTimezones(List<Timezone> timezones) { this.timezones = timezones; } public ValidateCountryResponse isOCurrencyCode(String isOCurrencyCode) { this.isOCurrencyCode = isOCurrencyCode; return this; } /** * ISO 4217 currency three-letter code associated with the country * @return isOCurrencyCode **/ @ApiModelProperty(value = "ISO 4217 currency three-letter code associated with the country") public String getIsOCurrencyCode() { return isOCurrencyCode; } public void setIsOCurrencyCode(String isOCurrencyCode) { this.isOCurrencyCode = isOCurrencyCode; } public ValidateCountryResponse currencySymbol(String currencySymbol) { this.currencySymbol = currencySymbol; return this; } /** * Symbol associated with the currency * @return currencySymbol **/ @ApiModelProperty(value = "Symbol associated with the currency") public String getCurrencySymbol() { return currencySymbol; } public void setCurrencySymbol(String currencySymbol) { this.currencySymbol = currencySymbol; } public ValidateCountryResponse currencyEnglishName(String currencyEnglishName) { this.currencyEnglishName = currencyEnglishName; return this; } /** * Full name of the currency * @return currencyEnglishName **/ @ApiModelProperty(value = "Full name of the currency") public String getCurrencyEnglishName() { return currencyEnglishName; } public void setCurrencyEnglishName(String currencyEnglishName) { this.currencyEnglishName = currencyEnglishName; } public ValidateCountryResponse region(String region) { this.region = region; return this; } /** * Region (continent) in which the country is located; possible values are None, Europe, Americas, Asia, Africa, Oceania * @return region **/ @ApiModelProperty(value = "Region (continent) in which the country is located; possible values are None, Europe, Americas, Asia, Africa, Oceania") public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public ValidateCountryResponse subregion(String subregion) { this.subregion = subregion; return this; } /** * Subregion in which the country is located; possible values are None, NorthernEurope, WesternEurope, SouthernEurope, EasternEurope, CentralAmerica, NorthernAmerica, SouthAmerica, EasternAfrica, MiddleAfrica, NorthernAfrica , SouthernAfrica , WesternAfrica , CentralAsia , EasternAsia , SouthernAsia , SouthEasternAsia , WesternAsia , Southern , Middle , AustraliaandNewZealand , Melanesia , Polynesia , Micronesia , Caribbean, * @return subregion **/ @ApiModelProperty(value = "Subregion in which the country is located; possible values are None, NorthernEurope, WesternEurope, SouthernEurope, EasternEurope, CentralAmerica, NorthernAmerica, SouthAmerica, EasternAfrica, MiddleAfrica, NorthernAfrica , SouthernAfrica , WesternAfrica , CentralAsia , EasternAsia , SouthernAsia , SouthEasternAsia , WesternAsia , Southern , Middle , AustraliaandNewZealand , Melanesia , Polynesia , Micronesia , Caribbean,") public String getSubregion() { return subregion; } public void setSubregion(String subregion) { this.subregion = subregion; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ValidateCountryResponse validateCountryResponse = (ValidateCountryResponse) o; return Objects.equals(this.successful, validateCountryResponse.successful) && Objects.equals(this.countryFullName, validateCountryResponse.countryFullName) && Objects.equals(this.isOTwoLetterCode, validateCountryResponse.isOTwoLetterCode) && Objects.equals(this.fiPSTwoLetterCode, validateCountryResponse.fiPSTwoLetterCode) && Objects.equals(this.threeLetterCode, validateCountryResponse.threeLetterCode) && Objects.equals(this.isEuropeanUnionMember, validateCountryResponse.isEuropeanUnionMember) && Objects.equals(this.timezones, validateCountryResponse.timezones) && Objects.equals(this.isOCurrencyCode, validateCountryResponse.isOCurrencyCode) && Objects.equals(this.currencySymbol, validateCountryResponse.currencySymbol) && Objects.equals(this.currencyEnglishName, validateCountryResponse.currencyEnglishName) && Objects.equals(this.region, validateCountryResponse.region) && Objects.equals(this.subregion, validateCountryResponse.subregion); } @Override public int hashCode() { return Objects.hash(successful, countryFullName, isOTwoLetterCode, fiPSTwoLetterCode, threeLetterCode, isEuropeanUnionMember, timezones, isOCurrencyCode, currencySymbol, currencyEnglishName, region, subregion); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ValidateCountryResponse {\n"); sb.append(" successful: ").append(toIndentedString(successful)).append("\n"); sb.append(" countryFullName: ").append(toIndentedString(countryFullName)).append("\n"); sb.append(" isOTwoLetterCode: ").append(toIndentedString(isOTwoLetterCode)).append("\n"); sb.append(" fiPSTwoLetterCode: ").append(toIndentedString(fiPSTwoLetterCode)).append("\n"); sb.append(" threeLetterCode: ").append(toIndentedString(threeLetterCode)).append("\n"); sb.append(" isEuropeanUnionMember: ").append(toIndentedString(isEuropeanUnionMember)).append("\n"); sb.append(" timezones: ").append(toIndentedString(timezones)).append("\n"); sb.append(" isOCurrencyCode: ").append(toIndentedString(isOCurrencyCode)).append("\n"); sb.append(" currencySymbol: ").append(toIndentedString(currencySymbol)).append("\n"); sb.append(" currencyEnglishName: ").append(toIndentedString(currencyEnglishName)).append("\n"); sb.append(" region: ").append(toIndentedString(region)).append("\n"); sb.append(" subregion: ").append(toIndentedString(subregion)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
33.847222
456
0.737054
1463af2334048bb25a06e54fe45d19064b745f39
9,032
/* * Copyright © 2019 Cask Data, 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 io.cdap.plugin.gcp.bigquery.sink; import com.google.gson.stream.JsonWriter; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.plugin.gcp.bigquery.util.BigQueryUtil; import java.io.IOException; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * Util class to convert structured record into json. */ public final class BigQueryRecordToJson { private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS"); /** * Writes object and writes to json writer. * @param writer json writer to write the object to * @param name name of the field to be written * @param object object to be written * @param fieldSchema field schema to be written */ public static void write(JsonWriter writer, String name, Object object, Schema fieldSchema) throws IOException { write(writer, name, false, object, fieldSchema); } /** * Writes object and writes to json writer. * @param writer json writer to write the object to * @param name name of the field to be written * @param isArrayItem true if the method is writing array item. This means the name of the array field will not be * added to the json writer * @param object object to be written * @param fieldSchema field schema to be written */ private static void write(JsonWriter writer, String name, boolean isArrayItem, Object object, Schema fieldSchema) throws IOException { Schema schema = BigQueryUtil.getNonNullableSchema(fieldSchema); switch (schema.getType()) { case NULL: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case STRING: case BYTES: writeSimpleTypes(writer, name, isArrayItem, object, schema); break; case ARRAY: writeArray(writer, name, object, schema); break; default: throw new IllegalStateException( String.format("Field '%s' is of unsupported type '%s'", name, fieldSchema.getType())); } } /** * Writes simple types to json writer. * @param writer json writer * @param name name of the field to be written * @param isArrayItem true if the method is writing array item. This means the name of the array field will not be * added to the json writer * @param object object to be written * @param schema field schema to be written */ private static void writeSimpleTypes(JsonWriter writer, String name, boolean isArrayItem, Object object, Schema schema) throws IOException { if (!isArrayItem) { writer.name(name); } if (object == null) { writer.nullValue(); return; } Schema.LogicalType logicalType = schema.getLogicalType(); if (logicalType != null) { switch (logicalType) { case DATE: writer.value(Objects.requireNonNull(LocalDate.ofEpochDay(((Integer) object).longValue()).toString())); break; case TIME_MILLIS: writer.value(TIME_FORMATTER.format( Objects.requireNonNull(LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(((Integer) object)))))); break; case TIME_MICROS: writer.value(TIME_FORMATTER.format( Objects.requireNonNull(LocalTime.ofNanoOfDay(TimeUnit.MICROSECONDS.toNanos((Long) object))))); break; case TIMESTAMP_MILLIS: //timestamp for json input should be in this format yyyy-MM-dd HH:mm:ss.SSSSSS writer.value(DATETIME_FORMATTER.format( Objects.requireNonNull(getZonedDateTime((long) object, TimeUnit.MILLISECONDS)))); break; case TIMESTAMP_MICROS: writer.value(DATETIME_FORMATTER.format( Objects.requireNonNull(getZonedDateTime((long) object, TimeUnit.MICROSECONDS)))); break; case DECIMAL: writer.value(Objects.requireNonNull(getDecimal(name, (byte[]) object, schema)).toPlainString()); break; default: throw new IllegalStateException( String.format("Field '%s' is of unsupported type '%s'", name, logicalType.getToken())); } return; } switch (schema.getType()) { case NULL: writer.nullValue(); // nothing much to do here. break; case INT: case LONG: case FLOAT: case DOUBLE: writer.value((Number) object); break; case BOOLEAN: writer.value((Boolean) object); break; case STRING: writer.value(object.toString()); break; // TODO CDAP-15342 write byte type to json writer default: throw new IllegalStateException(String.format("Field '%s' is of unsupported type '%s'", name, schema.getType())); } } private static void writeArray(JsonWriter writer, String name, Object value, Schema fieldSchema) throws IOException { if (value == null) { throw new RuntimeException( String.format("Field '%s' is of value null, which is not a valid value for BigQuery type array.", name)); } if (!(value instanceof Collection) && !value.getClass().isArray()) { throw new IllegalArgumentException("The value should be of type collection or array. Got: " + value.getClass()); } Schema componentSchema = BigQueryUtil.getNonNullableSchema(fieldSchema.getComponentSchema()); if (BigQueryUtil.UNSUPPORTED_ARRAY_TYPES.contains(componentSchema.getType())) { throw new IllegalArgumentException(String.format("Field '%s' is an array of '%s', " + "which is not a valid BigQuery type.", name, componentSchema)); } writer.name(name); writer.beginArray(); if (value instanceof Collection) { for (Object element : (Collection) value) { // big query does not allow null values in array items if (element == null) { throw new IllegalArgumentException(String.format("Field '%s' contains null values in its array, " + "which is not allowed by BigQuery.", name)); } write(writer, name, true, element, componentSchema); } } else { for (int i = 0; i < Array.getLength(value); i++) { // big query does not allow null values in array items if (Array.get(value, i) == null) { throw new IllegalArgumentException(String.format("Field '%s' contains null values in its array, " + "which is not allowed by BigQuery.", name)); } write(writer, name, true, Array.get(value, i), componentSchema); } } writer.endArray(); } private static ZonedDateTime getZonedDateTime(long ts, TimeUnit unit) { long mod = unit.convert(1, TimeUnit.SECONDS); int fraction = (int) (ts % mod); long tsInSeconds = unit.toSeconds(ts); // create an Instant with time in seconds and fraction which will be stored as nano seconds. Instant instant = Instant.ofEpochSecond(tsInSeconds, unit.toNanos(fraction)); return ZonedDateTime.ofInstant(instant, ZoneId.ofOffset("UTC", ZoneOffset.UTC)); } private static BigDecimal getDecimal(String name, byte[] value, Schema schema) { int scale = schema.getScale(); BigDecimal decimal = new BigDecimal(new BigInteger(value), scale); if (decimal.precision() > 38 || decimal.scale() > 9) { throw new IllegalArgumentException( String.format("Numeric Field '%s' has invalid precision '%s' and scale '%s'. " + "Precision must be at most 38 and scale must be at most 9.", name, decimal.precision(), decimal.scale())); } return decimal; } private BigQueryRecordToJson() { //no-op } }
39.269565
120
0.646258
4bc0b0b9340823bb363442597a8c6555d0a72478
1,393
package io.github.ingvarc.text; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 10, time = 1) @Measurement(iterations = 10, time = 1) @Fork(1) @State(Scope.Thread) public class PalindromeBenchmark { @Param({"Anna", "Racecar", "Evil olive", "Noel sees Leon", "No lemon, no melon", "Some men interpret nine memos", "Gateman sees name, garageman sees nametag"}) private String text; public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(PalindromeBenchmark.class.getSimpleName()) .build(); new Runner(opt).run(); } @Benchmark public void isPalindrome() { Palindrome.isPalindrome(text); } @Benchmark public void isPalindromeReverseString() { Palindrome.isPalindromeReverseString(text); } @Benchmark public void isPalindromeStringBuilder() { Palindrome.isPalindromeStringBuilder(text); } @Benchmark public void countDigitsLog() { Palindrome.isPalindromeIntStream(text); } }
28.428571
90
0.694903
46bb6b7a3c64acff88f0947ef3972265d543eec7
377
package com.redhat.service.smartevents.manager.dao; import com.redhat.service.smartevents.infra.models.processors.ProcessorType; /** * Custom Type for {@link ProcessorType} enumeration. */ public class EnumTypeProcessorType extends EnumTypeBase<ProcessorType> { @Override protected Class<ProcessorType> getEnumClass() { return ProcessorType.class; } }
25.133333
76
0.761273
0d556292fd2b144e147e21fb3236907917d97e66
4,229
package daos; import models.Home; import models.User; import play.db.jpa.JPAApi; import javax.inject.Inject; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import java.util.Collection; import java.util.List; public class UserdaoImpl implements Userdao{ final JPAApi jpaApi; @Inject public UserdaoImpl(JPAApi jpaApi) { this.jpaApi = jpaApi; } @Override public User create(User user) { if (null == user) { throw new IllegalArgumentException("user must be provided"); } jpaApi.em().persist(user); return user; } @Override public User update(User user) { if(null == user){ throw new IllegalArgumentException("user does not exist"); } if(null == user.getUsername()){ throw new IllegalArgumentException("UserName must be provided"); } final User existingUser = findUserByName(user.getUsername()); if(null == existingUser){ throw new IllegalArgumentException("Invalid user"); } existingUser.setName(user.getName()); existingUser.setGender(user.getGender()); existingUser.setDob(user.getDob()); existingUser.setMobilenbr(user.getMobilenbr()); existingUser.setAadharcard(user.getAadharcard()); existingUser.setAddress((user.getAddress())); jpaApi.em().persist(existingUser); return existingUser; } @Override public User findUserByName(String username) { User user = null; try { TypedQuery<User> query = jpaApi.em().createQuery("SELECT u from User u WHERE username = '" + username + "'", User.class); user = query.getSingleResult(); } catch(NoResultException nre){ } if(null == user){ return null; } return user; } @Override public User findUserByAuthToken(String authToken) { User user = null; try { //LOGGER.debug("accessToken at find by level" + authToken); TypedQuery<User> query = jpaApi.em().createQuery("SELECT u from User u WHERE u.accessToken = '" + authToken +"' ", User.class); user = query.getSingleResult(); } catch(NoResultException nre){ throw new IllegalArgumentException("Sign in to complete the action"); } return user; } @Override public User updateaccessToken(User user) { if(null == user){ throw new IllegalArgumentException("user does not exist"); } if(null == user.getUsername()){ throw new IllegalArgumentException("UserName must be provided"); } final User existingUser = findUserByName(user.getUsername()); if(null == existingUser){ throw new IllegalArgumentException("Invalid user"); } existingUser.setAccessToken(user.getAccessToken()); jpaApi.em().persist(existingUser); return existingUser; } @Override public User userRoleUpdate(User existingUser) { if(null == existingUser){ throw new IllegalArgumentException("Invalid user"); } //existingUser.setHouseStatus(Home.HouseStatus.APPROVED); existingUser.setRole(User.Role.HOST); jpaApi.em().persist(existingUser); return existingUser; } @Override public User findUserById(Integer id) { if(null == id){ throw new IllegalArgumentException("Id must be provided"); } final User existingUser = jpaApi.em().find(User.class,id); if(null == existingUser){ throw new IllegalArgumentException("Invalid User"); } //LOGGER.debug("urls are"+ imageDao.searchByHomeId(36)); return existingUser; } // @Override // public Collection<User> pendingUsers() { // TypedQuery<User> query = jpaApi.em().createQuery("SELECT u FROM User u WHERE home.houseStatus= 0 and user.role = 1", User.class); // List<User> users = query.getResultList(); // // return users; // // } }
24.876471
140
0.60227
60e2b5eb066d1a166a6d1a8dfe69e13df13403fb
3,916
package com.ray.model.service; import java.util.List; import com.ray.model.dao.ImageRepository; import com.ray.model.dao.RepositoryFactory; import com.ray.model.entities.Arquivo; import com.ray.util.ArquivosUtil; import com.ray.util.Miniatura; import com.ray.util.ThreadMiniature; public class ImageService { private ImageRepository repository = RepositoryFactory.createImageDao(); /** * Seta miniatura e base64 pra "";<br> * checa o contentType do arquivo, se nao for uma imagem, seta o tipo de acordo com o contentType <br> * inicia o trabalho de thread para criar miniatura. * @param arquivo * @return */ public Arquivo save(Arquivo arquivo) { boolean isImage = arquivo.getContentType().contains("image"); boolean IsPdf = arquivo.getContentType().contains("pdf"); if (isImage || IsPdf) { arquivo.setMiniatura(""); } else { String contentType = ArquivosUtil.getContentType(arquivo.getNome()); arquivo.setContentType("application/" + contentType); arquivo.setMiniatura("null"); } arquivo.setBase64(""); Arquivo fileToSave = repository.save(arquivo); new ThreadMiniature(fileToSave); return fileToSave; } public Arquivo update(Arquivo arquivo, boolean updateInputStream) { return repository.update(arquivo, updateInputStream); } public boolean deleteById(Long id) { Long withoutImage = 0L; boolean hasImage = !id.equals(withoutImage); if (hasImage) { repository.deleteById(id); return true; } return false; } /** * * @param canecaId - todas as imagens de acordo com o id da caneca * @param withInputStream - <br> * setar true para caso queira a lista completa, com * todos os atributos. <br> * Setar falso caso queira a lista parcialmente completa, * sem inputstream * @return todas as canecas */ public List<Arquivo> findAll(Long canecaId, boolean withInputStream) { List<Arquivo> arquivos = repository.findAll(canecaId); arquivos.forEach(x -> setMiniature(x)); arquivos.forEach(x -> x.setFileSize(ArquivosUtil.getReadableFileSize(x))); if (withInputStream) { return arquivos; } arquivos.forEach(x -> x.setInputStream(null)); return arquivos; } /** * * @param canecaId - todas as imagens de acordo com o id da caneca * @param withInputStream - <br> * setar true para caso queira a lista completa, com * todos os atributos. <br> * Setar falso caso queira a lista parcialmente completa, * sem inputstream * @return todas as canecas */ public List<Arquivo> findAllWithout64Base(Long canecaId) { List<Arquivo> arquivos = repository.findAllHalfElements(canecaId); arquivos.forEach(x -> setMiniature(x)); // arquivos.forEach(x -> x.setFileSize(ArquivosUtil.getReadableFileSize(x))); //tamanho dos arquivos. arquivos.forEach(x -> x.setBase64("")); arquivos.forEach(x -> x.setInputStream(null)); return arquivos; } /** * Seta miniatura de acordo com seu tipo de arquivo caso nao seja uma imagem * @param arquivo */ private void setMiniature(Arquivo arquivo) { boolean notAImage = !arquivo.getContentType().contains("image"); if (notAImage) { if (arquivo.getContentType().contains("pdf")) { arquivo.setMiniatura(Miniatura.PDF); }else if(arquivo.getContentType().contains("docx")) { arquivo.setMiniatura(Miniatura.WORD); }else if(arquivo.getContentType().contains("psd")) { arquivo.setMiniatura(Miniatura.PSD); }else if(arquivo.getContentType().contains("eps")) { arquivo.setMiniatura(Miniatura.EPS); }else if(arquivo.getContentType().contains("cdr")) { arquivo.setMiniatura(Miniatura.CDR); } } } }
34.052174
106
0.660368
81745f1158cc4f474638414e581ae25310c0e7b8
737
package com.semmle.ts.ast; import com.semmle.js.ast.Expression; import com.semmle.js.ast.Identifier; import com.semmle.js.ast.SourceLocation; import com.semmle.js.ast.Statement; import com.semmle.js.ast.Visitor; /** * An import of form <tt>import a = E</tt>. */ public class ImportWholeDeclaration extends Statement { private final Identifier lhs; private final Expression rhs; public ImportWholeDeclaration(SourceLocation loc, Identifier lhs, Expression rhs) { super("ImportWholeDeclaration", loc); this.lhs = lhs; this.rhs = rhs; } public Identifier getLhs() { return lhs; } public Expression getRhs() { return rhs; } @Override public <C, R> R accept(Visitor<C, R> v, C c) { return v.visit(this, c); } }
21.057143
84
0.720488
eb6325eb4658aa3c796002142148cad4eecb7440
7,751
package cortador; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class SacoDePrototipos extends SacoDePiezasH { private MuestrarioDeSaco muestrarioDeSaco=null;; public SacoDePrototipos(int noPiezasH) { super(noPiezasH); // TODO Auto-generated constructor stub } public void leeSacoDesdeFile_Bezier_Normal() { // String directorio = DirectorioTrabajo.directorio;// Garde dir // racine du proyect // String directorio_normal = directorio + File.separator + "objetos" + // File.separator + "normal_svg"; String directorio_normal = null; // DirectorioBase dbase = new DirectorioBase(); File directorio_normalD = null; // final File directorio_normalD = new File(directorio_normal); directorio_normal = DirectorioBase .getNombreFileFromResources("cortador" + File.separator + "objetos" + File.separator + "normal_svg"); directorio_normalD = new File(directorio_normal); // directorio_normalD = DirectorioBase.getFileFromResources("objetos" + // File.separator + "normal_svg"); noPiezasH = directorio_normalD.listFiles().length; System.out.format("No total de dessins:%d%n", noPiezasH); creaSaco(noPiezasH); if (saco != null) { int i = 0; for (final File fileEntry : directorio_normalD.listFiles()) { if (fileEntry.isDirectory()) { // listFilesForFolder(fileEntry); } else { String nombre_svgP = fileEntry.getName(); // noPiezas = scanner.nextInt(); saco[i] = new PiezaH(); saco[i].obtiene_curvas_de_bezier_normal_de_pieza(nombre_svgP); saco[i].setAncho(1.); saco[i].setAlto(1.); saco[i].setPosX(0.); saco[i].setPosY(0.); //saco[i].escalaCurbasDeBezier(1.,1.);//MALO saco[i].setRect0(new RectanguloH(0.,0.,saco[i].getAncho(),saco[i].getAlto())); i++; } } } } @SuppressWarnings("serial") class MuestrarioDeSaco extends JPanel implements ActionListener { int RECT_X = 20; int RECT_Y = 20; int RECT_HEIGHT = 200; int RECT_WIDTH = 400; private double ANCHO_WIN = 100; private double ALTO_WIN = 100; private JButton button = null; private int indPieza = 0; private final int ESCALAX = 100; //ESCALE DE DIMENSIONS DE DESSINS private final int ESCALAY = 100; public int getRECT_X() { return RECT_X; } public int getRECT_Y() { return RECT_Y; } public int getRECT_WIDTH() { return RECT_WIDTH; } public int getRECT_HEIGHT() { return RECT_HEIGHT; } public void muestra_piezas_en_pane() { JFrame frame = new JFrame(); setLayout(new BorderLayout()); button = new JButton(); // add(label, BorderLayout.EAST); add(button, BorderLayout.SOUTH); // button.setLocation(250, 100); button.setText("Suivant"); button.addActionListener(this); // add(label); // add(button); frame.add(this); frame.setSize(RECT_WIDTH, RECT_HEIGHT); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public void muestra_protos() { setLayout(new BorderLayout()); button = new JButton(); // add(label, BorderLayout.EAST); add(button, BorderLayout.SOUTH); button.setText("Suivant"); button.addActionListener(this); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // draw the rectangle here Color cOld = g.getColor(); Color cNew = new Color(0, 0, 0); g.setColor(cNew); // dibuja_pieza(g, saco[0], 100); // for (int i = 0; i < saco.length; i++) { if (saco.length > 0) { int i_fig = indPieza % saco.length; saco[i_fig].dibuja_pieza(g, 100, saco[i_fig].getRect0(),ESCALAX, ESCALAY, 100, 10); String nombre = saco[i_fig].getNombre(); g.drawString(nombre, 10, 150); } else System.out.println("saco.length=0"); /* * Color cp = saco[i].getColorDePieza(); g.setColor(cp); // g.setColor(new * Color(0, 0, 0)); int pX = saco[i].getRect().getPosX(); int pY = * saco[i].getRect().getPosY(); int dX = saco[i].getRect().getDX(); int dY = * saco[i].getRect().getDY(); g.fillRect(RECT_X + pX, RECT_Y + pY, dX, dY); */ g.setColor(cOld); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub if (arg0.getActionCommand() == button.getText()) { // System.out.println("Boton apretado"); indPieza++; repaint(); } } public void dibuja_pieza(Graphics g, PiezaH pz, int presicion, int escalax, int escalay, int xOrigen, int yOrigen) { Point P1, P2, P3, P4, resG, res_prevG; EleCalculo elx; Path pathX; P1 = new Point(); P2 = new Point(); P3 = new Point(); P4 = new Point(); resG = new Point(); res_prevG = new Point(); // Point p1=NULL,p2=NULL,p3=NULL,p4=NULL; // p1= MALLOC(point);p2= MALLOC(point);p3= MALLOC(point);p4= MALLOC(point); // Point res=MALLOC(point);Point res_prev=MALLOC(point); boolean esPrimero = true; double tx, del = 1. / presicion; int no_paths = pz.pathList.size(); for (int i = 0; i < no_paths; i++) { pathX = pz.pathList.get(i); if (pathX.flag_vis == 1) { for (int j = 0; pathX.path != null && j < pathX.path.size(); j++) { elx = pathX.path.get(j); P1.x = elx.xP1 * pz.getAncho() * escalax + pz.getPosXP0() * escalax + xOrigen; P1.y = elx.yP1 * pz.getAlto() * escalay + pz.getPosYP0() * escalay + yOrigen; P2.x = elx.xP2 * pz.getAncho() * escalax + pz.getPosXP0() * escalax + xOrigen; P2.y = elx.yP2 * pz.getAlto() * escalay + pz.getPosYP0() * escalay + yOrigen; P3.x = elx.xP3 * pz.getAncho() * escalax + pz.getPosXP0() * escalax + xOrigen; P3.y = elx.yP3 * pz.getAlto() * escalay + pz.getPosYP0() * escalay + yOrigen; P4.x = elx.xP4 * pz.getAncho() * escalax + pz.getPosXP0() * escalax + xOrigen; P4.y = elx.yP4 * pz.getAlto() * escalay + pz.getPosYP0() * escalay + yOrigen; for (int k = 0; k < presicion + 1; k++) { tx = del * k; if (elx.t == 'c' || elx.t == 'C') resG = Bezier.vectorBezierC(tx, resG, P1, P2, P3, P4); if (elx.t == 'q' || elx.t == 'Q') resG = Bezier.vectorBezierQ(tx, resG, P1, P2, P3); if (elx.t == 'L' || elx.t == 'l') resG = Bezier.vectorBezierL(tx, resG, P1, P2); if (!esPrimero) { // dibuja linea entre puntos res y res_pr g.drawLine((int) res_prevG.x, (int) res_prevG.y, (int) resG.x, (int) resG.y); // g.drawLine((int) (ANCHO_WIN * res_prevG.x), (int) (ALTO_WIN * res_prevG.y), // (int) (ANCHO_WIN * resG.x), (int) (ALTO_WIN * resG.y)); } res_prevG.x = resG.x; res_prevG.y = resG.y; esPrimero = false; // printf("%d %lf\t%lf\t%lf\n",path->id,t,res->x,res->y); } esPrimero = true; } } } return; } @Override public Dimension getPreferredSize() { // so that our GUI is big enough return new Dimension(RECT_WIDTH + 2 * RECT_X, 3 * RECT_HEIGHT + 2 * RECT_Y); } } MuestrarioDeSaco getMuestrario() { return muestrarioDeSaco; } public void generaMuestrario() { muestrarioDeSaco = new MuestrarioDeSaco(); } public static void main(String[] args) { SacoDePrototipos sacoDePrototipos = new SacoDePrototipos(1); sacoDePrototipos.leeSacoDesdeFile_Bezier_Normal(); sacoDePrototipos.generaMuestrario() ; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { sacoDePrototipos.getMuestrario().muestra_piezas_en_pane(); } }); } }
30.636364
105
0.645336
f162d726cd0d7ee2f540104b61c02dcfd1db30e0
1,036
package org.firstinspires.ftc.teamcode.testers; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.AnalogInput; import com.qualcomm.robotcore.hardware.CRServo; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.Servo; import org.firstinspires.ftc.teamcode.common.UniversalConstants; import org.firstinspires.ftc.teamcode.common.utilities.Gamepad; import org.firstinspires.ftc.teamcode.modules.elevator.Clamp; @TeleOp(group = "TestOp", name = "Clamp") public class ClampTester extends LinearOpMode { @Override public void runOpMode() throws InterruptedException { Clamp clamp = new Clamp(hardwareMap); Gamepad g = new Gamepad(this); waitForStart(); while (opModeIsActive()) { clamp.updateByGamepad(g); g.update(); telemetry.addData("Clamp", clamp.getStatus()); telemetry.update(); } } }
34.533333
64
0.73166
b4fd0966baaf6f94b457f6a41c10be8bc8fcee7e
2,364
package backend.core.Staff; import backend.core.Staff.domain.Staff; import backend.core.Staff.domain.StaffStatus; import backend.core.Staff.dto.StaffResponseDto; import backend.core.Staff.service.StaffService; import backend.core.global.response.ApiResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import java.util.stream.Collectors; import static backend.core.Staff.dto.StaffRequestDto.StaffCreateRequestDto; @RestController @Slf4j @RequestMapping("/api/v1") @RequiredArgsConstructor public class StaffController { private final StaffService staffService; @PostMapping("/staff") public StaffResponseDto save( @AuthenticationPrincipal String userId, @Valid @RequestBody StaffCreateRequestDto dto) { Long staffId = staffService.save(dto); Staff staff = staffService.findByIdOrThrow(staffId); return new StaffResponseDto(staff); } @GetMapping("/staff/{id}") public StaffResponseDto findById( @PathVariable Long id) { Staff staff = staffService.findByIdOrThrow(id); return new StaffResponseDto(staff); } @GetMapping("/staffs") public ApiResponse findAll( @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "100") int limit) { List<Staff> staffList = staffService.findAllOrThrow(offset, limit); List<StaffResponseDto> result = staffList.stream() .map(staff -> new StaffResponseDto(staff)) .collect(Collectors.toList()); return ApiResponse.builder().count(result.size()).data(result).build(); } @GetMapping("/staff") public ApiResponse findByStatus( @RequestParam(name = "status", defaultValue = "WAIT") String status) { List<Staff> staffList = staffService.findByStatusOrThrow(StaffStatus.valueOf(status)); List<StaffResponseDto> result = staffList.stream() .map(staff -> new StaffResponseDto(staff)) .collect(Collectors.toList()); return ApiResponse.builder().count(result.size()).data(result).build(); } }
35.283582
94
0.702623
66f73db7ccab6d9f37e0395c3abde067f1bad42a
1,966
package com.cwj.datasource.configuration; import lombok.Data; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** * com.cwj.datasource.elasticsearch.curd * * @author ChengWenjia cwj1714@163.com * @date 2021-12-16 10:12 */ @Data @Configuration @PropertySource(value = "classpath:application-data-dev.yml", encoding = "UTF-8") @ConfigurationProperties(prefix = "spring.elasticsearch") public class ElasticSearchClientConfig /*extends AbstractElasticsearchConfiguration*/ { private String hostName; @Bean public RestHighLevelClient restHighLevelClient() { // 注意:http://es.yannises.cn 域名中已经包含了9200端口,所以无需再次设置端口号 RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create(hostName))); System.out.println("client toString: " + client.toString()); return client; // 完整写法 // return new RestHighLevelClient(RestClient.builder(new HttpHost(hostName, 9200, "http"))); } // 此种定义方式总是自动追加9200端口号。 //@NotNull //@Override //@Bean //// 2021-12-16 11:12:35 //// https://docs.spring.io/spring-data/elasticsearch/docs/4.0.6.RELEASE/reference/html/#elasticsearch.clients.rest //public RestHighLevelClient elasticsearchClient() { // System.out.println("-----> hostName: " + hostName); // // // 使用构建器提供集群地址、设置默认值HttpHeaders或启用 SSL // final ClientConfiguration clientConfiguration = ClientConfiguration.builder() // .connectedTo(hostName) // .build(); // // // 创建 RestHighLevelClient // return RestClients.create(clientConfiguration).rest(); //} }
36.407407
119
0.717192
23649cf33a42d1c7680da6ede27f33c340572477
213
package org.drools.spi; import org.drools.base.ClassObjectType; public interface AcceptsClassObjectType extends Acceptor { public void setClassObjectType(ClassObjectType classObjectType); }
21.3
69
0.765258
0e4bb8fdc202cf866ee56e03ef35f361276a9afe
1,241
/* * Copyright © 2022 Pl4yingNight (pl4yingnight@gmail.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 net.runeduniverse.lib.rogm.test.model; import java.util.HashSet; import java.util.Set; import lombok.Getter; import lombok.Setter; import net.runeduniverse.lib.rogm.annotations.Property; import net.runeduniverse.lib.rogm.annotations.Relationship; import net.runeduniverse.lib.rogm.annotations.Transient; import net.runeduniverse.lib.rogm.test.model.relations.Slot; @Getter @Setter public class Inventory extends AEntity { @Relationship private Set<Slot> slots = new HashSet<>(); @Property private Integer size = -1; @Transient private String inventory = null; }
31.820513
76
0.743755
434a189f8ebd995f17e9ab6604c272cfc7cbc9a5
3,759
/** * 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.catalog.definition; import com.tinkerpop.pipes.PipeFunction; import com.tinkerpop.pipes.transform.TransformFunctionPipe; import org.apache.atlas.catalog.Request; import org.apache.atlas.catalog.TaxonomyResourceProvider; import org.apache.atlas.catalog.VertexWrapper; import org.apache.atlas.catalog.exception.InvalidPayloadException; import org.apache.atlas.catalog.projection.Projection; import org.apache.atlas.catalog.projection.ProjectionResult; import org.apache.atlas.typesystem.types.DataTypes; import org.apache.atlas.typesystem.types.utils.TypesUtil; import java.util.*; /** * Taxonomy resource definition. */ public class TaxonomyResourceDefinition extends BaseResourceDefinition { public TaxonomyResourceDefinition() { registerProperty(TypesUtil.createUniqueRequiredAttrDef("name", DataTypes.STRING_TYPE)); registerProperty(TypesUtil.createOptionalAttrDef("description", DataTypes.STRING_TYPE)); registerProperty(TypesUtil.createOptionalAttrDef(TaxonomyResourceProvider.NAMESPACE_ATTRIBUTE_NAME, DataTypes.STRING_TYPE)); //todo: combine with above registrations instanceProperties.add("name"); instanceProperties.add("description"); instanceProperties.add("creation_time"); collectionProperties.add("name"); collectionProperties.add("description"); projections.put("terms", getTermsProjection()); } @Override public void validateCreatePayload(Request request) throws InvalidPayloadException { super.validateCreatePayload(request); if (String.valueOf(request.getQueryProperties().get("name")).contains(".")) { throw new InvalidPayloadException("The \"name\" property may not contain the character '.'"); } } @Override public String getTypeName() { return "Taxonomy"; } @Override public String getIdPropertyName() { return "name"; } @Override public String resolveHref(Map<String, Object> properties) { return String.format("v1/taxonomies/%s", properties.get("name")); } private Projection getTermsProjection() { final String termsProjectionName = "terms"; return new Projection(termsProjectionName, Projection.Cardinality.SINGLE, new TransformFunctionPipe<>(new PipeFunction<VertexWrapper, Collection<ProjectionResult>>() { private String baseHref = "v1/taxonomies/"; @Override public Collection<ProjectionResult> compute(VertexWrapper v) { Map<String, Object> map = new HashMap<>(); map.put("href", baseHref + v.getProperty("name") + "/terms"); return Collections.singleton(new ProjectionResult(termsProjectionName, v, Collections.singleton(map))); } })); } }
40.858696
132
0.701782
c9b5cd6b3b890ea8671caf0d11d7c328adc35a12
429
package behavioral_patterns.strategy.after.client; import behavioral_patterns.strategy.after.flybehavior.FlyWithWings; import behavioral_patterns.strategy.after.quackbehavior.Quack; public class RedheadDuck extends Duck { public RedheadDuck() { flyBehavior = new FlyWithWings(); quackBehavior = new Quack(); } @Override public void display() { System.out.println("redheadduck"); } }
26.8125
67
0.724942
50c641112f073849d8ff31bbc847dbd287f90e78
9,235
/* * 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. */ /** * @author Sergey Burlak */ package javax.swing.plaf.metal; import javax.swing.UIDefaults; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; public abstract class MetalTheme { private static final ColorUIResource blackColor = new ColorUIResource(0, 0, 0); private static final ColorUIResource whiteColor = new ColorUIResource(255, 255, 255); /** */ public MetalTheme() { } /** * Return the theme name * @return String name */ public abstract String getName(); /** * Return window title font * @return FontUIResource result */ public abstract FontUIResource getWindowTitleFont(); /** * Return user text font * @return FontUIResource result */ public abstract FontUIResource getUserTextFont(); /** * Return system text font * @return FontUIResource result */ public abstract FontUIResource getSystemTextFont(); /** * Return sub text font * @return FontUIResource result */ public abstract FontUIResource getSubTextFont(); /** * Return menu text font * @return FontUIResource result */ public abstract FontUIResource getMenuTextFont(); /** * Return control text font * @return FontUIResource result */ public abstract FontUIResource getControlTextFont(); protected abstract ColorUIResource getPrimary3(); protected abstract ColorUIResource getPrimary2(); protected abstract ColorUIResource getPrimary1(); protected abstract ColorUIResource getSecondary3(); protected abstract ColorUIResource getSecondary2(); protected abstract ColorUIResource getSecondary1(); /** * Return window title inactive foreground color * @return ColorUIResource result */ public ColorUIResource getWindowTitleInactiveForeground() { return getBlack(); } /** * Return window title inactive background color * @return ColorUIResource result */ public ColorUIResource getWindowTitleInactiveBackground() { return getSecondary3(); } /** * Return window title foreground color * @return ColorUIResource result */ public ColorUIResource getWindowTitleForeground() { return getBlack(); } /** * Return window title background color * @return ColorUIResource result */ public ColorUIResource getWindowTitleBackground() { return getPrimary3(); } /** * Return window background color * @return ColorUIResource result */ public ColorUIResource getWindowBackground() { return getWhite(); } /** * Return white color * @return ColorUIResource result */ protected ColorUIResource getWhite() { return whiteColor; } /** * Return user text color * @return ColorUIResource result */ public ColorUIResource getUserTextColor() { return getBlack(); } /** * Return user text color * @return ColorUIResource result */ public ColorUIResource getTextHighlightColor() { return getPrimary3(); } /** * Return system text color * @return ColorUIResource result */ public ColorUIResource getSystemTextColor() { return getBlack(); } /** * Return separator foreground color * @return ColorUIResource result */ public ColorUIResource getSeparatorForeground() { return getPrimary1(); } /** * Return separator background color * @return ColorUIResource result */ public ColorUIResource getSeparatorBackground() { return getWhite(); } /** * Return primary control shadow color * @return ColorUIResource result */ public ColorUIResource getPrimaryControlShadow() { return getPrimary2(); } /** * Return primary control info color * @return ColorUIResource result */ public ColorUIResource getPrimaryControlInfo() { return getBlack(); } /** * Return primary control highlight color * @return ColorUIResource result */ public ColorUIResource getPrimaryControlHighlight() { return getWhite(); } /** * Return primary control dark shadow color * @return ColorUIResource result */ public ColorUIResource getPrimaryControlDarkShadow() { return getPrimary1(); } /** * Return primary control color * @return ColorUIResource result */ public ColorUIResource getPrimaryControl() { return getPrimary3(); } /** * Return menu selected foreground color * @return ColorUIResource result */ public ColorUIResource getMenuSelectedForeground() { return getBlack(); } /** * Return menu selected background color * @return ColorUIResource result */ public ColorUIResource getMenuSelectedBackground() { return getPrimary2(); } /** * Return menu foreground color * @return ColorUIResource result */ public ColorUIResource getMenuForeground() { return getBlack(); } /** * Return menu disabled foreground color * @return ColorUIResource result */ public ColorUIResource getMenuDisabledForeground() { return getSecondary2(); } /** * Return menu background color * @return ColorUIResource result */ public ColorUIResource getMenuBackground() { return getSecondary3(); } /** * Return inactive system text color * @return ColorUIResource result */ public ColorUIResource getInactiveSystemTextColor() { return getSecondary2(); } /** * Return inactive control text color * @return ColorUIResource result */ public ColorUIResource getInactiveControlTextColor() { return getSecondary2(); } /** * Return highlighted text color * @return ColorUIResource result */ public ColorUIResource getHighlightedTextColor() { return getBlack(); } /** * Return focus color * @return ColorUIResource result */ public ColorUIResource getFocusColor() { return getPrimary2(); } /** * Return desktop color * @return ColorUIResource result */ public ColorUIResource getDesktopColor() { return getPrimary2(); } /** * Return control text color * @return ColorUIResource result */ public ColorUIResource getControlTextColor() { return getBlack(); } /** * Return control shadow color * @return ColorUIResource result */ public ColorUIResource getControlShadow() { return getSecondary2(); } /** * Return control info color * @return ColorUIResource result */ public ColorUIResource getControlInfo() { return getBlack(); } /** * Return control highlight color * @return ColorUIResource result */ public ColorUIResource getControlHighlight() { return getWhite(); } /** * Return control disabled color * @return ColorUIResource result */ public ColorUIResource getControlDisabled() { return getSecondary2(); } /** * Return control dark shadow color * @return ColorUIResource result */ public ColorUIResource getControlDarkShadow() { return getSecondary1(); } /** * Return control color * @return ColorUIResource result */ public ColorUIResource getControl() { return getSecondary3(); } /** * Return black color * @return ColorUIResource result */ protected ColorUIResource getBlack() { return blackColor; } /** * Return selected accelerator color * @return ColorUIResource result */ public ColorUIResource getAcceleratorSelectedForeground() { return getBlack(); } /** * Return accelerator foreground color * @return ColorUIResource result */ public ColorUIResource getAcceleratorForeground() { return getPrimary1(); } /** * Add custom entries to the defaults table * @param uiDefs defaults table */ public void addCustomEntriesToTable(final UIDefaults uiDefs) { } }
24.112272
89
0.642447
6447b0438cd684f3b673f2af7722abb662b4deec
1,220
package com.vihanga.sample.scim2.java.client; import java.io.FileInputStream; import java.io.IOException; import java.util.PropertyResourceBundle; /** * Test class to demonstrate SCIM2 Java API Usage. */ public class SCIMTest { public static void main(String[] args) { try { String propertyFilePath = "src/main/resources/app.properties"; PropertyResourceBundle properties = new PropertyResourceBundle(new FileInputStream(propertyFilePath)); SCIM2Client scim2Client = new SCIM2Client(properties); String username = "vihanga"; String scimId = scim2Client.getUserSCIMID(username); System.out.println("SCIM ID of the user " + username + " is: " + scimId); String status = scim2Client.updateUserAttribute(scimId, "name.givenName", "Vihanga Liyanage"); System.out.println("Updating user attribute givenName... Status: " + status); status = scim2Client.updateExtendedUserAttribute(scimId, "country", "Sri Lanka"); System.out.println("Updating extended user attribute country... Status: " + status); } catch (IOException e) { e.printStackTrace(); } } }
34.857143
114
0.664754
1cf3baaac7cdf09455853014ad77e904e2e227cd
2,059
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2020, Nordix Foundation. 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. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.model; import lombok.NoArgsConstructor; import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; @NoArgsConstructor public class AttributeDefinition extends AttributeDataDefinition implements IOperationParameter, IComplexDefaultValue { public AttributeDefinition(final AttributeDataDefinition attributeDataDefinition) { super(attributeDataDefinition); } @Override public String getDefaultValue() { return get_default() == null ? null : String.valueOf(get_default()); } @Override public void setDefaultValue(final String value) { set_default(value); } @Override public boolean isDefinition() { return false; } @Override public String toString() { return "AttributeDefinition{" + "name=" + getName() + "uniqueId=" + getUniqueId() + "ownerId=" + getOwnerId() + "type=" + getType() + "description=" + getDescription() + "default=" + getDefaultValue() + '}'; } }
34.898305
119
0.578922
7a89a6542fd88c7b8a46cd5a99de775eac5d9fd6
506
package kr.co.popone.fitts.feature.post.detail; import kotlin.jvm.functions.Function0; import kotlin.jvm.internal.Lambda; final class PostActivity$defaultPostId$2 extends Lambda implements Function0<Long> { final /* synthetic */ PostActivity this$0; PostActivity$defaultPostId$2(PostActivity postActivity) { this.this$0 = postActivity; super(0); } public final long invoke() { return this.this$0.getIntent().getLongExtra("post_id", -1); } }
28.111111
85
0.683794
88de518e40c6eb36586593ebbde98269071869fb
792
package com.lunaticaliens.bankingapp.ui.launch; import android.app.Application; import android.view.View; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; public class LaunchViewModel extends AndroidViewModel { private static final String TAG = "LaunchViewModel"; private LaunchPageCallBack launchPageCallBack = null; public LaunchViewModel(@NonNull Application application) { super(application); } void setLaunchPageCallBack(LaunchPageCallBack launchPageCallBack) { this.launchPageCallBack = launchPageCallBack; } public void onLoginButtonClick(View view) { launchPageCallBack.onLogin(); } public void onRegisterButtonClick(View view) { launchPageCallBack.onRegistration(); } }
24.75
71
0.752525
32ddd251cd03f71582aab0a87d2dec2a8aab4bcb
1,516
package com.animsh.newsdeap.data; import java.io.Serializable; /** * Created by animsh on 1/18/2021. */ public class Article implements Serializable { private final NewsSource source; // News Source private final String author; // News Author private final String title; // News Title private final String description; // News Description private final String url; // News URL private final String urlToImage; // News Image URL private final String publishedAt; // News Published Date private final String content; // News Content public Article(NewsSource source, String author, String title, String description, String url, String urlToImage, String publishedAt, String content) { this.source = source; this.author = author; this.title = title; this.description = description; this.url = url; this.urlToImage = urlToImage; this.publishedAt = publishedAt; this.content = content; } public NewsSource getSource() { return source; } public String getAuthor() { return author; } public String getTitle() { return title; } public String getDescription() { return description; } public String getUrl() { return url; } public String getUrlToImage() { return urlToImage; } public String getPublishedAt() { return publishedAt; } public String getContent() { return content; } }
24.852459
155
0.645119
e6376dcb7ce5b839dd086d5e66069437d145275e
2,235
package io.github.inventories; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import io.github.valk.Viesta; public class JoinInventory implements Listener { Viesta plugin; public JoinInventory (Viesta instance) { plugin = instance; } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { Player p = event.getPlayer(); PlayerInventory inventory = p.getInventory(); if (!p.hasPlayedBefore()) { inventory.setHelmet(invItem(Material.IRON_HELMET, "Lil' Helm", new String[] { "Keeps your head warm!", "Never get cold again!" })); inventory.setChestplate(invItem(Material.IRON_CHESTPLATE, "Plate", new String[] { "Protects you from stuff.", "Very useful.", "Will save your life.." })); inventory.setLeggings(invItem(Material.IRON_LEGGINGS, "Leggings", new String[] { "Protects you from alot of stuff.", ":D" })); inventory.setBoots(invItem(Material.IRON_BOOTS, "Lil' Shoes", new String[] { "Very useful for walking.", "I'm really bad at this xD" })); inventory.addItem(invItem(Material.IRON_SWORD, "Ms. Sharpy", new String[] { "Early-game helpful sword.", "Very hard to craft in-game.", "Also known as sword of the cat." })); inventory.addItem(invItem(Material.BREAD, "Bread", new String[] { "Yumm!" })); } } private ItemStack invItem(Material item, String name, String[] lore) { ItemStack stack = new ItemStack(item); stack.addUnsafeEnchantment(Enchantment.FROST_WALKER, 1); ItemMeta stack_meta = stack.getItemMeta(); stack_meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&a" + name)); List<String> item_lore = new ArrayList<String>(); for (int i = 0; i < lore.length; i++) { item_lore.add(ChatColor.translateAlternateColorCodes('&', "&2" + lore[i])); } stack_meta.setLore(item_lore); stack.setItemMeta(stack_meta); return stack; } }
37.25
107
0.727517
060b4be58c85c50e024aa9f069d0f0510d42209d
4,749
package com.workflowconversion.portlet.ui.table.resource; import org.apache.commons.lang3.Validate; import com.vaadin.data.Item; import com.vaadin.ui.Label; import com.workflowconversion.portlet.core.exception.ApplicationException; import com.workflowconversion.portlet.core.resource.Resource; import com.workflowconversion.portlet.core.resource.ResourceProvider; import com.workflowconversion.portlet.core.utils.KeyUtils; import com.workflowconversion.portlet.ui.table.AbstractGenericElementDetailsDialog; import com.workflowconversion.portlet.ui.table.AbstractTableWithControls; import com.workflowconversion.portlet.ui.table.AbstractTableWithControlsFactory; import com.workflowconversion.portlet.ui.table.Size; import com.workflowconversion.portlet.ui.table.TableWithControls; /** * Table on which resources are displayed. * * @author delagarza * */ public class ResourceTable extends AbstractTableWithControls<Resource> { private final static long serialVersionUID = 4634915248824534764L; private final static String PROPERTY_RESOURCE = "ResourcesTable_property_resource"; private final ResourceProvider resourceProvider; /** * The size of a couple of components depends on the width of this table. */ public static final int WIDTH_PIXELS = 650; private ResourceTable(final String title, final ResourceProvider resourceProvider) { // cannot modify resources super(title, false, true); Validate.notNull(resourceProvider, "resourceProvider cannot be null. This seems to be a coding problem and should be reported."); this.resourceProvider = resourceProvider; } @Override protected void setUpContainerProperties() { addContainerProperty(Resource.Field.Name, Label.class); addContainerProperty(Resource.Field.Type, Label.class); // no need to provide a type, since these two properties are hidden // and their type will be set to Object.class addContainerProperty(Resource.Field.Queues); addContainerProperty(Resource.Field.Applications); addContainerProperty(PROPERTY_RESOURCE); } @Override public Size getSize() { final Size tableDimensions = new Size(); tableDimensions.width = WIDTH_PIXELS; tableDimensions.widthUnit = Unit.PIXELS; tableDimensions.height = 350; tableDimensions.heightUnit = Unit.PIXELS; return tableDimensions; } @Override protected Object[] getVisibleColumns() { return new Object[] { Resource.Field.Name, Resource.Field.Type }; } @SuppressWarnings("unchecked") @Override protected void fillItemProperties(final Resource resource, final Item item) { item.getItemProperty(Resource.Field.Name).setValue(newLabelWithValue(resource.getName())); item.getItemProperty(Resource.Field.Type).setValue(newLabelWithValue(resource.getType())); item.getItemProperty(Resource.Field.Queues).setValue(resource.getQueues()); item.getItemProperty(Resource.Field.Applications).setValue(resource.getApplications()); item.getItemProperty(PROPERTY_RESOURCE).setValue(resource); } @Override protected String getKeyForItem(final Item item) { final String name = ((Label) (item.getItemProperty(Resource.Field.Name).getValue())).getValue(); final String type = ((Label) (item.getItemProperty(Resource.Field.Type).getValue())).getValue(); return KeyUtils.generateResourceKey(name, type); } @Override protected Resource convertFromItem(final Item item) { return (Resource) item.getItemProperty(PROPERTY_RESOURCE).getValue(); } @Override protected AbstractGenericElementDetailsDialog<Resource> createElementDetailDialog(final Object itemId, final Resource element) { return new ResourceDetailsDialog(itemId, element, this, element.canModifyApplications()); } @Override public void elementDetailsSaved(final Object itemId, final Resource resource) { if (resourceProvider.canAddApplications() && resource.canModifyApplications()) { super.elementDetailsSaved(itemId, resource); resourceProvider.save(resource); } else { throw new ApplicationException( "The resource and/or the provider don't support modifying/adding applications. This seems to be a coding problem and should be reported."); } } /** * Factory for resource tables. * * @author delagarza */ public static class ResourceTableFactory extends AbstractTableWithControlsFactory<Resource> { private ResourceProvider resourceProvider; /** * @param resourceProvider * the resource provider. * @return {@code this} factory. */ public ResourceTableFactory withResourceProvider(final ResourceProvider resourceProvider) { this.resourceProvider = resourceProvider; return this; } @Override public TableWithControls<Resource> newInstance() { return new ResourceTable(super.title, resourceProvider); } } }
35.706767
144
0.78585
a1b348bf39de5de2a965ace2050dc46c08cce18b
3,029
package eu.telecomnancy.pcd2k17; import org.gitlab4j.api.models.Group; import java.io.*; import java.util.ArrayList; import java.util.List; public class FileManager { public static String getFilePath(String name) { String directoryPath = System.getProperty("user.dir") + File.separator + "saves"; File folder = new File(directoryPath); if(!folder.exists()) folder.mkdirs(); return folder.getAbsoluteFile() + File.separator + name; } public static ArrayList<GroupConfiguration> loadGroupsFromFile() { File file = new File(getFilePath("groups")); FileInputStream fIn; ObjectInputStream oIn; try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if(file.length() > 0) { try { fIn = new FileInputStream(file); oIn = new ObjectInputStream(fIn); ArrayList groupsConfiguration = (ArrayList) oIn.readObject(); if (oIn != null) oIn.close(); if (fIn != null) fIn.close(); return groupsConfiguration; } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return null; } public static ArrayList getNewGroupsInGit(List<GroupConfiguration> groupsList) { List<GroupConfiguration> groupsConfigurationList = loadGroupsFromFile(); ArrayList<GroupConfiguration> newGroupsList = new ArrayList(); int k; if (groupsList != null) { for (int i = 0; i < groupsList.size(); i++) { k = -1; if (groupsConfigurationList != null) { for (int j = 0; j < groupsConfigurationList.size(); j++) { if (groupsList.get(i).getId() == groupsConfigurationList.get(j).getId()) { k = j; break; } } } if(k >= 0) newGroupsList.add(groupsConfigurationList.get(k)); else newGroupsList.add(groupsList.get(i)); } return newGroupsList; } return null; } public static void saveGroupsInFile(ArrayList<GroupConfiguration> groupsList) { if(groupsList != null) { FileOutputStream fOut; ObjectOutputStream oOut; try { fOut = new FileOutputStream(getFilePath("groups")); oOut = new ObjectOutputStream(fOut); oOut.writeObject(groupsList); if (oOut != null) oOut.close(); if (fOut != null) fOut.close(); } catch (IOException e) { e.printStackTrace(); } } } }
28.575472
98
0.508088
04bed55264906cc4d0c81dcc525cb9ff5754b88a
6,446
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.carbon.identity.conditional.auth.functions.user; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.authentication.framework.config.model.graph.js.JsAuthenticatedUser; import org.wso2.carbon.identity.application.common.model.ClaimConfig; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.conditional.auth.functions.user.internal.UserFunctionsServiceHolder; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.user.profile.mgt.UserProfileException; import org.wso2.carbon.identity.user.profile.mgt.dao.UserProfileMgtDAO; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import java.util.Arrays; import java.util.Collections; import java.util.Map; public class SetAccountAssociationToLocalUserImpl implements SetAccountAssociationToLocalUser { private final String USERNAME_LOCAL_CLAIM = "http://wso2.org/claims/username"; private static final Log log = LogFactory.getLog(SetAccountAssociationToLocalUserImpl.class); @Override public void doAssociationWithLocalUser(JsAuthenticatedUser federatedUser, String username, String tenantDomain, String userStoreDomainName) { String federatedIdpName = null; try { if (federatedUser != null) { if (federatedUser.getWrapped().isFederatedUser()) { federatedIdpName = federatedUser.getWrapped().getFederatedIdPName(); String userIdClaimURI = getUserIdClaimURI(federatedIdpName, tenantDomain); String externalSubject; if (StringUtils.isNotEmpty(userIdClaimURI)) { externalSubject = federatedUser.getWrapped().getUserAttributes().entrySet().stream().filter( userAttribute -> userAttribute.getKey().getRemoteClaim().getClaimUri() .equals(userIdClaimURI)) .map(Map.Entry::getValue) .findFirst() .orElse(null); } else { externalSubject = federatedUser.getWrapped().getAuthenticatedSubjectIdentifier(); } String externalIdpName = federatedUser.getWrapped().getFederatedIdPName(); if (externalSubject != null && externalIdpName != null) { associateID(externalIdpName, externalSubject, username, tenantDomain, userStoreDomainName); } else { log.warn(" Authenticated user or External IDP may be null " + " Authenticated User: " + externalSubject + " and the External IDP name: " + externalIdpName); } } else { log.warn("User " + federatedUser.getWrapped().getAuthenticatedSubjectIdentifier() + " " + "is not a federated user."); } } else { log.warn(" Federated user is null "); } } catch (IdentityProviderManagementException e) { String msg = "Error while retrieving identity provider by name: " + federatedIdpName; log.error(msg, e); } } private String getUserIdClaimURI(String federatedIdpName, String tenantDomain) throws IdentityProviderManagementException { String userIdClaimURI = null; IdentityProvider idp = UserFunctionsServiceHolder.getInstance().getIdentityProviderManagementService() .getIdPByName(federatedIdpName, tenantDomain); if (idp == null) { return null; } ClaimConfig claimConfigs = idp.getClaimConfig(); if (claimConfigs == null) { return null; } ClaimMapping[] claimMappings = claimConfigs.getClaimMappings(); if (CollectionUtils.isEmpty(Collections.singleton(userIdClaimURI))) { return null; } ClaimMapping userNameClaimMapping = Arrays.stream(claimMappings).filter(claimMapping -> StringUtils.equals(USERNAME_LOCAL_CLAIM, claimMapping.getLocalClaim().getClaimUri())) .findFirst() .orElse(null); if (userNameClaimMapping != null) { userIdClaimURI = userNameClaimMapping.getRemoteClaim().getClaimUri(); } return userIdClaimURI; } /** * @param idpID external IDP name * @param associatedID external authenticated user * @param username local user name * @param tenantDomain tenant domain * @param userStoreDomainName user store domain name */ private void associateID(String idpID, String associatedID, String username, String tenantDomain, String userStoreDomainName) { int tenantID = IdentityTenantUtil.getTenantId(tenantDomain); try { UserProfileMgtDAO userProfileMgtDAO = UserProfileMgtDAO.getInstance(); userProfileMgtDAO.createAssociation(tenantID, userStoreDomainName, username, idpID, associatedID); } catch (UserProfileException e) { String msg = "Error while creating association for user: " + username + " with federated IdP: " + "" + idpID; log.error(msg, e); } } }
48.104478
121
0.64319
76d4e1889ca98c1caf62ee3b18162000ebd1b580
3,092
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * 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.tectonica.jonix.onix3; import java.io.Serializable; import com.tectonica.jonix.JPU; import com.tectonica.jonix.OnixElement; import com.tectonica.jonix.codelist.PriceTypes; import com.tectonica.jonix.codelist.RecordSourceTypes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ /** * <h1>Price type code</h1> * <p> * An ONIX code indicating the type of the comparison price in the &lt;PriceAmount&gt; element within the * &lt;ComparisonProductPrice&gt; composite. Optional if a &lt;DefaultPriceType&gt; has been specified in the message * header, otherwise mandatory. Non-repeating. * </p> * <table border='1' cellpadding='3'> * <tr> * <td>Format</td> * <td>Fixed-length, two digits</td> * </tr> * <tr> * <td>Codelist</td> * <td>List 58</td> * </tr> * <tr> * <td>Reference name</td> * <td>&lt;PriceType&gt;</td> * </tr> * <tr> * <td>Short tag</td> * <td>&lt;x462&gt;</td> * </tr> * <tr> * <td>Cardinality</td> * <td>0&#8230;1</td> * </tr> * <tr> * <td>Example</td> * <td>&lt;PriceType&gt;01&lt;/PriceType&gt; (RRP excluding tax)</td> * </tr> * </table> */ public class PriceType implements OnixElement, Serializable { private static final long serialVersionUID = 1L; public static final String refname = "PriceType"; public static final String shortname = "x462"; // /////////////////////////////////////////////////////////////////////////////// // ATTRIBUTES // /////////////////////////////////////////////////////////////////////////////// /** * (type: dt.DateOrDateTime) */ public String datestamp; public RecordSourceTypes sourcetype; public String sourcename; // /////////////////////////////////////////////////////////////////////////////// // VALUE MEMBER // /////////////////////////////////////////////////////////////////////////////// public PriceTypes value; // /////////////////////////////////////////////////////////////////////////////// // SERVICES // /////////////////////////////////////////////////////////////////////////////// public PriceType() {} public PriceType(org.w3c.dom.Element element) { datestamp = JPU.getAttribute(element, "datestamp"); sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype")); sourcename = JPU.getAttribute(element, "sourcename"); value = PriceTypes.byCode(JPU.getContentAsString(element)); } }
28.366972
117
0.586999
f97933342c74f1c2f19eb01280a4986aaf393f59
1,947
package org.thoughtcrime.securesms.insights; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.thoughtcrime.securesms.recipients.Recipient; import java.util.Collections; import java.util.List; final class InsightsDashboardState { private final List<Recipient> insecureRecipients; private final InsightsData insightsData; private final InsightsUserAvatar userAvatar; private InsightsDashboardState(@NonNull Builder builder) { this.insecureRecipients = builder.insecureRecipients; this.insightsData = builder.insightsData; this.userAvatar = builder.userAvatar; } static @NonNull InsightsDashboardState.Builder builder() { return new InsightsDashboardState.Builder(); } @NonNull InsightsDashboardState.Builder buildUpon() { return builder().withData(insightsData).withUserAvatar(userAvatar).withInsecureRecipients(insecureRecipients); } @NonNull List<Recipient> getInsecureRecipients() { return insecureRecipients; } @Nullable InsightsUserAvatar getUserAvatar() { return userAvatar; } @Nullable InsightsData getData() { return insightsData; } static final class Builder { private List<Recipient> insecureRecipients = Collections.emptyList(); private InsightsUserAvatar userAvatar; private InsightsData insightsData; private Builder() { } @NonNull Builder withInsecureRecipients(@NonNull List<Recipient> insecureRecipients) { this.insecureRecipients = insecureRecipients; return this; } @NonNull Builder withData(@NonNull InsightsData insightsData) { this.insightsData = insightsData; return this; } @NonNull Builder withUserAvatar(@NonNull InsightsUserAvatar userAvatar) { this.userAvatar = userAvatar; return this; } @NonNull InsightsDashboardState build() { return new InsightsDashboardState(this); } } }
27.422535
114
0.741654
119a8c8d9aff6d43548f327906333d68777a5a15
15,926
package com.assistant.mediatransfer; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import com.assistant.connection.Connection; import com.assistant.connection.ConnectionCreationResponse; import com.assistant.connection.ConnectionManager; import com.assistant.connection.EventSendRequest; import com.assistant.connection.EventSendResponse; import com.assistant.events.ChatMessageEvent; import com.assistant.events.ClientInfo; import com.assistant.events.Event; import com.assistant.events.EventFactory; import com.assistant.events.FileEvent; import com.assistant.utils.Log; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class ClientManager { private static ClientManager sInstance; public static ClientManager getInstance(Context context) { if (sInstance == null && context != null) { sInstance = new ClientManager(context); } return sInstance; } public interface ClientManagerListener { void onClientAvailable(int id, ClientInfo info); void onClientDisconnected(int id, int reason); void onMessageReceived(int clientId, Event msg); void onMessageSendResult(int clientId, int msgId, boolean isSuccess); } private Set<ClientManagerListener> mListeners = Collections.synchronizedSet(new HashSet<ClientManagerListener>()); private Context mContext; private ConnectionManager mConnectionManager; private MediaTransferManager mMediaTransferManager; private Set<Integer> mConnectionIds = Collections.synchronizedSet(new HashSet<Integer>()); // TODO: key string use unique id of one connection. private Map<Integer, Object> mMsgCollections = Collections.synchronizedMap(new HashMap<Integer, Object>(10)); private ThreadHandler mThreadHandler; class ThreadHandler extends Handler { public static final int EVENT_CONNECTION_ADDED = 1; public static final int EVENT_CONNECTION_REMOVED = 2; public static final int EVENT_CONNECTION_EVENT_RECEIVED = 3; public static final int EVENT_LISTEN = 4; public static final int EVENT_SEARCH_HOST = 5; ThreadHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { switch (msg.what) { case EVENT_CONNECTION_ADDED: handleConnectionAdded(msg.arg1); break; case EVENT_CONNECTION_REMOVED: handleConnectionClosed(msg.arg1, msg.arg2); break; case EVENT_CONNECTION_EVENT_RECEIVED: handleEventReceived(msg.arg1, (Event) msg.obj); break; case EVENT_LISTEN: handleListenEvent(msg.arg1); break; case EVENT_SEARCH_HOST: handleSearchHostEvent((ConnectionManager.SearchListener)msg.obj); break; default: break; } super.handleMessage(msg); } } private ClientManager(Context context) { mContext = context; mConnectionManager = ConnectionManager.getInstance(context); mMediaTransferManager = MediaTransferManager.getInstance(context); mConnectionManager.addListener(new ConnectionManager.ConnectionManagerListener() { @Override public void onConnectionAdded(int id) { mThreadHandler .obtainMessage(ThreadHandler.EVENT_CONNECTION_ADDED, id, 0) .sendToTarget(); } @Override public void onConnectionRemoved(int id, int reason) { mThreadHandler .obtainMessage(ThreadHandler.EVENT_CONNECTION_REMOVED, id, reason) .sendToTarget(); } @Override public void onEventReceived(int id, Event event) { mThreadHandler .obtainMessage( ThreadHandler.EVENT_CONNECTION_EVENT_RECEIVED, id, 0, event) .sendToTarget(); } }); HandlerThread thread = new HandlerThread("ClientManager"); thread.start(); mThreadHandler = new ThreadHandler(thread.getLooper()); } public List<Event> getMessageList(int connId) { Connection connection = mConnectionManager.getConnection(connId); if (connection != null) { ClientInfo clientInfo = (ClientInfo) connection.getConnData(); Log.d(this, "getMessageList, get msg list for connId:" + connId); if (clientInfo != null) { return (List<Event>)mMsgCollections.get(connId); } else { Log.d(this, "getMessageList, clientInfo not received for id:" + connId); } } else { Log.d(this, "getMessageList, connection not avaible for id:" + connId); } return null; } public int sendEvent(int connId, Event event, EventSendResponse response) { if (event != null) { EventSendRequest request = new EventSendRequest(event, response); recordVisibleEvent(connId, event); Log.d(this, "sendEvent, connId:" + event.connId + ", event:" + event.getEventClassName()); mConnectionManager.sendEvent(request); } return 0; } public int sendFile(int connId, String filePathName, EventSendResponse response) { FileEvent event = EventFactory.generateFileEvent(connId, filePathName); if (event != null) { EventSendRequest request = new EventSendRequest(event, response); recordVisibleEvent(connId, event); mConnectionManager.sendEvent(request); return 0; } Log.d(this, "sendFile, generateFileEvent failed!"); return -1; } public boolean isClientAvailable(int connId) { synchronized (mConnectionIds) { return mConnectionIds.contains(connId); } } public List<Integer> getConnectionIds() { List<Integer> connIdList; synchronized (mConnectionIds) { connIdList = Collections.synchronizedList(new ArrayList<Integer>(mConnectionIds.size())); connIdList.addAll(mConnectionIds); } return connIdList; } private void handleConnectionAdded(int connId) { Connection connection = mConnectionManager.getConnection(connId); Log.d(this, "handleConnectionAdded, connId:" + connId); if (connection != null && !connection.isHost()) { sendClientInfoEvent(connId); } } private void sendClientInfoEvent(int connId) { Log.d(this, "sendClientInfoEvent, connId:" + connId); ClientInfo clientInfoEvent = mMediaTransferManager.getClientInfo(); clientInfoEvent.setConnId(connId); clientInfoEvent.setEventCreateTime(System.currentTimeMillis()); sendEvent(connId, clientInfoEvent, new EventSendResponse() { @Override public void onSendProgress(long eventId, int percent) {} @Override public void onResult(int connId, long eventId, int result, int failedReason) { if (result == EventSendResponse.RESULT_FAILED) { Connection connection = mConnectionManager.getConnection(connId); if (connection != null) { Log.d(this, "ClientInfo Event send failed for connection:" + connId); connection.close(Connection.CONNECTION_REASON_CODE_IO_EXCEPTION); } } } }); } private void handleConnectionClosed(int connId, int closeReason) { Log.d(this, "handleConnectionClosed, connId:" + connId); removeConnectId(connId); mMsgCollections.remove(connId); notifyClientDisconnected(connId, closeReason); } private void handleEventReceived(int connId, Event event) { Log.d(this, "handleEventReceived, connId:" + connId + ", event:" + event.toString()); switch (event.getEventType()) { case Event.EVENT_TYPE_CLIENTNAME: handleClientInfoEvent(connId, (ClientInfo)event); break; case Event.EVENT_TYPE_FILE: case Event.EVENT_TYPE_CHAT: recordVisibleEvent(connId, event); notifyEventReceived(connId, event); break; default: break; } } private void handleClientInfoEvent(int connId, ClientInfo clientInfo) { Connection connection = mConnectionManager.getConnection(connId); if (connection != null) { Log.d(this, "handleClientInfoEvent, received ClientInfo, connId:" + connection.getId() + ", client size:" + mConnectionIds.size()); connection.setConnData(clientInfo); if (mMsgCollections.get(connId) == null) { List<Event> mMsgArray = Collections.synchronizedList(new ArrayList<Event>()); Log.d(this, "handleClientInfoEvent, create msg list for uid:" + clientInfo.clientUniqueId); mMsgCollections.put(connId, mMsgArray); } addConnectionId(connId); // when connection connected, client send info to host side first. // host side will send info back after received client info. if (connection.isHost()) { Log.d(this, "handleClientInfoEvent, response ClientInfo"); sendClientInfoEvent(connId); } notifyClientAvailable(connId, clientInfo); } } void recordVisibleEvent(int connId, Event event){ if (event instanceof ChatMessageEvent || event instanceof FileEvent) { Log.d(this, "recordVisibleEvent, record event for connId:" + connId); List<Event> msgList = getMessageList(connId); if (msgList != null) { msgList.add(event); } else { Log.d(this, "recordVisibleEvent, ChatMessageEvent message list not found!"); } } else { Log.d(this, "recordVisibleEvent, event not recorded:" + event.getEventClassName()); } } private void addConnectionId(int connId) { synchronized (mConnectionIds) { Log.d(this, "addConnectionId:" + connId); if (!mConnectionIds.contains(Integer.valueOf(connId))) { mConnectionIds.add(Integer.valueOf(connId)); } } logConnectionIds(); } private void removeConnectId(int connId) { synchronized (mConnectionIds) { Log.d(this, "removeConnectId:" + connId); mConnectionIds.remove(Integer.valueOf(connId)); } logConnectionIds(); } private void logConnectionIds() { StringBuilder builder = new StringBuilder(); synchronized (mConnectionIds) { if (mConnectionIds.size() > 0) { for (Integer id : mConnectionIds) { builder.append(String.valueOf(id) + " "); } } else { builder.append("No connection ids!"); } } Log.d(this, "mConnectionIds:" + builder.toString()); } public void connectTo(String ipAddress, int port, ConnectionCreationResponse listener) { mConnectionManager.connectTo(ipAddress, port, listener); } public void startListen() { mThreadHandler.obtainMessage(ThreadHandler.EVENT_LISTEN, mMediaTransferManager.getPort(), 0).sendToTarget(); } public void startSearchHost(ConnectionManager.SearchListener listener) { mThreadHandler.obtainMessage(ThreadHandler.EVENT_SEARCH_HOST,listener).sendToTarget(); } private void handleListenEvent(int port) { mConnectionManager.listen(port); } private void handleSearchHostEvent(ConnectionManager.SearchListener listener) { NetworkInfoManager networkInfoManager = NetworkInfoManager.getInstance(mContext); String ip = networkInfoManager.getWifiIpAddressString(); Log.d(this, "startSearchHost, ip:" + ip + ", wifi connected:" + networkInfoManager.isWifiConnected() + ", listener:" + listener); if (!TextUtils.isEmpty(ip) && networkInfoManager.isWifiConnected() && mMediaTransferManager.isNetworkSettingsOn()) { mConnectionManager.searchHost(ip, listener); } else { if (listener != null) { listener.onSearchCompleted(); } } } public void disconnectAllConnections() { mConnectionManager.disconnectAllConnections(); } public void addListener(ClientManagerListener listener) { if (listener != null) { mListeners.add(listener); } } public void removeListener(ClientManagerListener listener) { if (listener != null) { mListeners.remove(listener); } } protected void notifyClientAvailable(int connId, ClientInfo info) { for (ClientManagerListener listener : mListeners) { listener.onClientAvailable(connId, info); } } protected void notifyClientDisconnected(int connId, int reason) { for (ClientManagerListener listener : mListeners) { listener.onClientDisconnected(connId, reason); } } protected void notifyEventReceived(int connId, Event event) { for (ClientManagerListener listener : mListeners) { listener.onMessageReceived(connId, event); } } protected void notifyMessageSendResult(int connId, int msgId, boolean isSuccess) { for (ClientManagerListener listener : mListeners) { listener.onMessageSendResult(connId, msgId, isSuccess); } } public void dump(FileDescriptor fd, PrintWriter writer, String[] args) { try { writer.println("ClientManager:"); writer.println(" mListeners size:" + mListeners.size()); // dump connection id list: String idList = ""; for(int id : mConnectionIds) { idList += id + " "; } writer.println(" Connection Ids:" + idList); writer.println(" Connection Msgs:"); // dump connection messages mMsgCollections for (int connId : mMsgCollections.keySet()) { List<Event> events = (List<Event>)mMsgCollections.get(connId); if (events != null) { for(Event event : events) { writer.println(" connId[" + connId + "], Event:" + event.toString()); } writer.println(" "); } } writer.flush(); // mMediaTransferManager mMediaTransferManager.dump(fd, writer, args); writer.println(""); // mConnectionManager mConnectionManager.dump(fd, writer, args); writer.flush(); } catch (Exception e) { Log.d(this, "Exception happened when dump:" + e.getMessage()); } } }
34.471861
107
0.604986
76361845dedb0ccd56185aac21200ee34b6ba33f
2,601
package com.qa.ims.controller; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import com.qa.ims.persistence.domain.Customer; import com.qa.ims.services.CustomerServices; import com.qa.ims.utils.Utils; @RunWith(MockitoJUnitRunner.class) public class CustomerControllerTest { /** * The thing I want to fake functionlity for */ @Mock private CustomerServices customerServices; /** * Spy is used because i want to mock some methods inside the item I'm testing * InjectMocks uses dependency injection to insert the mock into the customer * controller */ @Spy // for the methods in customerController @InjectMocks // for any classes our customerController calls (in this case customerService) private CustomerController customerController; @Test public void readAllTest() { CustomerController customerController = new CustomerController(customerServices); List<Customer> customers = new ArrayList<>(); customers.add(new Customer("Chris", "P")); customers.add(new Customer("Rhys", "T")); customers.add(new Customer("Nic", "J")); Mockito.when(customerServices.readAll()).thenReturn(customers); assertEquals(customers, customerController.readAll()); } @Test public void createTest() { String firstName = "Chris"; String surname = "Perrins"; Mockito.doReturn(firstName, surname).when(customerController).getInput(); Customer customer = new Customer(firstName, surname); Customer savedCustomer = new Customer(1L, "Chris", "Perrins"); Mockito.when(customerServices.create(customer)).thenReturn(savedCustomer); assertEquals(savedCustomer, customerController.create()); } /** * */ @Test public void updateTest() { String id = "1"; String firstName = "Rhys"; String surname = "Thompson"; Mockito.doReturn(id, firstName, surname).when(customerController).getInput(); Customer customer = new Customer(1L, firstName, surname); Mockito.when(customerServices.update(customer)).thenReturn(customer); assertEquals(customer, customerController.update()); } /** * Delete doesn't return anything, so we can just verify that it calls the * delete method */ @Test public void deleteTest() { String id = "1"; Mockito.doReturn(id).when(customerController).getInput(); customerController.delete(); Mockito.verify(customerServices, Mockito.times(1)).delete(1L); } }
29.556818
92
0.75125
06549d2d564014c0f3ad68671a4b88f53e1cf954
2,022
package org.nextrtc.server.dao.provider; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.nextrtc.server.dao.Members; import org.nextrtc.server.domain.Member; import org.nextrtc.server.domain.provider.DefaultMember; import org.nextrtc.server.factory.MemberFactory; import org.nextrtc.server.factory.provider.DefaultMemberFactory; import com.google.common.base.Optional; public class InMemoryMembersTest { private Members container; private MemberFactory factory = new DefaultMemberFactory(); @Before public void setupContainer() { container = new InMemboryMembers(); } @Test public void shouldCreateMember() { // given // when Member newOne = factory.create(); // then assertNotNull(newOne); assertNotNull(newOne.getId()); } @Test public void shouldFindCreatedMember() { // given Member member = factory.create(); container.save(member); // when Optional<Member> found = container.findBy(member.getId()); // then assertTrue(found.isPresent()); assertThat(found.get(), is(member)); } @Test public void shouldRemoveMember() { // given Member member = factory.create(); container.save(member); // when container.remove(member); // then assertFalse(container.findBy(member.getId()).isPresent()); } @Test public void shouldUpdateMemberNick() { // given Member member = factory.create(); container.save(member); assertThat(member.getName(), isEmptyOrNullString()); // when container.update(new DefaultMember(member.getId(), "Stefan")); // then Optional<Member> found = container.findBy(member.getId()); assertTrue(found.isPresent()); assertThat(member.getId(), is(found.get().getId())); assertThat("Stefan", is(found.get().getName())); } }
22.977273
64
0.736894
9731944ce16dc044abefb8f02eecd87be6ac25e3
535
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.nokia.as.kafka.stest.producer; import org.osgi.framework.*; public class Activator implements BundleActivator { @Override public void start(BundleContext ctx) { System.out.println("Starting kafka avro producer"); try { KafkaEventProducer.main(new String[] { "10", "http://localhost:8081" }); } catch (Throwable t) { t.printStackTrace(); } } public void stop(BundleContext ctx) { } }
19.814815
75
0.706542
ef29609f989b0b3e9aed0c49f241925c2121a169
297
package p7.form_template_method2.org; public class MainProgram { public static void main(String[] args) { System.out.println("Before Refactoring:"); System.out.println("A: " + new SubClassA().compute(5, 10)); System.out.println("B: " + new SubClassA().compute(7, 4)); } }
29.7
65
0.656566
8b3e53f821362630a33dca4260fccbc8f52a3d87
3,632
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.drools.workbench.services.verifier.webworker.client.testutil; import java.util.Collection; import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint; import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52; import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52; import org.drools.workbench.models.guided.dtable.shared.model.LimitedEntryActionSetFieldCol52; import org.drools.workbench.models.guided.dtable.shared.model.LimitedEntryConditionCol52; import org.drools.workbench.models.guided.dtable.shared.model.Pattern52; import org.kie.soup.project.datamodel.imports.Import; import org.kie.soup.project.datamodel.oracle.DataType; public class LimitedGuidedDecisionTableBuilder extends AbstractDecisionTableBuilder { public LimitedGuidedDecisionTableBuilder(final String packageName, final Collection<Import> imports, final String tableName) { table.setPackageName(packageName); table.setTableFormat(GuidedDecisionTable52.TableFormat.LIMITED_ENTRY); table.getImports().getImports().addAll(imports); table.setTableName(tableName); } public LimitedGuidedDecisionTableBuilder withIntegerColumn(final String boundName, final String factType, final String field, final String operator, final int value) { final Pattern52 pattern = findPattern(boundName, factType); final LimitedEntryConditionCol52 condition = new LimitedEntryConditionCol52(); condition.setConstraintValueType(BaseSingleFieldConstraint.TYPE_LITERAL); condition.setFieldType(DataType.TYPE_NUMERIC_INTEGER); condition.setFactField(field); condition.setHeader("Some header"); condition.setOperator(operator); condition.setValue( new DTCellValue52() { { setNumericValue(new Integer(value)); } }); pattern.getChildColumns().add(condition); addPattern(pattern); return this; } public LimitedGuidedDecisionTableBuilder withAction(String boundName, String factField, String typeNumericInteger, DTCellValue52 value) { LimitedEntryActionSetFieldCol52 ins = new LimitedEntryActionSetFieldCol52(); ins.setBoundName(boundName); ins.setFactField(factField); ins.setValue(value); ins.setType(typeNumericInteger); table.getActionCols().add(ins); return this; } }
44.292683
94
0.636839
6b16e9d62794ad34b30e2afd1a3b9bd9dae0a097
2,631
package net.n2oapp.framework.autotest.impl.component.control; import com.codeborne.selenide.Condition; import com.codeborne.selenide.SelenideElement; import net.n2oapp.framework.autotest.api.component.control.NumberPicker; import org.openqa.selenium.Keys; /** * Компонент ввода числа из диапазона */ public class N2oNumberPicker extends N2oControl implements NumberPicker { @Override public void shouldBeEmpty() { inputElement().shouldBe(Condition.empty); } @Override public void val(String value) { inputElement().click(); inputElement().sendKeys(Keys.chord(Keys.CONTROL, "a"), value); // focus out inputElement().pressTab(); } @Override public void clear() { inputElement().click(); inputElement().sendKeys(Keys.chord(Keys.CONTROL, "a"), Keys.BACK_SPACE); // focus out inputElement().pressTab(); } @Override public void shouldHaveValue(String value) { inputElement().shouldHave(value == null || value.isEmpty() ? Condition.empty : Condition.value(value)); } @Override public void clickPlusStepButton() { plusButton().click(); } public void minusStepButtonShouldBeEnabled() { minusButton().parent().shouldBe(Condition.enabled); } public void minusStepButtonShouldBeDisabled() { minusButton().parent().shouldBe(Condition.disabled); } @Override public void clickMinusStepButton() { element().parent().$$(".n2o-number-picker__button .fa-minus").get(0).click(); } public void plusStepButtonShouldBeEnabled() { plusButton().parent().shouldBe(Condition.enabled); } public void plusStepButtonShouldBeDisabled() { plusButton().parent().shouldBe(Condition.disabled); } @Override public void minShouldBe(String val) { inputElement().shouldBe(Condition.attribute("min", val)); } @Override public void maxShouldBe(String val) { inputElement().shouldBe(Condition.attribute("max", val)); } @Override public void stepShouldBe(String val) { inputElement().shouldBe(Condition.attribute("step", val)); } private SelenideElement inputElement() { element().shouldBe(Condition.exist); return element().parent().$(".n2o-number-picker__input"); } private SelenideElement minusButton() { return element().parent().$(".n2o-number-picker__button .fa-minus"); } private SelenideElement plusButton() { return element().parent().$(".n2o-number-picker__button .fa-plus"); } }
27.989362
85
0.655644
51b10e5296ba0aa2c1197997bbe9742283675232
1,250
/* * Copyright (c) 2019. houbinbin Inc. * idoc All rights reserved. */ package com.github.houbb.idoc.common.util; import com.github.houbb.idoc.common.handler.IHandler; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 数组工具类 * @author binbin.hou * @since 0.0.1 */ public final class ArrayUtil { /** * 是否为空 * @param objects 数组 * @return 是否为空 */ public static boolean isEmpty(final Object[] objects) { return null == objects || objects.length == 0; } public static boolean isNotEmpty(final Object[] objects) { return !isEmpty(objects); } /** * 构建结果列表 * @param targets 原始信息 * @param handler 处理接口 * @param <T> 入参 * @param <R> 出参 * @return 结果 */ public static <T, R> List<R> buildList(final T[] targets, final IHandler<T, R> handler) { if(isEmpty(targets)) { return Collections.emptyList(); } List<R> rList = new ArrayList<>(targets.length); for(T t : targets) { R r = handler.handle(t); if(ObjectUtil.isNull(t)) { continue; } rList.add(r); } return rList; } }
21.551724
93
0.5544
87d6d4b54dc8546f8a4650e1f861affc44419918
371
package learning02.server.codec; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import lombok.extern.slf4j.Slf4j; /** * @author z201.coding@gmail.com * @date 11/21/21 **/ @Slf4j public class FrameDecoder extends LengthFieldBasedFrameDecoder { public FrameDecoder() { super(Integer.MAX_VALUE, 0, 2,0,2); log.info("running"); } }
20.611111
64
0.708895
5ba074f1b9f24f402b54778d23daf221902e6e2b
4,800
/* Copyright 2004-2005 Graeme Rocher * * 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.codehaus.groovy.grails.web.pages.ext.jsp; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import org.codehaus.groovy.grails.web.util.StreamCharBuffer; import java.io.*; /** * An implementation of BodyContent that uses an internal CharArrayWriter * * @author Graeme Rocher * @since 1.1 * * <p/> * Created: May 1, 2008 */ class BodyContentImpl extends BodyContent { static final char[] LINE_BREAK = System.getProperty("line.separator").toCharArray(); private StreamCharBuffer streamBuffer; private Writer streamBufferWriter; BodyContentImpl(JspWriter out, boolean buffer) { super(out); if (buffer) initBuffer(); } void initBuffer() { streamBuffer = new StreamCharBuffer(); streamBufferWriter = streamBuffer.getWriter(); } public void flush() throws IOException { if(streamBuffer == null) { getEnclosingWriter().flush(); } } public void clear() throws IOException { clearBuffer(); } public void clearBuffer() throws IOException { if(streamBuffer != null) { initBuffer(); } else { throw new IOException("Can't clear"); } } public int getRemaining() { return Integer.MAX_VALUE; } public void newLine() throws IOException { write(LINE_BREAK); } public void close() throws IOException { } public void print(boolean arg0) throws IOException { write(arg0 ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); } public void print(char arg0) throws IOException { write(arg0); } public void print(char[] arg0) throws IOException { write(arg0); } public void print(double arg0) throws IOException { write(Double.toString(arg0)); } public void print(float arg0) throws IOException { write(Float.toString(arg0)); } public void print(int arg0) throws IOException { write(Integer.toString(arg0)); } public void print(long arg0) throws IOException { write(Long.toString(arg0)); } public void print(Object arg0) throws IOException { write(arg0 == null ? "null" : arg0.toString()); } public void print(String arg0) throws IOException { write(arg0); } public void println() throws IOException { newLine(); } public void println(boolean arg0) throws IOException { print(arg0); newLine(); } public void println(char arg0) throws IOException { print(arg0); newLine(); } public void println(char[] arg0) throws IOException { print(arg0); newLine(); } public void println(double arg0) throws IOException { print(arg0); newLine(); } public void println(float arg0) throws IOException { print(arg0); newLine(); } public void println(int arg0) throws IOException { print(arg0); newLine(); } public void println(long arg0) throws IOException { print(arg0); newLine(); } public void println(Object arg0) throws IOException { print(arg0); newLine(); } public void println(String arg0) throws IOException { print(arg0); newLine(); } public void write(int c) throws IOException { if(streamBufferWriter != null) { streamBufferWriter.write(c); } else { getEnclosingWriter().write(c); } } public void write(char[] cbuf, int off, int len) throws IOException { if(streamBufferWriter != null) { streamBufferWriter.write(cbuf, off, len); } else { getEnclosingWriter().write(cbuf, off, len); } } public String getString() { return streamBuffer.toString(); } public Reader getReader() { return streamBuffer.getReader(); } public void writeOut(Writer out) throws IOException { streamBuffer.writeTo(out); } }
22.429907
88
0.611667
3f0f717148e98b4a564451a2028a9710f96bec66
1,967
package com.ababqq.buzzvil_test_android.utilities; import android.util.Log; import com.ababqq.buzzvil_test_android.models.AdBean; import com.ababqq.buzzvil_test_android.models.ArticleBean; import com.ababqq.buzzvil_test_android.models.CampaignBean; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class DataCollection { private static final String TAG = DataCollection.class.getSimpleName(); public static List<CampaignBean> shuffleCampaigns(List<CampaignBean> campaignList) { Collections.shuffle(campaignList); return new ArrayList<>(campaignList); } public static CampaignBean pickFirstCampaign(List<CampaignBean> list) { List<Integer> probabilityList = new ArrayList<>(); int highestPriority = Integer.MAX_VALUE; for (int i = 0; i < list.size(); i++) { if (highestPriority > list.get(i).firstDisplayPriority) highestPriority = list.get(i).firstDisplayPriority; } for (int campaignIndex = 0; campaignIndex < list.size(); campaignIndex++) { if (highestPriority == list.get(campaignIndex).firstDisplayPriority) { for (int weightObj = 0; weightObj < list.get(campaignIndex).firstDisplayWeight; weightObj++) probabilityList.add(campaignIndex); } } Random random = new Random(); random.setSeed(System.currentTimeMillis()); CampaignBean first = list.get(probabilityList.get(random.nextInt(probabilityList.size()))); if (first.getType().equals(AdBean.class.getSimpleName())) Log.e(TAG, first.id + " ads " + first.firstDisplayPriority + " " + first.firstDisplayWeight); else if (first.getType().equals(ArticleBean.class.getSimpleName())) Log.e(TAG, first.id + " article " + first.firstDisplayPriority + " " + first.firstDisplayWeight); return first; } }
40.142857
109
0.683782
465efe3febdd2b2f96bc8f874a4471c4ef562013
187
package com.cloudtemple.mattermost.traders.file; import com.cloudtemple.mattermost.traders.MmId; public class FileId extends MmId { public FileId(final String id) { super(id); } }
15.583333
48
0.764706
5794020210068742954575e6276881d50a2af967
1,950
package android.text.method; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public class MultiTapKeyListener extends BaseKeyListener implements android.text.SpanWatcher { // Constructors @com.francetelecom.rd.stubs.annotation.CallBackRegister("onCreate") public MultiTapKeyListener(TextKeyListener.Capitalize arg1, boolean arg2){ super(); } // Methods public static MultiTapKeyListener getInstance(boolean arg1, TextKeyListener.Capitalize arg2){ return (MultiTapKeyListener) null; } @com.francetelecom.rd.stubs.annotation.CallBack("onCreate") public boolean onKeyDown(android.view.View arg1, android.text.Editable arg2, int arg3, android.view.KeyEvent arg4){ return false; } public int getInputType(){ return 0; } @com.francetelecom.rd.stubs.annotation.CallBack("onCreate") public void onSpanAdded(android.text.Spannable arg1, java.lang.Object arg2, int arg3, int arg4){ } @com.francetelecom.rd.stubs.annotation.CallBack("onCreate") public void onSpanRemoved(android.text.Spannable arg1, java.lang.Object arg2, int arg3, int arg4){ } @com.francetelecom.rd.stubs.annotation.CallBack("onCreate") public void onSpanChanged(android.text.Spannable arg1, java.lang.Object arg2, int arg3, int arg4, int arg5, int arg6){ } }
33.62069
120
0.740513
6fe68430913c8b57409c36c571ae4eba12a67e14
653
package io.github.apace100.apoli.util; import net.minecraft.entity.attribute.EntityAttribute; import net.minecraft.entity.attribute.EntityAttributeModifier; public class AttributedEntityAttributeModifier { private final EntityAttribute attribute; private final EntityAttributeModifier modifier; public AttributedEntityAttributeModifier(EntityAttribute attribute, EntityAttributeModifier modifier) { this.attribute = attribute; this.modifier = modifier; } public EntityAttributeModifier getModifier() { return modifier; } public EntityAttribute getAttribute() { return attribute; } }
27.208333
107
0.761103
0fbdac86b19059ef2742e60ebb543b73aaaa0207
3,804
/* * Copyright (C) 2017 Piotr Wittchen * * 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.github.pwittchen.prefser.library.rx2; import android.content.SharedPreferences; import java.util.HashMap; import java.util.Map; class PreferencesAccessorsProvider implements AccessorsProvider { private final SharedPreferences preferences; private final SharedPreferences.Editor editor; private final Map<Class<?>, Accessor<?>> accessors = new HashMap<>(); PreferencesAccessorsProvider(SharedPreferences preferences, SharedPreferences.Editor editor) { Preconditions.checkNotNull(preferences, "preferences == null"); Preconditions.checkNotNull(editor, "editor == null"); this.preferences = preferences; this.editor = editor; createAccessors(); } @Override public Map<Class<?>, Accessor<?>> getAccessors() { return accessors; } private void createAccessors() { createBooleanAccessor(); createFloatAccessor(); createIntegerAccessor(); createLongAccessor(); createDoubleAccessor(); createStringAccessor(); } private void createBooleanAccessor() { accessors.put(Boolean.class, new Accessor<Boolean>() { @Override public Boolean get(String key, Boolean defaultValue) { return preferences.getBoolean(key, defaultValue); } @Override public void put(String key, Boolean value) { editor.putBoolean(key, value).apply(); } }); } private void createFloatAccessor() { accessors.put(Float.class, new Accessor<Float>() { @Override public Float get(String key, Float defaultValue) { return preferences.getFloat(key, defaultValue); } @Override public void put(String key, Float value) { editor.putFloat(key, value).apply(); } }); } private void createIntegerAccessor() { accessors.put(Integer.class, new Accessor<Integer>() { @Override public Integer get(String key, Integer defaultValue) { return preferences.getInt(key, defaultValue); } @Override public void put(String key, Integer value) { editor.putInt(key, value).apply(); } }); } private void createLongAccessor() { accessors.put(Long.class, new Accessor<Long>() { @Override public Long get(String key, Long defaultValue) { return preferences.getLong(key, defaultValue); } @Override public void put(String key, Long value) { editor.putLong(key, value).apply(); } }); } private void createDoubleAccessor() { accessors.put(Double.class, new Accessor<Double>() { @Override public Double get(String key, Double defaultValue) { return Double.valueOf(preferences.getString(key, String.valueOf(defaultValue))); } @Override public void put(String key, Double value) { editor.putString(key, String.valueOf(value)).apply(); } }); } private void createStringAccessor() { accessors.put(String.class, new Accessor<String>() { @Override public String get(String key, String defaultValue) { return preferences.getString(key, String.valueOf(defaultValue)); } @Override public void put(String key, String value) { editor.putString(key, String.valueOf(value)).apply(); } }); } }
31.7
96
0.688486
d35d1231bb0f1f4e9cbf0a682f2bb5a218272584
4,167
package ru.job4j.search; import org.apache.commons.cli.*; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.StringJoiner; import java.util.regex.Pattern; import java.util.stream.Stream; /** * @author Alexander Abramov (alllexe@mail.ru) * @version 1 * @since 16.05.2019 */ public class SearchFiles { private static final String PROJECT_NAME = "Search files"; public static void main(String[] args) { SearchFiles searchFiles = new SearchFiles(); searchFiles.init(args); } public void init(String[] args) { Options posixOptions = getOptions(); CommandLine commandLine = parseParams(args, posixOptions); if (commandLine != null) { String founded = search(commandLine); String fileNameOut = commandLine.getOptionValue("o"); try { Files.write(Paths.get(fileNameOut), founded.getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE); } catch (IOException e) { e.printStackTrace(); } } } private String search(CommandLine commandLine) { StringJoiner stringJoiner = new StringJoiner(System.lineSeparator()); String startDir = commandLine.getOptionValue("d"); Pattern filter = getFilter(commandLine); try { try (Stream<Path> paths = Files.walk(Paths.get(startDir))) { paths .filter(s -> filter.matcher(s.getFileName().toString()).find()) .map(s -> s.getFileName().toString()) .forEach(stringJoiner::add); } } catch (IOException e) { e.printStackTrace(); } return stringJoiner.toString(); } private Pattern getFilter(CommandLine commandLine) { String searchPattern = commandLine.getOptionValue("n"); Pattern pattern = null; if (commandLine.hasOption("m")) { pattern = Pattern.compile(WildCardToRegEx.convert(searchPattern)); } else if (commandLine.hasOption("r")) { pattern = Pattern.compile(searchPattern); } else if (commandLine.hasOption("f")) { pattern = Pattern.compile("^" + Pattern.quote(searchPattern) + "$"); } return pattern; } private Options getOptions() { Option optionDir = new Option("d", "dir", true, "start directory"); optionDir.setRequired(true); Option optionName = new Option("n", "name", true, "file name or mask or regexp"); optionName.setRequired(true); Option optionOut = new Option("o", "out", true, "file name to output search results"); optionName.setRequired(true); Option optionMask = new Option("m", "mask", false, "search by mask"); Option optionFull = new Option("f", "full name", false, "search by full name"); Option optionReg = new Option("r", "regexp", false, "search by regexp"); OptionGroup searchType = new OptionGroup() .addOption(optionMask) .addOption(optionFull) .addOption(optionReg); searchType.setRequired(true); return new Options() .addOption(optionDir) .addOption(optionName) .addOptionGroup(searchType) .addOption(optionOut); } private CommandLine parseParams(String[] commandLineArguments, Options posixOptions) { CommandLineParser cmdLinePosixParser = new PosixParser(); CommandLine commandLine = null; try { commandLine = cmdLinePosixParser.parse(posixOptions, commandLineArguments); } catch (ParseException e) { System.out.format("%s.%n", e.getMessage()); printHelp(posixOptions); } return commandLine; } public void printHelp(Options posixOptions) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(PROJECT_NAME, posixOptions); } }
33.336
123
0.612911
c548191d027dd72f67c094d148e2c378ea44212e
5,311
/************************************************************************** Exchange Web Services Java API Copyright (c) Microsoft Corporation All rights reserved. MIT License 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 microsoft.exchange.webservices.data; /** * Represents a request to a Find Conversation operation */ final class FindConversationRequest extends SimpleServiceRequestBase { private ConversationIndexedItemView view; private SearchFilter.IsEqualTo searchFilter; private FolderIdWrapper folderId; /** * @throws Exception */ protected FindConversationRequest(ExchangeService service) throws Exception { super(service); } /** * Gets or sets the view controlling the number of conversations returned. */ protected ConversationIndexedItemView getIndexedItemView() { return this.view; } protected void setIndexedItemView(ConversationIndexedItemView value) { this.view = value; } /** * Gets or sets the search filter. */ protected SearchFilter.IsEqualTo getConversationViewFilter() { return this.searchFilter; } protected void setConversationViewFilter(SearchFilter.IsEqualTo value) { this.searchFilter = value; } /** * Gets or sets folder id */ protected FolderIdWrapper getFolderId() { return this.folderId; } protected void setFolderId(FolderIdWrapper value) { this.folderId = value; } /** * Validate request. * * @throws Exception * @throws microsoft.exchange.webservices.data.ServiceLocalException */ @Override protected void validate() throws ServiceLocalException, Exception { super.validate(); this.view.internalValidate(this); } /** * Writes XML attributes. * * @param writer The writer. * @throws ServiceXmlSerializationException */ @Override protected void writeAttributesToXml(EwsServiceXmlWriter writer) throws ServiceXmlSerializationException { super.writeAttributesToXml(writer); } /** * Writes XML attributes. * * @param writer The writer. * @throws Exception */ @Override protected void writeElementsToXml(EwsServiceXmlWriter writer) throws Exception { this.getIndexedItemView().writeToXml(writer); if (this.getConversationViewFilter() != null) { writer.writeStartElement(XmlNamespace.Messages, XmlElementNames.Restriction); this.getConversationViewFilter().writeToXml(writer); writer.writeEndElement(); // Restriction } this.getIndexedItemView().writeOrderByToXml(writer); writer.writeStartElement(XmlNamespace.Messages, XmlElementNames.ParentFolderId); this.getFolderId().writeToXml(writer); writer.writeEndElement(); } /** * Parses the response. * * @param reader The reader. * @return Response object. * @throws Exception */ @Override protected Object parseResponse(EwsServiceXmlReader reader) throws Exception { FindConversationResponse response = new FindConversationResponse(); response.loadFromXml(reader, XmlElementNames.FindConversationResponse); return response; } /** * Gets the name of the XML element. * * @return XML element name. */ @Override protected String getXmlElementName() { return XmlElementNames.FindConversation; } /** * Gets the name of the response XML element. * * @return XML element name. */ @Override protected String getResponseXmlElementName() { return XmlElementNames.FindConversationResponse; } /** * Gets the request version. * * @return Earliest Exchange version in which this request is supported. */ @Override protected ExchangeVersion getMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2010_SP1; } /** * Executes this request. * * @return Service response. * @throws Exception * @throws microsoft.exchange.webservices.data.ServiceLocalException */ protected FindConversationResponse execute() throws ServiceLocalException, Exception { FindConversationResponse serviceResponse = (FindConversationResponse) this.internalExecute(); serviceResponse.throwIfNecessary(); return serviceResponse; } }
28.86413
461
0.710036
688d582072beabd22da9b05fd0c4b33276472e5f
403
package ua.dp.markos.onvif.discovery; import org.junit.jupiter.api.Test; import ua.dp.markos.onvif.model.OnvifDeviceInfo; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class IPCDiscoveryTest { @Test void testDiscovery() throws Exception { List<OnvifDeviceInfo> onvifDeviceInfos = IPCDiscovery.discovery(); assertNotNull(onvifDeviceInfos); } }
22.388889
74
0.744417
81720f897fee791caa052a1fce153ffe6f9ed1fa
4,438
/** * Copyright 2007-2013 Zuse Institute Berlin * * 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 de.zib.scalaris.examples.wikipedia.data; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * Represents a revision of a page. * * @author Nico Kruber, kruber@zib.de */ public class ShortRevision implements Serializable { /** * Version for serialisation. */ private static final long serialVersionUID = 1L; /** * the revision's ID */ protected int id; /** * the revision's date of creation */ protected String timestamp; /** * whether the change is a minor change or not */ protected boolean minor; /** * the revision's contributor */ protected Contributor contributor; /** * the comment of the revision */ protected String comment; /** * the size of the content (text) of the revision */ protected int size; /** * Creates an empty short revision. */ public ShortRevision() { this.id = 0; this.timestamp = ""; this.minor = false; this.contributor = new Contributor(); this.comment = ""; this.size = 0; } /** * Creates a new short revision from the given revision. * * @param revision * the revision to describe */ public ShortRevision(Revision revision) { this.id = revision.getId(); this.timestamp = revision.getTimestamp(); this.minor = revision.isMinor(); this.contributor = revision.getContributor(); this.comment = revision.getComment(); this.size = revision.unpackedText().length(); } /** * @return the id */ public int getId() { return id; } /** * @return the timestamp */ public String getTimestamp() { return timestamp; } /** * @return the contributor */ public Contributor getContributor() { return contributor; } /** * @return the comment */ public String getComment() { return comment; } /** * @return the size of the revision's text */ public int getSize() { return size; } /** * Gets whether the change is a minor change or not. * * @return <tt>true</tt> if the revision is a minor change, <tt>false</tt> * otherwise */ public boolean isMinor() { return minor; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @param timestamp the timestamp to set */ public void setTimestamp(String timestamp) { this.timestamp = timestamp; } /** * @param minor the minorChange to set */ public void setMinor(boolean minor) { this.minor = minor; } /** * @param contributor the contributor to set */ public void setContributor(Contributor contributor) { this.contributor = contributor; } /** * @param comment the comment to set */ public void setComment(String comment) { this.comment = comment; } /** * @param size the size to set */ public void setSize(int size) { this.size = size; } /** * Converts a list of {@link Revision} objects into a list of * {@link ShortRevision} objects. * * @param revisions * the revision list to convert * * @return a short revision list */ public static List<ShortRevision> fromRevisions(final List<Revision> revisions) { List<ShortRevision> result = new LinkedList<ShortRevision>(); for (Revision rev : revisions) { result.add(new ShortRevision(rev)); } return result; } }
22.876289
85
0.581343
35630943f2227eb02e9b062ac73676f030c46269
50,366
package mat.client.cqlworkspace; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.gwtbootstrap3.client.ui.Anchor; import org.gwtbootstrap3.client.ui.AnchorListItem; import org.gwtbootstrap3.client.ui.Badge; import org.gwtbootstrap3.client.ui.Label; import org.gwtbootstrap3.client.ui.ListBox; import org.gwtbootstrap3.client.ui.NavPills; import org.gwtbootstrap3.client.ui.PanelBody; import org.gwtbootstrap3.client.ui.PanelCollapse; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.constants.Pull; import org.gwtbootstrap3.client.ui.constants.Toggle; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.OptionElement; import com.google.gwt.dom.client.SelectElement; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.DoubleClickHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.SuggestOracle; import com.google.gwt.user.client.ui.SuggestOracle.Suggestion; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import mat.client.shared.CQLSuggestOracle; import mat.client.shared.MatContext; import mat.model.ComponentMeasureTabObject; import mat.model.clause.QDSAttributes; import mat.model.cql.CQLCode; import mat.model.cql.CQLDefinition; import mat.model.cql.CQLFunctions; import mat.model.cql.CQLIncludeLibrary; import mat.model.cql.CQLLibraryDataSetObject; import mat.model.cql.CQLParameter; import mat.model.cql.CQLQualityDataSetDTO; public class CQLLeftNavBarPanelView { private static final String CQL_LIBRARY_EDITOR_ANCHOR = "cqlLibraryEditor_Anchor"; private VerticalPanel rightHandNavPanel = new VerticalPanel(); private Map<String, String> defineNameMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); private Map<String, String> funcNameMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); private Map<String, String> includeLibraryNameMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); private HashMap<String, CQLDefinition> definitionMap = new HashMap<String, CQLDefinition>(); private HashMap<String, CQLFunctions> functionMap = new HashMap<String, CQLFunctions>(); private HashMap<String, CQLIncludeLibrary> includeLibraryMap = new HashMap<String, CQLIncludeLibrary>(); private Badge includesBadge = new Badge(); private Badge valueSetBadge = new Badge(); private Badge codesBadge = new Badge(); private Badge paramBadge = new Badge(); private Badge defineBadge = new Badge(); private Badge functionBadge = new Badge(); private Label includesLabel = new Label("Includes"); private Label valueSetLabel = new Label("Value Sets"); private Label codesLabel = new Label("Codes"); private Label paramLabel = new Label("Parameter"); private Label defineLabel = new Label("Definition"); private Label functionLibLabel = new Label("Function"); PanelCollapse paramCollapse = new PanelCollapse(); PanelCollapse defineCollapse = new PanelCollapse(); PanelCollapse functionCollapse = new PanelCollapse(); PanelCollapse includesCollapse = new PanelCollapse(); PanelCollapse codesCollapse = new PanelCollapse(); PanelCollapse valueSetCollapse = new PanelCollapse(); private AnchorListItem cqlLibraryEditorTab; private AnchorListItem appliedQDM; private AnchorListItem codesLibrary; private AnchorListItem generalInformation; private AnchorListItem includesLibrary; private AnchorListItem parameterLibrary; private AnchorListItem definitionLibrary; private AnchorListItem functionLibrary; private List<CQLIncludeLibrary> viewIncludeLibrarys = new ArrayList<CQLIncludeLibrary>(); private List<CQLParameter> viewParameterList = new ArrayList<CQLParameter>(); private List<CQLDefinition> viewDefinitions = new ArrayList<CQLDefinition>(); private List<CQLCode> codesList = new ArrayList<CQLCode>(); private List<CQLQualityDataSetDTO> appliedQdmTableList = new ArrayList<CQLQualityDataSetDTO>(); private List<CQLCode> appliedCodeTableList = new ArrayList<CQLCode>(); private List<CQLLibraryDataSetObject> includeLibraryList = new ArrayList<CQLLibraryDataSetObject>(); private List<CQLFunctions> viewFunctions = new ArrayList<CQLFunctions>(); private ListBox includesNameListbox = new ListBox(); private ListBox defineNameListBox = new ListBox(); private ListBox funcNameListBox = new ListBox(); private SuggestBox searchSuggestDefineTextBox; private SuggestBox searchSuggestIncludeTextBox; private SuggestBox searchSuggestFuncTextBox; private SuggestBox searchSuggestParamTextBox; private Map<String, String> parameterNameMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); private HashMap<String, CQLParameter> parameterMap = new HashMap<String, CQLParameter>(); private ListBox parameterNameListBox = new ListBox(); private Boolean isDoubleClick = false; private Boolean isNavBarClick = false; private Boolean isLoading = false; private String currentSelectedDefinitionObjId = null; private String currentSelectedParamerterObjId = null; private String currentSelectedFunctionObjId = null; private String currentSelectedFunctionArgumentObjId = null; private String currentSelectedFunctionArgumentName = null; private String currentSelectedIncLibraryObjId = null; private String currentSelectedValueSetObjId = null; private String currentSelectedCodesObjId = null; private List<QDSAttributes> availableQDSAttributeList; private Badge badge = new Badge(); private ListBox componentNameListBox = new ListBox(); private Label componentLabel = new Label("Components"); private PanelCollapse collapse = new PanelCollapse(); private SuggestBox searchAliasTextBox; private AnchorListItem anchor; private List<ComponentMeasureTabObject> componentObjectsList = new ArrayList<>(); private Map<String, ComponentMeasureTabObject> componentObjectsMap = new HashMap<String, ComponentMeasureTabObject>(); private Map<String, String> aliases = new HashMap<String,String>(); private PanelCollapse buildComponentCollapsablePanel() { collapse.clear(); collapse.setId("collapseComponent"); PanelBody componentCollapseBody = new PanelBody(); HorizontalPanel componentHP = new HorizontalPanel(); VerticalPanel rightVerticalPanel = new VerticalPanel(); rightVerticalPanel.setSpacing(10); rightVerticalPanel.getElement().setId("rhsVerticalPanel_VerticalPanelComponent"); rightVerticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); Label componentsLabel = new Label("Components"); Map<String, String> aliases = new HashMap<String,String>(); aliases.clear(); for(ComponentMeasureTabObject obj : componentObjectsList) { aliases.put(obj.getComponentId(), obj.getAlias()); } buildSearchAliasBox(); componentNameListBox.clear(); componentNameListBox.setWidth("180px"); componentNameListBox.setVisibleItemCount(10); componentNameListBox.getElement().setAttribute("id", "componentsListBox"); rightVerticalPanel.add(searchAliasTextBox); rightVerticalPanel.add(componentNameListBox); addSuggestHandler(searchAliasTextBox, componentNameListBox); addListBoxHandler(componentNameListBox, searchAliasTextBox); rightVerticalPanel.setCellHorizontalAlignment(componentsLabel, HasHorizontalAlignment.ALIGN_LEFT); componentHP.add(rightVerticalPanel); componentCollapseBody.add(componentHP); collapse.add(componentCollapseBody); return collapse; } private ClickHandler createClickHandler(SuggestBox suggestBox) { return new ClickHandler() { @Override public void onClick(ClickEvent event) { if ("Search".equals(suggestBox.getText())) { suggestBox.setText(""); } } }; } private void setBadgeNumber(int size, Badge badge) { if (size < 10) { badge.setText("0" + size); } else { badge.setText("" + size); } } private void buildComponentsTab() { this.anchor.setIcon(IconType.PENCIL); this.anchor.setTitle("Component"); this.anchor.setId("component_Anchor"); componentLabel.setStyleName("transparentLabel"); componentLabel.setId("componentsLabel_Label"); setBadgeNumber(0, badge); badge.setPull(Pull.RIGHT); badge.setMarginLeft(45); badge.setId("componentsBadge_Badge"); Anchor anchor = (Anchor) (this.anchor.getWidget(0)); anchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); anchor.addClickHandler(event -> { this.anchor.setDataToggle(Toggle.COLLAPSE); this.anchor.setHref("#collapseComponent"); }); anchor.add(componentLabel); anchor.add(badge); anchor.setDataParent("#navGroup"); this.anchor.add(collapse); } public VerticalPanel buildMeasureLibCQLView(){ collapse = buildComponentCollapsablePanel(); includesCollapse = createIncludesCollapsablePanel(); paramCollapse = createParameterCollapsablePanel(); defineCollapse = createDefineCollapsablePanel(); functionCollapse = createFunctionCollapsablePanel(); buildLeftHandNavBar(); return rightHandNavPanel; } private void buildLeftHandNavBar() { rightHandNavPanel.clear(); NavPills navPills = new NavPills(); navPills.setStacked(true); navPills.setWidth("200px"); generalInformation = new AnchorListItem(); anchor = new AnchorListItem(); includesLibrary = new AnchorListItem(); appliedQDM = new AnchorListItem(); codesLibrary = new AnchorListItem(); parameterLibrary = new AnchorListItem(); definitionLibrary = new AnchorListItem(); functionLibrary = new AnchorListItem(); cqlLibraryEditorTab = new AnchorListItem(); buildGeneralInfoTab(); buildComponentsTab(); buildIncludesTab(); buildValueSetsTab(); buildCodesTab(); buildParameterTab(); buildDefinitionsTab(); buildFunctionsTab(); buildCQLLibraryEditorTab(); navPills.add(generalInformation); navPills.add(anchor); navPills.add(includesLibrary); navPills.add(appliedQDM); navPills.add(codesLibrary); navPills.add(parameterLibrary); navPills.add(definitionLibrary); navPills.add(functionLibrary); navPills.add(cqlLibraryEditorTab); rightHandNavPanel.add(navPills); } private void buildGeneralInfoTab() { generalInformation.setIcon(IconType.INFO); generalInformation.setText("General Information"); generalInformation.setTitle("General Information"); generalInformation.setActive(true); generalInformation.setId("generatalInformation_Anchor"); } private void buildIncludesTab() { includesLibrary.setIcon(IconType.PENCIL); includesLibrary.setTitle("Includes"); includesBadge.setText("0" + viewIncludeLibrarys.size()); Anchor includesAnchor = (Anchor) (includesLibrary.getWidget(0)); includesAnchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); includesAnchor.addClickHandler(event -> { includesLibrary.setDataToggle(Toggle.COLLAPSE); includesLibrary.setHref("#collapseIncludes"); }); includesLabel.setStyleName("transparentLabel"); includesLabel.setId("includesLabel_Label"); includesAnchor.add(includesLabel); includesBadge.setPull(Pull.RIGHT); includesBadge.setMarginLeft(52); includesBadge.setId("includesBadge_Badge"); includesAnchor.add(includesBadge); includesAnchor.setDataParent("#navGroup"); includesLibrary.setId("includesLibrary_Anchor"); includesLibrary.add(includesCollapse); } private void buildValueSetsTab() { appliedQDM.setIcon(IconType.PENCIL); appliedQDM.setTitle("Value Sets"); valueSetBadge.setText("0" + appliedQdmTableList.size()); Anchor valueSetAnchor = (Anchor) (appliedQDM.getWidget(0)); valueSetAnchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); valueSetLabel.setStyleName("transparentLabel"); valueSetLabel.setId("valueSetLabel_Label"); valueSetAnchor.add(valueSetLabel); valueSetBadge.setPull(Pull.RIGHT); valueSetBadge.setMarginLeft(52); valueSetBadge.setId("valueSetBadge_Badge"); valueSetAnchor.add(valueSetBadge); valueSetAnchor.setDataParent("#navGroup"); } private void buildCodesTab() { codesLibrary.setIcon(IconType.PENCIL); codesLibrary.setTitle("Codes"); codesBadge.setText("0" + codesList.size()); Anchor codesAnchor = (Anchor) (codesLibrary.getWidget(0)); codesAnchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); codesLabel.setStyleName("transparentLabel"); codesLabel.setId("codesLabel_Label"); codesAnchor.add(codesLabel); codesBadge.setPull(Pull.RIGHT); codesBadge.setMarginLeft(52); codesBadge.setId("codesBadge_Badge"); codesAnchor.add(codesBadge); codesAnchor.setDataParent("#navGroup"); } private void buildParameterTab() { parameterLibrary.setIcon(IconType.PENCIL); parameterLibrary.setTitle("Parameter"); paramBadge.setText("" + viewParameterList.size()); Anchor paramAnchor = (Anchor) (parameterLibrary.getWidget(0)); paramAnchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); paramAnchor.addClickHandler(event -> { parameterLibrary.setDataToggle(Toggle.COLLAPSE); parameterLibrary.setHref("#collapseParameter"); }); paramLabel.setStyleName("transparentLabel"); paramLabel.setId("paramLabel_Label"); paramAnchor.add(paramLabel); paramBadge.setPull(Pull.RIGHT); paramBadge.setId("paramBadge_Badge"); paramAnchor.add(paramBadge); paramAnchor.setDataParent("#navGroup"); parameterLibrary.setId("parameterLibrary_Anchor"); parameterLibrary.add(paramCollapse); } private void buildDefinitionsTab() { definitionLibrary.setIcon(IconType.PENCIL); definitionLibrary.setTitle("Define"); definitionLibrary.setId("definitionLibrary_Anchor"); defineBadge.setText("" + viewDefinitions.size()); Anchor defineAnchor = (Anchor) (definitionLibrary.getWidget(0)); defineAnchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); defineAnchor.addClickHandler(event -> { definitionLibrary.setDataToggle(Toggle.COLLAPSE); definitionLibrary.setHref("#collapseDefine"); }); defineLabel.setStyleName("transparentLabel"); defineLabel.setId("defineLabel_Label"); defineAnchor.add(defineLabel); defineBadge.setPull(Pull.RIGHT); defineAnchor.add(defineBadge); defineBadge.setId("defineBadge_Badge"); defineAnchor.setDataParent("#navGroup"); definitionLibrary.add(defineCollapse); } private void buildFunctionsTab() { functionLibrary.setIcon(IconType.PENCIL); functionLibrary.setId("functionLibrary_Anchor"); functionLibrary.setTitle("Functions"); functionBadge.setText("" + viewFunctions.size()); Anchor funcAnchor = (Anchor) (functionLibrary.getWidget(0)); funcAnchor.addDoubleClickHandler(new DoubleClickHandler() { @Override public void onDoubleClick(DoubleClickEvent event) { event.stopPropagation(); } }); funcAnchor.addClickHandler(event -> { functionLibrary.setDataToggle(Toggle.COLLAPSE); functionLibrary.setHref("#collapseFunction"); }); functionLibLabel.setStyleName("transparentLabel"); functionLibLabel.setId("functionLibLabel_label"); funcAnchor.add(functionLibLabel); functionBadge.setPull(Pull.RIGHT); funcAnchor.add(functionBadge); functionBadge.setId("functionBadge_Badge"); funcAnchor.setDataParent("#navGroup"); functionLibrary.add(functionCollapse); } private void buildCQLLibraryEditorTab() { cqlLibraryEditorTab.setIcon(IconType.BOOK); cqlLibraryEditorTab.setText("CQL Library Editor"); cqlLibraryEditorTab.setTitle("CQL Library Editor"); cqlLibraryEditorTab.setId(CQL_LIBRARY_EDITOR_ANCHOR); } private PanelCollapse createIncludesCollapsablePanel() { includesCollapse.setId("collapseIncludes"); PanelBody includesCollapseBody = new PanelBody(); HorizontalPanel includesFP = new HorizontalPanel(); VerticalPanel rightVerticalPanel = new VerticalPanel(); rightVerticalPanel.setSpacing(10); rightVerticalPanel.getElement().setId("rhsVerticalPanel_VerticalPanelIncludes"); rightVerticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); Label includesLibraryLabel = new Label("Includes Library"); buildSearchSuggestIncludeBox(); includesNameListbox.clear(); includesNameListbox.setWidth("180px"); includesNameListbox.setVisibleItemCount(10); includesNameListbox.getElement().setAttribute("id", "includesListBox"); clearAndAddAliasNamesToListBox(); addSuggestHandler(searchSuggestIncludeTextBox, includesNameListbox); addListBoxHandler(includesNameListbox, searchSuggestIncludeTextBox); searchSuggestIncludeTextBox.getElement().setAttribute("id", "searchSuggestIncludesTextBox"); rightVerticalPanel.add(searchSuggestIncludeTextBox); searchSuggestIncludeTextBox.getElement().setId("searchSuggesIncludestTextBox_SuggestBox"); rightVerticalPanel.add(includesNameListbox); includesNameListbox.getElement().setId("includesNameListBox_ListBox"); rightVerticalPanel.setCellHorizontalAlignment(includesLibraryLabel, HasHorizontalAlignment.ALIGN_LEFT); includesFP.add(rightVerticalPanel); includesCollapseBody.add(includesFP); includesCollapse.add(includesCollapseBody); return includesCollapse; } private void buildSearchSuggestIncludeBox() { searchSuggestIncludeTextBox = new SuggestBox(getSuggestOracle(includeLibraryNameMap.values())); searchSuggestIncludeTextBox.setWidth("180px"); searchSuggestIncludeTextBox.setText("Search"); searchSuggestIncludeTextBox.setTitle("Search Included Alias"); searchSuggestIncludeTextBox.getElement().setId("searchTextBox_TextBoxIncludesLib"); searchSuggestIncludeTextBox.getValueBox().addClickHandler(createClickHandler(searchSuggestIncludeTextBox)); } private void buildSearchSuggestParamBox() { searchSuggestParamTextBox = new SuggestBox(getSuggestOracle(parameterNameMap.values())); searchSuggestParamTextBox.setWidth("180px"); searchSuggestParamTextBox.setText("Search"); searchSuggestParamTextBox.setTitle("Search Parameter"); searchSuggestParamTextBox.getElement().setId("searchTextBox_TextBoxParameterLib"); searchSuggestParamTextBox.getValueBox().addClickHandler(createClickHandler(searchSuggestParamTextBox)); } private PanelCollapse createParameterCollapsablePanel() { paramCollapse.setId("collapseParameter"); PanelBody parameterCollapseBody = new PanelBody(); HorizontalPanel parameterFP = new HorizontalPanel(); VerticalPanel rightVerticalPanel = new VerticalPanel(); rightVerticalPanel.setSpacing(10); rightVerticalPanel.getElement().setId("rhsVerticalPanel_VerticalPanelParam"); rightVerticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); Label paramLibraryLabel = new Label("Parameter Library"); buildSearchSuggestParamBox(); parameterNameListBox.clear(); parameterNameListBox.setWidth("180px"); parameterNameListBox.setVisibleItemCount(10); parameterNameListBox.getElement().setAttribute("id", "paramListBox"); clearAndAddParameterNamesToListBox(); addSuggestHandler(searchSuggestParamTextBox, parameterNameListBox); addListBoxHandler(parameterNameListBox, searchSuggestParamTextBox); searchSuggestParamTextBox.getElement().setAttribute("id", "searchSuggestTextBox"); rightVerticalPanel.add(searchSuggestParamTextBox); searchSuggestParamTextBox.getElement().setId("searchSuggestTextBox_SuggestBox"); rightVerticalPanel.add(parameterNameListBox); parameterNameListBox.getElement().setId("paramNameListBox_ListBox"); rightVerticalPanel.setCellHorizontalAlignment(paramLibraryLabel, HasHorizontalAlignment.ALIGN_LEFT); parameterFP.add(rightVerticalPanel); parameterCollapseBody.add(parameterFP); paramCollapse.add(parameterCollapseBody); return paramCollapse; } private PanelCollapse createDefineCollapsablePanel() { PanelCollapse defineCollapsePanel = new PanelCollapse(); defineCollapsePanel.setId("collapseDefine"); PanelBody defineCollapseBody = new PanelBody(); HorizontalPanel defineFP = new HorizontalPanel(); VerticalPanel rightVerticalPanel = new VerticalPanel(); rightVerticalPanel.setSpacing(10); rightVerticalPanel.getElement().setId("rhsVerticalPanel_VerticalPanelParam"); rightVerticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); Label defineLibraryLabel = new Label("Definition Library"); buildSearchSuggestDefineBox(); defineNameListBox.clear(); defineNameListBox.setWidth("180px"); defineNameListBox.setVisibleItemCount(10); defineNameListBox.getElement().setAttribute("id", "defineListBox"); clearAndAddDefinitionNamesToListBox(); addSuggestHandler(searchSuggestDefineTextBox, defineNameListBox); addListBoxHandler(defineNameListBox, searchSuggestDefineTextBox); searchSuggestDefineTextBox.getElement().setAttribute("id", "searchSuggestTextBox"); rightVerticalPanel.add(searchSuggestDefineTextBox); searchSuggestDefineTextBox.getElement().setId("searchSuggestTextBox_SuggestBox"); rightVerticalPanel.add(defineNameListBox); searchSuggestDefineTextBox.getElement().setId("DefineListBox_ListBox"); rightVerticalPanel.setCellHorizontalAlignment(defineLibraryLabel, HasHorizontalAlignment.ALIGN_LEFT); defineFP.add(rightVerticalPanel); defineCollapseBody.add(defineFP); defineCollapsePanel.add(defineCollapseBody); return defineCollapsePanel; } private void buildSearchAliasBox() { aliases.clear(); for(ComponentMeasureTabObject obj : componentObjectsList) { aliases.put(obj.getComponentId(), obj.getAlias()); } searchAliasTextBox = new SuggestBox(getSuggestOracle(aliases.values())); searchAliasTextBox.setWidth("180px"); searchAliasTextBox.setText("Search"); searchAliasTextBox.setTitle("Search Component Alias"); searchAliasTextBox.getElement().setId("searchSuggesComponentTextBox_SuggestBox"); searchAliasTextBox.getValueBox().addClickHandler(createClickHandler(searchAliasTextBox)); } private void buildSearchSuggestDefineBox() { searchSuggestDefineTextBox = new SuggestBox(getSuggestOracle(defineNameMap.values())); searchSuggestDefineTextBox.setWidth("180px"); searchSuggestDefineTextBox.setText("Search"); searchSuggestDefineTextBox.setTitle("Search Definition"); searchSuggestDefineTextBox.getElement().setId("searchSuggestDefineTextBox"); searchSuggestDefineTextBox.getValueBox().addClickHandler(createClickHandler(searchSuggestDefineTextBox)); } private void buildSearchSuggestFuncBox() { searchSuggestFuncTextBox = new SuggestBox(getSuggestOracle(funcNameMap.values())); searchSuggestFuncTextBox.setWidth("180px"); searchSuggestFuncTextBox.setText("Search"); searchSuggestFuncTextBox.setTitle("Search Function"); searchSuggestFuncTextBox.getElement().setId("searchTextBox_TextBoxFuncLib"); searchSuggestFuncTextBox.getValueBox().addClickHandler(createClickHandler(searchSuggestFuncTextBox)); } private PanelCollapse createFunctionCollapsablePanel() { PanelCollapse funcCollapsePanel = new PanelCollapse(); funcCollapsePanel.setId("collapseFunction"); PanelBody funcCollapseBody = new PanelBody(); HorizontalPanel funcFP = new HorizontalPanel(); VerticalPanel rightVerticalPanel = new VerticalPanel(); rightVerticalPanel.setSpacing(10); rightVerticalPanel.getElement().setId("rhsVerticalPanel_VerticalPanelFunc"); rightVerticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); Label functionLibraryLabel = new Label("Function Library"); buildSearchSuggestFuncBox(); funcNameListBox.clear(); funcNameListBox.setWidth("180px"); funcNameListBox.setVisibleItemCount(10); funcNameListBox.getElement().setAttribute("id", "funcListBox"); clearAndAddFunctionsNamesToListBox(); addSuggestHandler(searchSuggestFuncTextBox, funcNameListBox); addListBoxHandler(funcNameListBox, searchSuggestFuncTextBox); searchSuggestFuncTextBox.getElement().setAttribute("id", "searchSuggestTextBoxFunc"); rightVerticalPanel.add(searchSuggestFuncTextBox); rightVerticalPanel.add(funcNameListBox); rightVerticalPanel.setCellHorizontalAlignment(functionLibraryLabel, HasHorizontalAlignment.ALIGN_LEFT); funcFP.add(rightVerticalPanel); funcCollapseBody.add(funcFP); funcCollapsePanel.add(funcCollapseBody); return funcCollapsePanel; } private SuggestOracle getSuggestOracle(Collection<String> values) { return new CQLSuggestOracle(values); } public void clearAndAddAliasNamesToListBox() { if (includesNameListbox != null) { includesNameListbox.clear(); viewIncludeLibrarys = sortAliasList(viewIncludeLibrarys); for (CQLIncludeLibrary incl : viewIncludeLibrarys) { if(incl.getId() != null) { includesNameListbox.addItem(incl.getAliasName(), incl.getId()); } } SelectElement selectElement = SelectElement.as(includesNameListbox.getElement()); com.google.gwt.dom.client.NodeList<OptionElement> options = selectElement.getOptions(); for (int i = 0; i < options.getLength(); i++) { String title = options.getItem(i).getText(); OptionElement optionElement = options.getItem(i); optionElement.setTitle(title); } } } private List<CQLIncludeLibrary> sortAliasList(List<CQLIncludeLibrary> viewAliasList) { Collections.sort(viewAliasList, new Comparator<CQLIncludeLibrary>() { @Override public int compare(final CQLIncludeLibrary object1, final CQLIncludeLibrary object2) { return object1.getAliasName().compareToIgnoreCase(object2.getAliasName()); } }); return viewAliasList; } public void clearAndAddDefinitionNamesToListBox() { if (defineNameListBox != null) { defineNameListBox.clear(); viewDefinitions = sortDefinitionNames(viewDefinitions); for (CQLDefinition define : viewDefinitions) { defineNameListBox.addItem(define.getName(), define.getId()); } SelectElement selectElement = SelectElement.as(defineNameListBox.getElement()); com.google.gwt.dom.client.NodeList<OptionElement> options = selectElement.getOptions(); for (int i = 0; i < options.getLength(); i++) { String title = options.getItem(i).getText(); OptionElement optionElement = options.getItem(i); optionElement.setTitle(title); } } } private List<CQLDefinition> sortDefinitionNames(List<CQLDefinition> viewDef) { Collections.sort(viewDef, new Comparator<CQLDefinition>() { @Override public int compare(final CQLDefinition object1, final CQLDefinition object2) { return object1.getName().compareToIgnoreCase(object2.getName()); } }); return viewDef; } public void clearAndAddFunctionsNamesToListBox() { if (funcNameListBox != null) { funcNameListBox.clear(); // sort functions viewFunctions = sortFunctionNames(viewFunctions); for (CQLFunctions func : viewFunctions) { funcNameListBox.addItem(func.getName(), func.getId()); } SelectElement selectElement = SelectElement.as(funcNameListBox.getElement()); com.google.gwt.dom.client.NodeList<OptionElement> options = selectElement.getOptions(); for (int i = 0; i < options.getLength(); i++) { String title = options.getItem(i).getText(); OptionElement optionElement = options.getItem(i); optionElement.setTitle(title); } } } private List<CQLFunctions> sortFunctionNames(List<CQLFunctions> viewFunc) { Collections.sort(viewFunc, new Comparator<CQLFunctions>() { @Override public int compare(final CQLFunctions object1, final CQLFunctions object2) { return object1.getName().compareToIgnoreCase(object2.getName()); } }); return viewFunc; } public void clearAndAddParameterNamesToListBox() { if (parameterNameListBox != null) { parameterNameListBox.clear(); viewParameterList = sortParamList(viewParameterList); for (CQLParameter param : viewParameterList) { parameterNameListBox.addItem(param.getName(), param.getId()); } SelectElement selectElement = SelectElement.as(parameterNameListBox.getElement()); com.google.gwt.dom.client.NodeList<OptionElement> options = selectElement.getOptions(); for (int i = 0; i < options.getLength(); i++) { String title = options.getItem(i).getText(); OptionElement optionElement = options.getItem(i); optionElement.setTitle(title); } } } private List<CQLParameter> sortParamList(List<CQLParameter> viewParamList) { Collections.sort(viewParamList, new Comparator<CQLParameter>() { @Override public int compare(final CQLParameter object1, final CQLParameter object2) { return object1.getName().compareToIgnoreCase(object2.getName()); } }); return viewParamList; } private void addSuggestHandler(final SuggestBox suggestBox, final ListBox listBox) { suggestBox.addSelectionHandler(new SelectionHandler<Suggestion>() { @Override public void onSelection(SelectionEvent<Suggestion> event) { String selectedQDMName = event.getSelectedItem().getReplacementString(); for (int i = 0; i < listBox.getItemCount(); i++) { if (selectedQDMName.equals(listBox.getItemText(i))) { listBox.setItemSelected(i, true); listBox.setFocus(true); break; } } } }); } private void addListBoxHandler(final ListBox listBox, final SuggestBox suggestBox) { listBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { System.out.println("listbox change event:" + event.getAssociatedType().getName()); int selectedIndex = listBox.getSelectedIndex(); String selectedItem = listBox.getItemText(selectedIndex); suggestBox.setText(selectedItem); } }); } public void updateValueSetMap(List<CQLQualityDataSetDTO> appliedValueSetTableList) { if (getAppliedQdmTableList().size() < 10) { getValueSetBadge().setText("0" + appliedValueSetTableList.size()); } else { getValueSetBadge().setText("" + appliedValueSetTableList.size()); } } public void setCodeBadgeValue(List<CQLCode> appliedCodeTableList) { if (appliedCodeTableList.size() < 10) { getCodesBadge().setText("0" + appliedCodeTableList.size()); } else { getCodesBadge().setText("" + appliedCodeTableList.size()); } } public void updateParamMap() { getParameterMap().clear(); getParameterNameMap().clear(); for (CQLParameter parameter : getViewParameterList()) { getParameterNameMap().put(parameter.getId(), parameter.getName()); getParameterMap().put(parameter.getId(), parameter); } if (getViewParameterList().size() < 10) { getParamBadge().setText("0" + getViewParameterList().size()); } else { getParamBadge().setText("" + getViewParameterList().size()); } } public void updateDefineMap() { getDefinitionMap().clear(); getDefineNameMap().clear(); for (CQLDefinition define : getViewDefinitions()) { getDefineNameMap().put(define.getId(), define.getName()); getDefinitionMap().put(define.getId(), define); } if (getViewDefinitions().size() < 10) { getDefineBadge().setText("0" + getViewDefinitions().size()); } else { getDefineBadge().setText("" + getViewDefinitions().size()); } updateSuggestDefineOracle(); } public void updateFunctionMap() { functionMap.clear(); funcNameMap.clear(); for (CQLFunctions function : viewFunctions) { funcNameMap.put(function.getId(), function.getName()); functionMap.put(function.getId(), function); } if (viewFunctions.size() < 10) { functionBadge.setText("0" + viewFunctions.size()); } else { functionBadge.setText("" + viewFunctions.size()); } updateSuggestFuncOracle(); } public void udpateIncludeLibraryMap() { includeLibraryMap.clear(); includeLibraryNameMap.clear(); for (CQLIncludeLibrary incLibrary : viewIncludeLibrarys) { includeLibraryNameMap.put(incLibrary.getId(), incLibrary.getAliasName()); includeLibraryMap.put(incLibrary.getId(), incLibrary); } if (viewIncludeLibrarys.size() < 10) { includesBadge.setText("0" + viewIncludeLibrarys.size()); } else { includesBadge.setText("" + viewIncludeLibrarys.size()); } updateSuggestIncludeOracle(); } public void updateSuggestParamOracle() { if (searchSuggestParamTextBox != null) { CQLSuggestOracle suggestOracle = (CQLSuggestOracle) searchSuggestParamTextBox.getSuggestOracle(); suggestOracle.setData(parameterNameMap.values()); } } public void updateSuggestDefineOracle() { if (searchSuggestDefineTextBox != null) { CQLSuggestOracle suggestOracle = (CQLSuggestOracle) searchSuggestDefineTextBox.getSuggestOracle(); suggestOracle.setData(defineNameMap.values()); } } public void updateSuggestFuncOracle() { if (searchSuggestFuncTextBox != null) { CQLSuggestOracle suggestOracle = (CQLSuggestOracle) searchSuggestFuncTextBox.getSuggestOracle(); suggestOracle.setData(funcNameMap.values()); } } public void updateSuggestIncludeOracle() { CQLSuggestOracle suggestOracle = (CQLSuggestOracle) searchSuggestIncludeTextBox.getSuggestOracle(); suggestOracle.setData(includeLibraryNameMap.values()); } public Map<String, String> getDefineNameMap() { return defineNameMap; } public void setDefineNameMap(Map<String, String> defineNameMap) { this.defineNameMap = defineNameMap; } public Map<String, String> getFuncNameMap() { return funcNameMap; } public void setFuncNameMap(Map<String, String> funcNameMap) { this.funcNameMap = funcNameMap; } public Map<String, String> getIncludeLibraryNameMap() { return includeLibraryNameMap; } public void setIncludeLibraryNameMap(Map<String, String> includeLibraryNameMap) { this.includeLibraryNameMap = includeLibraryNameMap; } public HashMap<String, CQLDefinition> getDefinitionMap() { return definitionMap; } public void setDefinitionMap(HashMap<String, CQLDefinition> definitionMap) { this.definitionMap = definitionMap; } public HashMap<String, CQLFunctions> getFunctionMap() { return functionMap; } public void setFunctionMap(HashMap<String, CQLFunctions> functionMap) { this.functionMap = functionMap; } public AnchorListItem getComponentsTab() { return anchor; } public HashMap<String, CQLIncludeLibrary> getIncludeLibraryMap() { return includeLibraryMap; } public void setIncludeLibraryMap(HashMap<String, CQLIncludeLibrary> includeLibraryMap) { this.includeLibraryMap = includeLibraryMap; } public Map<String, String> getParameterNameMap() { return parameterNameMap; } public void setParameterNameMap(Map<String, String> parameterNameMap) { this.parameterNameMap = parameterNameMap; } public HashMap<String, CQLParameter> getParameterMap() { return parameterMap; } public void setParameterMap(HashMap<String, CQLParameter> parameterMap) { this.parameterMap = parameterMap; } public List<CQLIncludeLibrary> getViewIncludeLibrarys() { return viewIncludeLibrarys; } public void setViewIncludeLibrarys(List<CQLIncludeLibrary> viewIncludeLibrarys) { this.viewIncludeLibrarys = viewIncludeLibrarys; } public List<CQLParameter> getViewParameterList() { return viewParameterList; } public void setViewParameterList(List<CQLParameter> viewParameterList) { this.viewParameterList = viewParameterList; } public List<CQLDefinition> getViewDefinitions() { return viewDefinitions; } public void setViewDefinitions(List<CQLDefinition> viewDefinitions) { this.viewDefinitions = viewDefinitions; } public List<CQLFunctions> getViewFunctions() { return viewFunctions; } public void setViewFunctions(List<CQLFunctions> viewFunctions) { this.viewFunctions = viewFunctions; } public Badge getValueSetBadge() { return valueSetBadge; } public void setValueSetBadge(Badge valueSetBadge) { this.valueSetBadge = valueSetBadge; } public Badge getCodesBadge() { return codesBadge; } public void setCodesBadge(Badge codesBadge) { this.codesBadge = codesBadge; } public Badge getIncludesBadge() { return includesBadge; } public void setIncludesBadge(Badge includesBadge) { this.includesBadge = includesBadge; } public Badge getParamBadge() { return paramBadge; } public void setParamBadge(Badge paramBadge) { this.paramBadge = paramBadge; } public Badge getDefineBadge() { return defineBadge; } public void setDefineBadge(Badge defineBadge) { this.defineBadge = defineBadge; } public Badge getFunctionBadge() { return functionBadge; } public void setFunctionBadge(Badge functionBadge) { this.functionBadge = functionBadge; } public VerticalPanel getRightHandNavPanel() { return rightHandNavPanel; } public ListBox getIncludesNameListbox() { return includesNameListbox; } public void setIncludesNameListbox(ListBox includesNameListbox) { this.includesNameListbox = includesNameListbox; } public ListBox getDefineNameListBox() { return defineNameListBox; } public void setDefineNameListBox(ListBox defineNameListBox) { this.defineNameListBox = defineNameListBox; } public ListBox getFuncNameListBox() { return funcNameListBox; } public void setFuncNameListBox(ListBox funcNameListBox) { this.funcNameListBox = funcNameListBox; } public ListBox getParameterNameListBox() { return parameterNameListBox; } public void setParameterNameListBox(ListBox parameterNameListBox) { this.parameterNameListBox = parameterNameListBox; } public AnchorListItem getGeneralInformation() { return generalInformation; } public void setGeneralInformation(AnchorListItem generalInformation) { this.generalInformation = generalInformation; } public AnchorListItem getIncludesLibrary() { return includesLibrary; } public void setIncludesLibrary(AnchorListItem includesLibrary) { this.includesLibrary = includesLibrary; } public AnchorListItem getParameterLibrary() { return parameterLibrary; } public void setParameterLibrary(AnchorListItem parameterLibrary) { this.parameterLibrary = parameterLibrary; } public AnchorListItem getDefinitionLibrary() { return definitionLibrary; } public void setDefinitionLibrary(AnchorListItem definitionLibrary) { this.definitionLibrary = definitionLibrary; } public AnchorListItem getFunctionLibrary() { return functionLibrary; } public void setFunctionLibrary(AnchorListItem functionLibrary) { this.functionLibrary = functionLibrary; } public AnchorListItem getCQLLibraryEditorTab() { return cqlLibraryEditorTab; } public void setCQLLibraryEditorTab(AnchorListItem viewCQL) { this.cqlLibraryEditorTab = viewCQL; } public List<CQLQualityDataSetDTO> getAppliedQdmTableList() { return appliedQdmTableList; } public void setAppliedQdmTableList(List<CQLQualityDataSetDTO> appliedQdmTableList) { this.appliedQdmTableList = appliedQdmTableList; } public List<CQLLibraryDataSetObject> getIncludeLibraryList() { return includeLibraryList; } public void setIncludeLibraryList(List<CQLLibraryDataSetObject> includeLibraryList) { this.includeLibraryList = includeLibraryList; } public AnchorListItem getAppliedQDM() { return appliedQDM; } public void setAppliedQDM(AnchorListItem appliedQDM) { this.appliedQDM = appliedQDM; } public AnchorListItem getCodesLibrary() { return codesLibrary; } public void setCodesLibrary(AnchorListItem codesLibrary) { this.codesLibrary = codesLibrary; } public PanelCollapse getParamCollapse() { return paramCollapse; } public PanelCollapse getDefineCollapse() { return defineCollapse; } public PanelCollapse getFunctionCollapse() { return functionCollapse; } public PanelCollapse getIncludesCollapse() { return includesCollapse; } public SuggestBox getSearchSuggestDefineTextBox() { return searchSuggestDefineTextBox; } public void setSearchSuggestDefineTextBox(SuggestBox searchSuggestDefineTextBox) { this.searchSuggestDefineTextBox = searchSuggestDefineTextBox; } public SuggestBox getSearchSuggestIncludeTextBox() { return searchSuggestIncludeTextBox; } public void setSearchSuggestIncludeTextBox(SuggestBox searchSuggestIncludeTextBox) { this.searchSuggestIncludeTextBox = searchSuggestIncludeTextBox; } public SuggestBox getSearchSuggestFuncTextBox() { return searchSuggestFuncTextBox; } public void setSearchSuggestFuncTextBox(SuggestBox searchSuggestFuncTextBox) { this.searchSuggestFuncTextBox = searchSuggestFuncTextBox; } public SuggestBox getSearchSuggestParamTextBox() { return searchSuggestParamTextBox; } public void setSearchSuggestParamTextBox(SuggestBox searchSuggestParamTextBox) { this.searchSuggestParamTextBox = searchSuggestParamTextBox; } public String getCurrentSelectedDefinitionObjId() { return currentSelectedDefinitionObjId; } public void setCurrentSelectedDefinitionObjId(String currentSelectedDefinitionObjId) { this.currentSelectedDefinitionObjId = currentSelectedDefinitionObjId; } public String getCurrentSelectedParamerterObjId() { return currentSelectedParamerterObjId; } public void setCurrentSelectedParamerterObjId(String currentSelectedParamerterObjId) { this.currentSelectedParamerterObjId = currentSelectedParamerterObjId; } public void setIsDoubleClick(Boolean isDoubleClick) { this.isDoubleClick = isDoubleClick; } public Boolean isDoubleClick() { return isDoubleClick; } public void setIsNavBarClick(Boolean isNavBarClick) { this.isNavBarClick = isNavBarClick; } public Boolean isNavBarClick() { return isNavBarClick; } public String getOwnerName(CQLLibraryDataSetObject cqlLibrary) { StringBuilder owner = new StringBuilder(); owner = owner.append(cqlLibrary.getOwnerFirstName()).append(" ").append(cqlLibrary.getOwnerLastName()); return owner.toString(); } public String getCurrentSelectedFunctionObjId() { return currentSelectedFunctionObjId; } public void setCurrentSelectedFunctionObjId(String currentSelectedFunctionObjId) { this.currentSelectedFunctionObjId = currentSelectedFunctionObjId; } public String getCurrentSelectedFunctionArgumentObjId() { return currentSelectedFunctionArgumentObjId; } public void setCurrentSelectedFunctionArgumentObjId(String currentSelectedFunctionArgumentObjId) { this.currentSelectedFunctionArgumentObjId = currentSelectedFunctionArgumentObjId; } public String getCurrentSelectedFunctionArgumentName() { return currentSelectedFunctionArgumentName; } public void setCurrentSelectedFunctionArgumentName(String currentSelectedFunctionArgumentName) { this.currentSelectedFunctionArgumentName = currentSelectedFunctionArgumentName; } public String getCurrentSelectedIncLibraryObjId() { return currentSelectedIncLibraryObjId; } public void setCurrentSelectedIncLibraryObjId(String currentSelectedIncLibraryObjId) { this.currentSelectedIncLibraryObjId = currentSelectedIncLibraryObjId; } public List<String> getIncludedList(Map<String, CQLIncludeLibrary> includeMap) { List<String> list = new ArrayList<String>(); for (Map.Entry<String, CQLIncludeLibrary> entry : includeMap.entrySet()) { list.add(entry.getValue().getCqlLibraryId()); } return list; } public void setAvailableQDSAttributeList(List<QDSAttributes> result) { availableQDSAttributeList = result; } public List<QDSAttributes> getAvailableQDSAttributeList(){ return availableQDSAttributeList; } public void clearShotcutKeyList(){ MatContext.get().getParameters().clear(); MatContext.get().getDefinitions().clear(); MatContext.get().getFuncs().clear(); MatContext.get().getValuesets().clear(); MatContext.get().getIncludes().clear(); MatContext.get().getIncludedValueSetNames().clear(); MatContext.get().getIncludedCodeNames().clear(); MatContext.get().getIncludedParamNames().clear(); MatContext.get().getIncludedDefNames().clear(); MatContext.get().getIncludedFuncNames().clear(); } public void buildInfoPanel(Widget sourceWidget) { PopupPanel panel = new PopupPanel(); panel.setAutoHideEnabled(true); panel.setPopupPosition(sourceWidget.getAbsoluteLeft() + 40, sourceWidget.getAbsoluteTop() + 20); VerticalPanel dialogContents = new VerticalPanel(); dialogContents.getElement().setId("dialogContents_VerticalPanel"); panel.setWidget(dialogContents); HTML html1 = new HTML("Ctrl-Alt-a: attributes"); HTML html2 = new HTML("Ctrl-Alt-y: datatypes"); HTML html3 = new HTML("Ctrl-Alt-d: definitions"); HTML html4 = new HTML("Ctrl-Alt-f: functions"); HTML html5 = new HTML("Ctrl-Alt-k: keywords"); HTML html6 = new HTML("Ctrl-Alt-p: parameters"); HTML html7 = new HTML("Ctrl-Alt-t: timings"); HTML html8 = new HTML("Ctrl-Alt-u: units"); HTML html9 = new HTML("Ctrl-Alt-v: value sets & codes"); HTML html10 = new HTML("Ctrl-Space: all"); dialogContents.add(html1); dialogContents.add(html2); dialogContents.add(html3); dialogContents.add(html4); dialogContents.add(html5); dialogContents.add(html6); dialogContents.add(html7); dialogContents.add(html8); dialogContents.add(html9); dialogContents.add(html10); panel.show(); } public Boolean getIsLoading() { return isLoading; } public void setIsLoading(Boolean isLoading) { this.isLoading = isLoading; } public List<CQLCode> getCodesTableList() { return codesList; } public List<CQLCode> getAppliedCodeTableList() { return appliedCodeTableList; } public void setAppliedCodeTableList(List<CQLCode> appliedCodeTableList) { this.appliedCodeTableList = appliedCodeTableList; } public String getCurrentSelectedCodesObjId() { return currentSelectedCodesObjId; } public void setCurrentSelectedCodesObjId(String currentSelectedCodesObjId) { this.currentSelectedCodesObjId = currentSelectedCodesObjId; } public String getCurrentSelectedValueSetObjId() { return currentSelectedValueSetObjId; } public void setCurrentSelectedValueSetObjId(String currentSelectedValueSetObjId) { this.currentSelectedValueSetObjId = currentSelectedValueSetObjId; } public boolean checkForIncludedLibrariesQDMVersion(boolean isStandAloneCQLLibrary){ boolean isValid = true; if(!isStandAloneCQLLibrary && !MatContext.get().isDraftMeasure()) { return isValid; } if(isStandAloneCQLLibrary && !MatContext.get().isDraftLibrary()) { return isValid; } List<CQLIncludeLibrary> includedLibraryList = getViewIncludeLibrarys(); if(includedLibraryList.size()==0){ isValid = true; } else { for(CQLIncludeLibrary cqlIncludeLibrary : includedLibraryList){ if(cqlIncludeLibrary.getQdmVersion()==null){ continue; }else if(!cqlIncludeLibrary.getQdmVersion().equalsIgnoreCase(MatContext.get().getCurrentQDMVersion())){ isValid = false; break; } } } return isValid; } public ListBox getComponentsListBox() { return componentNameListBox; } public Map<String, ComponentMeasureTabObject> getComponentMap() { return componentObjectsMap; } public UIObject getComponentsCollapse() { return collapse; } public void updateComponentInformation(List<ComponentMeasureTabObject> componentMeasures) { componentObjectsList.clear(); componentObjectsMap.clear(); aliases.clear(); componentObjectsList.addAll(componentMeasures); if (componentNameListBox != null) { componentNameListBox.clear(); sortComponentsList(componentObjectsList); for (ComponentMeasureTabObject object : componentObjectsList) { componentObjectsMap.put(object.getComponentId(), object); componentNameListBox.addItem(object.getAlias(), object.getComponentId()); aliases.put(object.getComponentId(), object.getAlias()); } SelectElement selectElement = SelectElement.as(componentNameListBox.getElement()); com.google.gwt.dom.client.NodeList<OptionElement> options = selectElement.getOptions(); for (int i = 0; i < options.getLength(); i++) { String title = options.getItem(i).getText(); OptionElement optionElement = options.getItem(i); optionElement.setTitle(title); } } setBadgeNumber(componentObjectsList.size(), badge); updateComponentSearchBox(); } public void updateComponentSearchBox() { buildSearchAliasBox(); } private void sortComponentsList(List<ComponentMeasureTabObject> objectList) { Collections.sort(objectList, new Comparator<ComponentMeasureTabObject>() { @Override public int compare(final ComponentMeasureTabObject object1, final ComponentMeasureTabObject object2) { return (object1.getAlias()).compareToIgnoreCase(object2.getAlias()); } }); } public void reset() { getRightHandNavPanel().clear(); getViewIncludeLibrarys().clear(); getViewParameterList().clear(); getViewDefinitions().clear(); getViewFunctions().clear(); getViewIncludeLibrarys().clear(); getIncludesCollapse().clear(); getParamCollapse().clear(); getDefineCollapse().clear(); getFunctionCollapse().clear(); } public void resetSelectedObjects() { setCurrentSelectedDefinitionObjId(null); setCurrentSelectedParamerterObjId(null); setCurrentSelectedFunctionObjId(null); setCurrentSelectedFunctionArgumentObjId(null); setCurrentSelectedFunctionArgumentName(null); setCurrentSelectedIncLibraryObjId(null); } public void resetActiveAnchorLists() { getComponentsTab().setActive(false); getIncludesLibrary().setActive(false); getAppliedQDM().setActive(false); getCodesLibrary().setActive(false); getFunctionLibrary().setActive(false); getParameterLibrary().setActive(false); getDefinitionLibrary().setActive(false); getCQLLibraryEditorTab().setActive(false); } }
33.026885
119
0.781678
b9edb694adce3f2e8f93211508247022994bef0d
763
package eg.edu.alexu.csd.datastructure.stack; /** * IStack. * created on April 20, 2016 * @author Amr Hedny * */ public interface IStack { /** * @param index where we want to add * @param element which we want to add */ public void add(int index, Object element); /** * @return "Object" that you want to remove */ public Object pop(); /** * @return "Object" at the top */ public Object peek(); /** * @param element that we want to push */ public void push(Object element); /** * @return "boolean" tells you if this stack is empty or not */ public boolean isEmpty(); /** * @return "int" represents the size of stack */ public int size(); }
18.609756
64
0.568807
56759b603b817ce75b9dafe566a4f96ad680bec7
463
package net.eightlives.friendlyssl.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @Configuration public class SchedulerConfig { @Bean(name = "update-checker-scheduler") public ScheduledExecutorService scheduler() { return Executors.newSingleThreadScheduledExecutor(); } }
27.235294
60
0.803456
150055102b8ed35d27c00af78b09a3bd38c17f6f
10,055
package edu.stanford.math.plex4.autogen.homology; import java.util.Comparator; import java.util.Iterator; import java.util.Set; import edu.stanford.math.plex4.homology.barcodes.AnnotatedBarcodeCollection; import edu.stanford.math.plex4.homology.barcodes.BarcodeCollection; import edu.stanford.math.plex4.streams.interfaces.AbstractFilteredStream; import edu.stanford.math.primitivelib.autogen.formal_sum.BooleanSparseFormalSum; import edu.stanford.math.primitivelib.autogen.pair.ObjectObjectPair; import gnu.trove.THashMap; import gnu.trove.THashSet; /** * This class defines the functionality for a persistence algorithm with underlying * field type being boolean and underlying basis element type being U. * It acts as an intermediate layer between the interface AbstractPersistenceBasisAlgorithm * and the actual implementations of the persistent homology/cohomology algorithms. * * <p>boolean the underlying type of the coefficient field</p> * <p>U the underlying basis type</p> * * @author autogen * */ public abstract class BooleanPersistentHomology<U> extends BooleanPersistenceAlgorithm<U> { /** * This constructor initializes the object with a comparator on the basis type. * * @param basisComparator a comparator on the basis type U * @param minDimension the minimum dimension to compute * @param maxDimension the maximum dimension to compute */ public BooleanPersistentHomology(Comparator<U> basisComparator, int minDimension, int maxDimension) { super(basisComparator, minDimension, maxDimension); } @Override protected AnnotatedBarcodeCollection<Integer, BooleanSparseFormalSum<U>> computeAnnotatedIntervalsImpl(AbstractFilteredStream<U> stream) { return this.getAnnotatedIntervals(this.pHcol(stream), stream); } @Override protected BarcodeCollection<Integer> computeIntervalsImpl(AbstractFilteredStream<U> stream) { return this.getIntervals(this.pHcol(stream), stream); } /** * This function implements the pHcol algorithm described in the paper. It computes the decomposition * R = D * V, where D is the boundary matrix, R is reduced, and is invertible and upper triangular. * This function returns the pair (R, V). Note that in our implementation, we represent a matrix by * a hash map which maps a generating object to a formal sum which corresponds to a column in the matrix. * Note that this is simply a sparse representation of a linear transformation on a vector space with * free basis consisting of elements of type U. * * @param stream the filtered chain complex which provides elements in increasing filtration order * @return a ObjectObjectPair containing the matrices R and V */ private ObjectObjectPair<THashMap<U, BooleanSparseFormalSum<U>>, THashMap<U, BooleanSparseFormalSum<U>>> pHcol(AbstractFilteredStream<U> stream) { THashMap<U, BooleanSparseFormalSum<U>> R = new THashMap<U, BooleanSparseFormalSum<U>>(); THashMap<U, BooleanSparseFormalSum<U>> V = new THashMap<U, BooleanSparseFormalSum<U>>(); /** * This maps a simplex to the set of columns containing the key as its low value. */ THashMap<U, THashSet<U>> lowMap = new THashMap<U, THashSet<U>>(); for (U i : stream) { /* * Do not process simplices of higher dimension than maxDimension. */ if (stream.getDimension(i) < this.minDimension) { continue; } if (stream.getDimension(i) > this.maxDimension + 1) { continue; } // initialize V to be the identity matrix V.put(i, this.chainModule.createNewSum(i)); // form the column R[i] which equals the boundary of the current simplex. // store the column as a column in R R.put(i, chainModule.createNewSum(stream.getBoundaryCoefficients(i), stream.getBoundary(i))); // compute low_R(i) U low_R_i = this.low(R.get(i)); // if the boundary of i is empty, then continue to next iteration since there // is nothing to process if (low_R_i == null) { continue; } THashSet<U> matchingLowSimplices = lowMap.get(low_R_i); while (matchingLowSimplices != null && !matchingLowSimplices.isEmpty()) { Iterator<U> iterator = matchingLowSimplices.iterator(); /** * TODO: Is this the right thing to do??? * Ie. should the iterator.next go at the end of the loop? */ U j = iterator.next(); assert (R.get(j).getCoefficient(low_R_i) == true); boolean negative_c = R.get(i).getCoefficient(low_R_i); //R.put(i, chainModule.subtract(R.get(i), chainModule.multiply(c, R.get(j)))); //V.put(i, chainModule.subtract(V.get(i), chainModule.multiply(c, V.get(j)))); this.chainModule.accumulate(R.get(i), R.get(j), negative_c); this.chainModule.accumulate(V.get(i), V.get(j), negative_c); // remove old low_R(i) entry //lowMap.get(low_R_i).remove(i); // recompute low_R(i) low_R_i = this.low(R.get(i)); matchingLowSimplices = lowMap.get(low_R_i); } // store the low value in the map if (low_R_i != null) { if (!lowMap.containsKey(low_R_i)) { lowMap.put(low_R_i, new THashSet<U>()); } lowMap.get(low_R_i).add(i); } } // at this point we have computed the decomposition R = D * V // we return the pair (R, V) return new ObjectObjectPair<THashMap<U, BooleanSparseFormalSum<U>>, THashMap<U, BooleanSparseFormalSum<U>>>(R, V); } protected abstract AnnotatedBarcodeCollection<Integer, BooleanSparseFormalSum<U>> getAnnotatedIntervals(ObjectObjectPair<THashMap<U, BooleanSparseFormalSum<U>>, THashMap<U, BooleanSparseFormalSum<U>>> RV_pair, AbstractFilteredStream<U> stream); protected abstract BarcodeCollection<Integer> getIntervals(ObjectObjectPair<THashMap<U, BooleanSparseFormalSum<U>>, THashMap<U, BooleanSparseFormalSum<U>>> RV_pair, AbstractFilteredStream<U> stream); protected AnnotatedBarcodeCollection<Integer, BooleanSparseFormalSum<U>> getAnnotatedIntervals( ObjectObjectPair<THashMap<U, BooleanSparseFormalSum<U>>, THashMap<U, BooleanSparseFormalSum<U>>> RV_pair, AbstractFilteredStream<U> stream, boolean absolute) { AnnotatedBarcodeCollection<Integer, BooleanSparseFormalSum<U>> barcodeCollection = new AnnotatedBarcodeCollection<Integer, BooleanSparseFormalSum<U>>(); THashMap<U, BooleanSparseFormalSum<U>> R = RV_pair.getFirst(); THashMap<U, BooleanSparseFormalSum<U>> V = RV_pair.getSecond(); Set<U> births = new THashSet<U>(); for (U i: stream) { if (!R.containsKey(i)) { continue; } U low_R_i = this.low(R.get(i)); int dimension = stream.getDimension(i); if (low_R_i == null) { if (dimension <= this.maxDimension && dimension >= this.minDimension) { births.add(i); } } else { // simplex i kills low_R_i births.remove(low_R_i); births.remove(i); int start = stream.getFiltrationIndex(low_R_i); int end = stream.getFiltrationIndex(i); if (end > start) { if (absolute) { dimension = stream.getDimension(low_R_i); if (dimension < this.maxDimension && dimension >= this.minDimension) barcodeCollection.addInterval(stream.getDimension(low_R_i), start, end, R.get(i)); } else { dimension = stream.getDimension(i); if (dimension < this.maxDimension && dimension >= this.minDimension) barcodeCollection.addInterval(dimension, start, end, V.get(i)); } } } } // the elements in birth are the ones that are never killed // these correspond to semi-infinite intervals for (U i: births) { int dimension = stream.getDimension(i); if (dimension < this.maxDimension && dimension >= this.minDimension) { if (absolute) { barcodeCollection.addRightInfiniteInterval(stream.getDimension(i), stream.getFiltrationIndex(i), V.get(i)); } else { barcodeCollection.addLeftInfiniteInterval(stream.getDimension(i), stream.getFiltrationIndex(i), V.get(i)); } } } return barcodeCollection; } protected BarcodeCollection<Integer> getIntervals( ObjectObjectPair<THashMap<U, BooleanSparseFormalSum<U>>, THashMap<U, BooleanSparseFormalSum<U>>> RV_pair, AbstractFilteredStream<U> stream, boolean absolute) { BarcodeCollection<Integer> barcodeCollection = new BarcodeCollection<Integer>(); THashMap<U, BooleanSparseFormalSum<U>> R = RV_pair.getFirst(); Set<U> births = new THashSet<U>(); for (U i: stream) { if (!R.containsKey(i)) { continue; } U low_R_i = this.low(R.get(i)); int dimension = stream.getDimension(i); if (low_R_i == null) { if (dimension <= this.maxDimension && dimension >= this.minDimension) { births.add(i); } } else { // simplex i kills low_R_i births.remove(low_R_i); births.remove(i); int start = stream.getFiltrationIndex(low_R_i); int end = stream.getFiltrationIndex(i); if (end > start) { if (absolute) { dimension = stream.getDimension(low_R_i); if (dimension < this.maxDimension && dimension >= this.minDimension) barcodeCollection.addInterval(stream.getDimension(low_R_i), start, end); } else { dimension = stream.getDimension(i); if (dimension < this.maxDimension && dimension >= this.minDimension) barcodeCollection.addInterval(dimension, start, end); } } } } // the elements in birth are the ones that are never killed // these correspond to semi-infinite intervals for (U i: births) { int dimension = stream.getDimension(i); if (dimension < this.maxDimension && dimension >= this.minDimension) { if (absolute) { barcodeCollection.addRightInfiniteInterval(stream.getDimension(i), stream.getFiltrationIndex(i)); } else { barcodeCollection.addLeftInfiniteInterval(stream.getDimension(i), stream.getFiltrationIndex(i)); } } } return barcodeCollection; } }
37.518657
163
0.695276
a4d7b8b510b6cc2feb7e8d6ba27a0ee0328dc949
3,954
/* * MIT License * * Copyright (c) 2021 Azortis * * 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 com.azortis.orbis.biomedemo; import com.azortis.orbis.biomedemo.objects.Biome; import com.azortis.orbis.biomedemo.objects.Dimension; import com.azortis.orbis.biomedemo.objects.Region; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class Registry { private static final Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); private static final Map<String, Dimension> dimensionMap = new HashMap<>(); private static final Map<String, Region> regionMap = new HashMap<>(); private static final Map<String, Biome> biomeMap = new HashMap<>(); private static final Map<Integer, Biome> biomeIdMap = new HashMap<>(); private Registry(){} public static void initialize(){ File rootDirectory = new File(System.getProperty("user.dir")); File dimensionDirectory = new File(rootDirectory, "/dimensions/"); for (File dimensionFile : Objects.requireNonNull(dimensionDirectory.listFiles())) { try{ Dimension dimension = gson.fromJson(new FileReader(dimensionFile), Dimension.class); dimensionMap.put(dimension.getName(), dimension); }catch (FileNotFoundException ex){ ex.printStackTrace(); } } File regionsDirectory = new File(rootDirectory, "/regions/"); for (File regionFile : Objects.requireNonNull(regionsDirectory.listFiles())) { try{ Region region = gson.fromJson(new FileReader(regionFile), Region.class); regionMap.put(region.getName(), region); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } File biomesDirectory = new File(rootDirectory, "/biomes/"); for (File biomeFile : Objects.requireNonNull(biomesDirectory.listFiles())) { try{ Biome biome = gson.fromJson(new FileReader(biomeFile), Biome.class); biomeMap.put(biome.getName(), biome); biomeIdMap.put(biome.getId(), biome); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } } @NotNull public static Dimension getDimension(String name){ return dimensionMap.get(name); } @NotNull public static Region getRegion(String name){ return regionMap.get(name); } @NotNull public static Biome getBiome(String name){ return biomeMap.get(name); } @NotNull public static Biome getBiome(int id){ return biomeIdMap.get(id); } }
37.657143
106
0.68083
527a9c76ecf3af0564de403a8d1f8b13aeca3ae6
3,407
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gr.spinellis.ckjm; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Siti Nur Fatihah Fauzi */ public class CompileFile { public static List<String> getFolder(String path){ File file = new File(path); File[] array = file.listFiles(); List<String> folderPathList=new ArrayList<String>(); for(int i =0;i < array.length;i++){ if(array[i].isDirectory()){ String folderPath = array[i].getPath(); folderPathList.add(folderPath); } } return folderPathList; } public boolean mkDirectory(String path){ File file = null; try{ file = new File(path); if(!file.exists()){ return file.mkdirs(); } else{ return false; } }catch(Exception e){ }finally{ file = null; } return false; } public void mkLog(){ String mkDirectoryPath = "D:\\realDemo\\log"; CloneRes cr = new CloneRes(); if(cr.mkDirectory(mkDirectoryPath)){ System.out.println(mkDirectoryPath+" The Direcory have benn sucessfully created"); } else{ System.out.println(mkDirectoryPath+" The Directory created failed!The Directory have been already existed"); } } public static void CompileProgram(String path) throws InterruptedException{ try { // System.out.println("--"+path); System.out.println("========================="); String matricNum = path.substring(12, 18); //D:\realDemo\[249879]-STIW3054-A191-A1\ String Command = "cmd /c cd "+path+"&& mvn compile > D:\\realDemo\\log\\"+matricNum+".log.txt"; Process a = Runtime.getRuntime().exec(Command); a.waitFor(); a.destroy(); } catch (IOException ex) { ex.printStackTrace(); Logger.getLogger(CompileFile.class.getName()).log(Level.SEVERE, null, ex); } } public void compile()throws InterruptedException{ //main!!! String path = "D:\\realDemo"; List<String> pomPathList=new ArrayList<String>(); for(int i =0;i < getFolder(path).size();i++){ String folderPath = getFolder(path).get(i); FileFinder ff = new FileFinder(); ff.pomPath(folderPath); if(!"".equals(ff.pomPath(folderPath))){ int begin=ff.pomPath(folderPath).indexOf("D:"); int last=ff.pomPath(folderPath).indexOf("\\pom"); pomPathList.add(ff.pomPath(folderPath).substring(begin,last)); }else{ System.out.println("Please "+folderPath.substring(12,18)+" upload the full file"); } } mkLog(); for(int i = 0;i < pomPathList.size();i++){ CompileProgram(pomPathList.get(i)); } } }
35.123711
121
0.540652
f0b20bb8ad81fa89e942904a3840da85bfb24007
1,626
package com.kevintweber.kimpachi.board; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; class GroupsTest { @Test void associateNothing() { List<Group> groupList = Groups.associate(Set.of()); assertThat(groupList) .as("Checking empty group list.") .isEmpty(); } @Test void intersection() { Group group = Group.of(Set.of(Point.of(5, 5), Point.of(5, 6))); Group otherGroup = Group.of(Set.of(Point.of(5, 5), Point.of(5, 4))); List<Group> intersection = Groups.intersection(group, otherGroup); assertThat(intersection.size()) .as("Checking the number of intersecting groups.") .isEqualTo(1); assertThat(intersection.get(0).getPoints()) .as("Checking intersecting points.") .containsExactly(Point.of(5, 5)); } @Test void union() { Group group = Group.of(Set.of(Point.of(5, 5), Point.of(5, 6))); Group otherGroup = Group.of(Set.of(Point.of(5, 5), Point.of(5, 4))); List<Group> union = Groups.union(group, otherGroup); assertThat(union.size()) .as("Checking the number of union groups.") .isEqualTo(1); assertThat(union.get(0).getPoints()) .as("Checking union group points") .containsExactlyInAnyOrder( Point.of(5, 5), Point.of(5, 6), Point.of(5, 4) ); } }
32.52
76
0.552891
d2f707ab3e8c7cc8cbdf1979a697e6eb18514e3d
98
package com.android.gl2jni; /** * Created by julian on 02/07/15. */ public @interface Keep { }
12.25
33
0.663265
ea26341d2c16957da00947d9a81a22602fbe8ca7
150
package com.laolang.notespring.aopone; public interface ForumService { void removeTopic( int topicId ); void removeForum( int forumId ); }
16.666667
38
0.733333
8eac9a8d46457e8d9ed271ebcf645546ff280fe8
2,383
package aperture.config; import aperture.filter.JWTAuthenticationFilter; import aperture.filter.JWTLoginFilter; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers( "/*", "/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**" ); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests() //Allow all routes except supervisor .antMatchers("/api/greetings").permitAll() .antMatchers("/api/rooms").permitAll() .antMatchers("/api/subjects").permitAll() // Login route .antMatchers(HttpMethod.POST, "/api/login").permitAll().anyRequest().authenticated() .and() // We filter the api/login requests .addFilterBefore(new JWTLoginFilter("/api/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class) // And filter other requests to check the presence of JWT in header .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // Create a default account auth.inMemoryAuthentication() .withUser("admin") .password("password") .roles("ADMIN"); } }
40.389831
107
0.695762
80844bb838c27b0dd8df86ecf21c734daa66e46b
1,567
package com.sid.leetcode.problem.puzzle; /** * 52. N-Queens II. * * <blockquote> * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens atack each other. * <p><img src="https://assets.leetcode.com/uploads/2018/10/12/8-queens.png"/> * <p>Given an integer n, return the number of distinct solutions to the n-queens puzzle. * * <p> * <b>Example:</b> * <blockquote> * <b>Input:</b> 4 * <p><b>Output:</b> 2 * <b>Explanation:</b> There are two distinct solutions to the 4-queens puzzle as shown below. * <p>[ * <pre>[ ".Q..", * <p> "...Q", * <p> "Q...", * <p> "..Q."], * <p>[ "..Q.", * <p> "Q...", * <p> "...Q", * <p> ".Q.."] * </pre> * <p>] * </blockquote> * </blockquote> * * @author Sid.Chen * @version 1.0, 2019-07-23 * */ public class NQueensII { int count = 0; public int totalNQueens(final int n) { count = 0; boolean[] cols = new boolean[n]; boolean[] d1 = new boolean[2 * n]; boolean[] d2 = new boolean[2 * n]; backtracking(0, cols, d1, d2, n); return count; } private void backtracking(final int row, final boolean[] cols, final boolean[] d1, final boolean[] d2, final int n) { if (row == n) count++; for (int col = 0; col < n; col++) { int id1 = col - row + n; int id2 = col + row; if (cols[col] || d1[id1] || d2[id2]) continue; cols[col] = true; d1[id1] = true; d2[id2] = true; backtracking(row + 1, cols, d1, d2, n); cols[col] = false; d1[id1] = false; d2[id2] = false; } } }
22.710145
120
0.553287
ad964406ff71447c0b976f9ea35b4004073f909f
1,655
package se.natusoft.osgi.aps.api.messaging; import se.natusoft.docutations.Optional; import se.natusoft.osgi.aps.exceptions.APSValidationException; import java.util.Map; /** * This represents a common base for all messages. aps-core-lib provides an implementation of this. * * A message structure will as a minimum look like this: * * { * aps: { * type: "type" // Identifies what is in the message under 'content'. * version: n.n, // The version of the message. For forwards/backwards compatibility. * }, * content: { * ... * } * } */ public interface APSBaseMessage extends Map<String, Object> { /** * Validates the content of the message. */ void validate() throws APSValidationException; /** * @return the 'aps.version' value. */ float getApsVersion(); /** * Sets the 'aps.version' value. * * @param version The version value to set. */ void setApsVersion(float version); /** * @return The 'aps.from' value. */ @Optional String getApsFrom(); /** * Sets the 'aps.from' value. * * @param from The from value to set. */ @Optional void setApsFrom(String from); /** * @return the 'aps.type' id. */ String getApsType(); /** * Sets the 'aps.type' id * * @param type The type to set. */ void setApsType(String type); /** * @return the 'aps' object. */ Map<String, Object> getAps(); /** * @return the 'content' object. */ Map<String, Object> getContent(); }
21.217949
99
0.566163
6524c687361b1f207ce7c6f578c55fd134e28d4c
4,510
package com.ojcoleman.ahni.experiments; import org.apache.log4j.Logger; import com.anji_ahni.integration.ActivatorTranscriber; import com.ojcoleman.ahni.evaluation.HyperNEATTargetFitnessFunction; import com.ojcoleman.ahni.hyperneat.Properties; import com.ojcoleman.ahni.transcriber.HyperNEATTranscriber; /** * A test fitness function that determines fitness based on how close the output of a network is to a target output * given some input. The specific test set can be specified with the property key "fitness.function.test.type". Valid * values are: * <ul> * <li>pass-through: the output should match the input.</li> * <li>pass-through-flip: same as pass-through except the target output is a mirror of the input.</li> * <li>rotate90: the target output is the input rotated 90 degrees.</li> * <li>parity: bitwise parity over all inputs.</li> * <li>[More to come!]</li> * </ul> * The number of trials is determined by the width and height of the input layer as 2 ^ (width + height), thus every * possible input pattern is tested. See {@link HyperNEATTargetFitnessFunction} for other available parameters that may * be specified via the properties file. * * @author Oliver Coleman */ public class TestTargetFitnessFunction extends HyperNEATTargetFitnessFunction { private static final long serialVersionUID = 1L; public static final String TEST_TYPE_KEY = "fitness.function.test.type"; private static Logger logger = Logger.getLogger(TestTargetFitnessFunction.class); private int numTrials; String testType; public TestTargetFitnessFunction() { } public void init(Properties props) { super.init(props); testType = props.getProperty(TEST_TYPE_KEY); if (testType.equals("pass-through") || testType.equals("pass-through-flip") || testType.equals("rotate90")) { if (inputWidth != outputWidth || inputHeight != outputHeight) { throw new IllegalArgumentException("HyperNEAT substrate input and output dimensions must be the same for TestTargetFitnessFunction."); } } if (testType.equals("rotate90") && inputWidth != inputHeight) { throw new IllegalArgumentException("HyperNEAT substrate input (and output) width and height must be the same for the rotate90 test in TestTargetFitnessFunction."); } else if (testType.equals("parity") && (outputWidth != 1 || outputHeight != 1)) { throw new IllegalArgumentException("HyperNEAT substrate output width and height must be 1 for the parity test in TestTargetFitnessFunction."); } numTrials = 1 << (inputWidth * inputHeight); logger.info("Target fitness function generating " + numTrials + " trials (if this number seems too large use an input layer with smaller dimensions)."); generatePatterns(); } @Override protected void scale(int scaleCount, int scaleFactor, HyperNEATTranscriber transcriber) { int[] width = transcriber.getWidth(); int[] height = transcriber.getHeight(); int connectionRange = transcriber.getConnectionRange(); for (int l = 0; l < width.length; l++) { width[l] *= scaleFactor; height[l] *= scaleFactor; } if (connectionRange != -1) { connectionRange *= scaleFactor; } transcriber.resize(width, height, connectionRange); generatePatterns(); } private void generatePatterns() { int[] width = HyperNEATTranscriber.getProvisionalLayerSize(props, HyperNEATTranscriber.SUBSTRATE_WIDTH); int[] height = HyperNEATTranscriber.getProvisionalLayerSize(props, HyperNEATTranscriber.SUBSTRATE_HEIGHT); int depth = width.length; double[][][] inputPatterns = new double[numTrials][height[0]][width[0]]; double[][][] targetOutputPatterns = new double[numTrials][height[depth - 1]][width[depth - 1]]; for (int t = 0; t < numTrials; t++) { int p = t; for (int y = 0; y < height[0]; y++) { for (int x = 0; x < width[0]; x++, p >>= 1) { inputPatterns[t][y][x] = p & 0x1; if (testType.equals("pass-through")) { targetOutputPatterns[t][y][x] = inputPatterns[t][y][x]; } else if (testType.equals("pass-through-flip")) { targetOutputPatterns[t][y][(width[0] - 1) - x] = inputPatterns[t][y][x]; } else if (testType.equals("rotate90")) { targetOutputPatterns[t][x][(height[0] - 1) - y] = inputPatterns[t][y][x]; } } } if (testType.equals("parity")) { int parity = t & 0x1; for (int i = 1; i < 31; i++) { parity ^= (t >> i) & 0x1; } targetOutputPatterns[t][0][0] = parity; } } setPatterns(inputPatterns, targetOutputPatterns, 0, 1); } }
38.220339
166
0.706652
337282a47eb8740a6f423dcae2650eef20d22592
391
package br.com.zupacademy.mateuschacon.mercadolivre.ProductResource.Repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import br.com.zupacademy.mateuschacon.mercadolivre.ProductResource.Models.ProductOpinion; @Repository public interface ProductOpinionRepository extends CrudRepository<ProductOpinion, String>{ }
32.583333
89
0.861893
6e97309f35f09a6ca80c3d4f132261fde7ef75bb
3,216
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.ldap.client; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import java.util.Properties; import eu.unicore.util.configuration.ConfigurationException; import pl.edu.icm.unity.engine.api.PKIManagement; import pl.edu.icm.unity.engine.api.authn.remote.AbstractRemoteVerificator; import pl.edu.icm.unity.engine.api.authn.remote.RemoteAuthnResponseProcessor; import pl.edu.icm.unity.engine.api.authn.remote.RemoteAuthnResultTranslator; import pl.edu.icm.unity.exceptions.InternalException; import pl.edu.icm.unity.ldap.client.config.LdapClientConfiguration; import pl.edu.icm.unity.ldap.client.config.LdapProperties; import pl.edu.icm.unity.types.I18nString; import pl.edu.icm.unity.types.authn.IdPInfo; import pl.edu.icm.unity.types.translation.TranslationProfile; import pl.edu.icm.unity.webui.authn.CommonWebAuthnProperties; /** * Base for LDAP verificators, responsible for handling configuration (common for both pass and cert verificators). */ public abstract class LdapBaseVerificator extends AbstractRemoteVerificator { protected final LdapClient client; private final PKIManagement pkiManagement; protected final RemoteAuthnResponseProcessor remoteAuthnProcessor; private LdapProperties ldapProperties; protected LdapClientConfiguration clientConfiguration; protected TranslationProfile translationProfile; protected LdapBaseVerificator(String name, String description, RemoteAuthnResultTranslator processor, PKIManagement pkiManagement, String exchangeId, RemoteAuthnResponseProcessor remoteAuthnProcessor) { super(name, description, exchangeId, processor); this.remoteAuthnProcessor = remoteAuthnProcessor; this.client = new LdapClient(name); this.pkiManagement = pkiManagement; } @Override public String getSerializedConfiguration() { StringWriter sbw = new StringWriter(); try { ldapProperties.getProperties().store(sbw, ""); } catch (IOException e) { throw new InternalException("Can't serialize LDAP verificator configuration", e); } return sbw.toString(); } @Override public void setSerializedConfiguration(String source) { try { Properties properties = new Properties(); properties.load(new StringReader(source)); ldapProperties = new LdapProperties(properties); translationProfile = getTranslationProfile(ldapProperties, CommonWebAuthnProperties.TRANSLATION_PROFILE, CommonWebAuthnProperties.EMBEDDED_TRANSLATION_PROFILE); clientConfiguration = new LdapClientConfiguration(ldapProperties, pkiManagement); } catch(ConfigurationException e) { throw new InternalException("Invalid configuration of the LDAP verificator", e); } catch (IOException e) { throw new InternalException("Invalid configuration of the LDAP verificator(?)", e); } } @Override public VerificatorType getType() { return VerificatorType.Remote; } @Override public List<IdPInfo> getIdPs() { return List.of(IdPInfo.builder().withId(getName()).withDisplayedName(new I18nString(getName())).build()); } }
33.154639
115
0.796331
d80335aa2c76eb022584931ee56ecf11ff361839
1,519
package com.test.ahmedorabi.movieapp.viewmodel; import android.app.Application; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Transformations; import androidx.annotation.NonNull; import com.test.ahmedorabi.movieapp.repository.data.MovieType; import com.test.ahmedorabi.movieapp.api.Resource; import com.test.ahmedorabi.movieapp.repository.ReviewRepository; import com.test.ahmedorabi.movieapp.repository.data.reviewModel.ReviewResponse; import com.test.ahmedorabi.movieapp.util.AbsentLiveData; import javax.inject.Inject; public class ReviewViewModel extends AndroidViewModel { private final LiveData<Resource<ReviewResponse>> reviewResponseLiveData; private final MutableLiveData<MovieType> movieType; @Inject public ReviewViewModel(ReviewRepository repository, @NonNull Application application) { super(application); this.movieType = new MutableLiveData<>(); reviewResponseLiveData = Transformations.switchMap(movieType, input -> { if (input == null) { return AbsentLiveData.create(); }else { return repository.getReviews(input.getId(),input.getType()); } }); } public LiveData<Resource<ReviewResponse>> getReviewResponseLiveData() { return reviewResponseLiveData; } public void setMovieType(MovieType type) { this.movieType.setValue(type); } }
28.660377
91
0.740619
32b1004077d10842b512a566546a3a0c5cdc43b1
5,847
package br.com.jadson.mailframe.client; import br.com.jadson.mailframe.client.dtos.AttachmentDto; import br.com.jadson.mailframe.client.dtos.MailDto; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.*; /** * Class to builder a Mail Dto Object. * https://www.vogella.com/tutorials/DesignPatternBuilder/article.html */ public class MailDtoBuilder { private String from; private List<String> to; private List<String> cc; private List<String> bcc; private String replyTo; private String subject; private String text; private Map<String, byte[]> attachments = new HashMap<>(); private String application; /** * Minimum constructor * * Build an anonymous email, the "form" field will be replaced by "noReply" * * @param to * @param subject * @param text * @param application */ public MailDtoBuilder(String to, String subject, String text, String application) { this(null, Arrays.asList(new String[]{to}), null, null, null, subject, text, application); } /** * Minimum constructor * * Build an anonymous email, the "form" field will be replaced by "noReply" * * @param to * @param subject * @param text * @param application */ public MailDtoBuilder(List<String> to, String subject, String text, String application) { this(null, to, null, null, null, subject, text, application); } /** * * @param from * @param to * @param subject * @param text * @param application */ public MailDtoBuilder(String from, String to, String subject, String text, String application) { this(from, Arrays.asList(new String[]{to}), null, null, null, subject, text, application); } /** * * @param from * @param to * @param subject * @param text * @param application */ public MailDtoBuilder(String from, List<String> to, String subject, String text, String application) { this(from, to, null, null, null, subject, text, application); } /** * Complete constructor * * @param from * @param to * @param cc * @param bcc * @param replyTo * @param subject * @param text * @param application */ public MailDtoBuilder(String from, List<String> to, List<String> cc, List<String> bcc, String replyTo, String subject, String text, String application) { this.from = from; this.to = to; this.cc = cc; this.bcc = bcc; this.replyTo = replyTo; this.subject = subject; this.text = text; this.application = application; } public MailDtoBuilder setFrom(String s) { from = s; return this; } public MailDtoBuilder addTo(String s) { if(to == null) to = new ArrayList<>(); to.add(s); return this; } public MailDtoBuilder addCc(String cc) { if(cc == null || cc.trim().isBlank()) throw new IllegalArgumentException("bcc: should have at least one mail"); if(this.cc == null) this.cc = new ArrayList<>(); this.cc.add(cc); return this; } public MailDtoBuilder addBcc(String bcc) { if(bcc == null || bcc.trim().isBlank()) throw new IllegalArgumentException("bcc: should have at least one mail"); if(this.bcc == null) this.bcc = new ArrayList<>(); this.bcc.add(bcc); return this; } public MailDtoBuilder setCc(List<String> cc) { if(cc == null || cc.size() == 0) throw new IllegalArgumentException("cc: should have at least one mail"); this.cc = cc; return this; } public MailDtoBuilder setBcc(List<String> bcc) { if(bcc == null || bcc.size() == 0) throw new IllegalArgumentException("bcc: should have at least one mail"); this.bcc = bcc; return this; } public MailDtoBuilder addFile(String fileName, byte[] file) { if(this.attachments == null){ this.attachments = new HashMap<>(); }else { if (this.attachments.containsKey(fileName)) throw new IllegalArgumentException("Attached files can not have same name"); } this.attachments.put(fileName, file); return this; } public MailDtoBuilder setReplyTO(String s) { replyTo = s; return this; } public MailDtoBuilder addFile(String fileName, File file) { try { this.addFile(fileName, Files.readAllBytes(file.toPath()) ); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage()); } return this; } public MailDtoBuilder addFile(String fileName, InputStream ins) { try { this.addFile(fileName, ins.readAllBytes() ); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage()); } return this; } public MailDto build() { MailDto dto = new MailDto(from, to, subject, text, application); if(cc != null && cc.size() > 0) dto.setCc(cc); if(bcc != null && bcc.size() > 0) dto.setBcc(bcc); if(replyTo != null && ! replyTo.isBlank()) dto.setReplyTo(replyTo); // attachments if(attachments.size() > 0){ List<AttachmentDto> atts = new ArrayList<>(); for (String key: attachments.keySet()) { atts.add(new AttachmentDto(key, Base64.getEncoder().encodeToString(attachments.get(key)))); } dto.setAttachments(atts); } return dto; } }
27.7109
157
0.585599
a1a83f2e7d594bd2da090a7920b76e107c6f5584
9,562
package example.app.model; import android.content.Context; import android.support.test.runner.AndroidJUnit4; import android.test.InstrumentationTestCase; import android.test.mock.MockContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; @RunWith(AndroidJUnit4.class) public class ExtendedUserTest extends InstrumentationTestCase { ExtendedUser user; private Context getApplicationContext() { return this.getInstrumentation().getTargetContext().getApplicationContext(); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test__constructor__default() throws Exception { user = new ExtendedUser(); //NOTE: protected assertEquals(ExtendedUser.class, user.getClass()); assertEquals(ExtendedUser.class.getName(), user.getCollectionID()); assertEquals(0, user.getEstimatedData().size()); assertEquals(0, user.getFilteredEstimatedData().size()); assertEquals(0, user.getOriginalData().size()); assertEquals(0, user.getAddedKeys().size()); assertEquals(0, user.getAddedKeysAndValues().size()); assertEquals(0, user.getUpdatedKeys().size()); assertEquals(0, user.getUpdatedKeysAndValues().size()); assertEquals(0, user.getRemovedKeys().size()); assertEquals(0, user.getRemovedKeysAndValues().size()); assertTrue(user.isNew()); assertFalse(user.isDirty()); assertNull(user.getID()); assertNull(user.getCreated()); assertNull(user.getCreatedBy()); assertNull(user.getUpdated()); assertNull(user.getUpdatedBy()); assertNull(user.getLoginId()); assertNull(user.getEmail()); assertFalse(user.isEmailVerified()); assertNull(user.getPassword()); assertNull(user.getAuthData()); assertNull(user.getState()); } @Test public void test__constructor__collectionID() throws Exception { user = new ExtendedUser("MyUser"); assertEquals(ExtendedUser.class, user.getClass()); assertEquals("MyUser", user.getCollectionID()); //XXX: ExtendedUserはコレクションを持たないので常に com.appiaries.baas.sdk.ExtendedUser が返されるはずなんですが。。。 assertEquals(0, user.getEstimatedData().size()); assertEquals(0, user.getFilteredEstimatedData().size()); assertEquals(0, user.getOriginalData().size()); assertEquals(0, user.getAddedKeys().size()); assertEquals(0, user.getAddedKeysAndValues().size()); assertEquals(0, user.getUpdatedKeys().size()); assertEquals(0, user.getUpdatedKeysAndValues().size()); assertEquals(0, user.getRemovedKeys().size()); assertEquals(0, user.getRemovedKeysAndValues().size()); assertTrue(user.isNew()); assertFalse(user.isDirty()); assertNull(user.getID()); assertNull(user.getCreated()); assertNull(user.getCreatedBy()); assertNull(user.getUpdated()); assertNull(user.getUpdatedBy()); assertNull(user.getLoginId()); assertNull(user.getEmail()); assertFalse(user.isEmailVerified()); assertNull(user.getPassword()); assertNull(user.getAuthData()); assertNull(user.getState()); } @Test public void test__constructor__collectionID__map() throws Exception { Map<String, Object> map = new HashMap<String, Object>(){ { put(ExtendedUser.Field.ID.getKey(), "8dce4f6cf9682027d889110426d"); put(ExtendedUser.Field.CREATED.getKey(), new Date(){{ setTime(1436951840123L / 1000); }}.getTime() * 1000); put(ExtendedUser.Field.CREATED_BY.getKey(), "fooman"); put(ExtendedUser.Field.UPDATED.getKey(), new Date(){{ setTime(1436951850987L / 1000); }}.getTime() * 1000); put(ExtendedUser.Field.UPDATED_BY.getKey(), "barman"); put(ExtendedUser.Field.LOGIN_ID.getKey(), "melissa"); put(ExtendedUser.Field.EMAIL.getKey(), "melissa@example.com"); put(ExtendedUser.Field.EMAIL_VERIFIED.getKey(), true); put(ExtendedUser.Field.PASSWORD.getKey(), "pw123456"); put(ExtendedUser.Field.AUTH_DATA.getKey(), new HashMap<String, Object>()); put(ExtendedUser.Field.STATE.getKey(), "locking"); put("ageGroup", 10); put("gender", "female"); put("favorites", new HashMap<String, Object>(){{ put("brands", Arrays.asList("Appiaries", "BaaS")); }}); } }; user = new ExtendedUser("MyUser", map); assertEquals(ExtendedUser.class, user.getClass()); assertEquals("MyUser", user.getCollectionID()); //XXX: ExtendedUserはコレクションを持たないので常に com.appiaries.baas.sdk.ExtendedUser が返されるはずなんですが。。。 assertEquals(14, user.getEstimatedData().size()); assertEquals(14, user.getFilteredEstimatedData().size()); assertEquals(14, user.getOriginalData().size()); assertEquals(0, user.getAddedKeys().size()); assertEquals(0, user.getAddedKeysAndValues().size()); assertEquals(0, user.getUpdatedKeys().size()); assertEquals(0, user.getUpdatedKeysAndValues().size()); assertEquals(0, user.getRemovedKeys().size()); assertEquals(0, user.getRemovedKeysAndValues().size()); assertTrue(user.isNew()); assertFalse(user.isDirty()); assertEquals("8dce4f6cf9682027d889110426d", user.getID()); assertEquals(1436951840123L / 1000, user.getCreated().getTime()); assertEquals("fooman", user.getCreatedBy()); assertEquals(1436951850987L / 1000, user.getUpdated().getTime()); assertEquals("barman", user.getUpdatedBy()); assertEquals("melissa", user.getLoginId()); assertEquals("melissa@example.com", user.getEmail()); assertEquals(true, user.isEmailVerified()); assertEquals("pw123456", user.getPassword()); assertNotNull(user.getAuthData()); assertEquals("locking", user.getState()); assertEquals(10, user.get("ageGroup")); assertEquals("female", user.get("gender")); assertEquals(1, ((Map<String, Object>) user.get("favorites")).size()); } @Test public void test__constructor__map() throws Exception { Map<String, Object> map = new HashMap<String, Object>(){ { put(ExtendedUser.Field.ID.getKey(), "8dce4f6cf9682027d889110426d"); put(ExtendedUser.Field.CREATED.getKey(), new Date(){{ setTime(1436951840123L / 1000); }}.getTime() * 1000); put(ExtendedUser.Field.CREATED_BY.getKey(), "fooman"); put(ExtendedUser.Field.UPDATED.getKey(), new Date(){{ setTime(1436951850987L / 1000); }}.getTime() * 1000); put(ExtendedUser.Field.UPDATED_BY.getKey(), "barman"); put(ExtendedUser.Field.LOGIN_ID.getKey(), "melissa"); put(ExtendedUser.Field.EMAIL.getKey(), "melissa@example.com"); put(ExtendedUser.Field.EMAIL_VERIFIED.getKey(), true); put(ExtendedUser.Field.PASSWORD.getKey(), "pw123456"); put(ExtendedUser.Field.AUTH_DATA.getKey(), new HashMap<String, Object>()); put(ExtendedUser.Field.STATE.getKey(), "locking"); put("ageGroup", 10); put("gender", "female"); put("favorites", new HashMap<String, Object>(){{ put("brands", Arrays.asList("Appiaries", "BaaS")); }}); } }; user = new ExtendedUser(map); assertEquals(ExtendedUser.class, user.getClass()); assertEquals(ExtendedUser.class.getName(), user.getCollectionID()); assertEquals(14, user.getEstimatedData().size()); assertEquals(14, user.getFilteredEstimatedData().size()); assertEquals(14, user.getOriginalData().size()); assertEquals(0, user.getAddedKeys().size()); assertEquals(0, user.getAddedKeysAndValues().size()); assertEquals(0, user.getUpdatedKeys().size()); assertEquals(0, user.getUpdatedKeysAndValues().size()); assertEquals(0, user.getRemovedKeys().size()); assertEquals(0, user.getRemovedKeysAndValues().size()); assertTrue(user.isNew()); assertFalse(user.isDirty()); assertEquals("8dce4f6cf9682027d889110426d", user.getID()); assertEquals(1436951840123L / 1000, user.getCreated().getTime()); assertEquals("fooman", user.getCreatedBy()); assertEquals(1436951850987L / 1000, user.getUpdated().getTime()); assertEquals("barman", user.getUpdatedBy()); assertEquals("melissa", user.getLoginId()); assertEquals("melissa@example.com", user.getEmail()); assertEquals(true, user.isEmailVerified()); assertEquals("pw123456", user.getPassword()); assertNotNull(user.getAuthData()); assertEquals("locking", user.getState()); assertEquals(10, user.get("ageGroup")); assertEquals("female", user.get("gender")); assertEquals(1, ((Map<String, Object>)user.get("favorites")).size()); } /*@Test public void testGetNickname() throws Exception { }*/ /*@Test public void testSetNickname() throws Exception { }*/ }
45.533333
143
0.635641
c294def6af25c03d1ebb19d20e938a948bc0ea50
1,941
package restPackage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class getDetailsRoot { public static void main(String []args) throws IOException, JSONException{ getCFS_root("main"); } public getDetailsRoot() { // TODO Auto-generated constructor stub } static String filePath; public static JSONObject getCFS_root(String fName) throws IOException, JSONException{ File dirs = new File("D:/4thyearBackEnd/temp_files/"); String dirPath = dirs.getCanonicalPath() + File.separator;//+"src"+File.separator; System.out.println("Chandeesha *********************fName"+fName); JSONObject obj1 = new JSONObject(); Collection<JSONObject> items = new ArrayList<JSONObject>(); File root = new File(dirPath); //System.out.println(rootDir.listFiles()); File[] files = root.listFiles ( ); filePath = null; for (File f : files ) { filePath = f.getAbsolutePath(); //file = filePath; if(f.isFile()){ System.out.println("Chandeesha *********************filePath"+filePath); obj1.put("value", CFS.getCFSValue_root(filePath));; } } System.out.println(obj1); return obj1; } // public static JSONObject getCWCM_root(String fName) throws IOException, JSONException{ // // File dirs = new File("G:/SLIIT/Year 4/testfiles/src"); // String dirPath = dirs.getCanonicalPath() + File.separator;//+"src"+File.separator; // // JSONObject obj1 = new JSONObject(); // Collection<JSONObject> items = new ArrayList<JSONObject>(); // // File root = new File(dirPath); // //System.out.println(rootDir.listFiles()); // File[] files = root.listFiles ( ); // filePath = null; // // // for (File f : files ) { // filePath = f.getAbsolutePath(); // // } // // return obj1; // // } }
23.962963
89
0.656363
c2ccce9c520a0ed063b3ef59937e9decaf0bdf44
2,435
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("3") class Record_3954 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 3954: FirstName is Monte") void FirstNameOfRecord3954() { assertEquals("Monte", customers.get(3953).getFirstName()); } @Test @DisplayName("Record 3954: LastName is Wowk") void LastNameOfRecord3954() { assertEquals("Wowk", customers.get(3953).getLastName()); } @Test @DisplayName("Record 3954: Company is Safety & Occuptnl Hlth Cncl") void CompanyOfRecord3954() { assertEquals("Safety & Occuptnl Hlth Cncl", customers.get(3953).getCompany()); } @Test @DisplayName("Record 3954: Address is 26 W Bel Air Ave") void AddressOfRecord3954() { assertEquals("26 W Bel Air Ave", customers.get(3953).getAddress()); } @Test @DisplayName("Record 3954: City is Aberdeen") void CityOfRecord3954() { assertEquals("Aberdeen", customers.get(3953).getCity()); } @Test @DisplayName("Record 3954: County is Harford") void CountyOfRecord3954() { assertEquals("Harford", customers.get(3953).getCounty()); } @Test @DisplayName("Record 3954: State is MD") void StateOfRecord3954() { assertEquals("MD", customers.get(3953).getState()); } @Test @DisplayName("Record 3954: ZIP is 21001") void ZIPOfRecord3954() { assertEquals("21001", customers.get(3953).getZIP()); } @Test @DisplayName("Record 3954: Phone is 410-272-0313") void PhoneOfRecord3954() { assertEquals("410-272-0313", customers.get(3953).getPhone()); } @Test @DisplayName("Record 3954: Fax is 410-272-8602") void FaxOfRecord3954() { assertEquals("410-272-8602", customers.get(3953).getFax()); } @Test @DisplayName("Record 3954: Email is monte@wowk.com") void EmailOfRecord3954() { assertEquals("monte@wowk.com", customers.get(3953).getEmail()); } @Test @DisplayName("Record 3954: Web is http://www.montewowk.com") void WebOfRecord3954() { assertEquals("http://www.montewowk.com", customers.get(3953).getWeb()); } }
25.364583
80
0.728953
e54fdc34babb69af2ed59c035b37a493b9e0d57d
3,313
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */ package io.annot8.components.documents.processors; public class DocumentProperties { public static final String CUSTOM_PREFIX = "custom."; public static final String AUTHOR = "author"; public static final String APPLICATION = "application"; public static final String APPLICATION_VERSION = "applicationVersion"; public static final String BYTE_COUNT = "byteCount"; public static final String CATEGORY = "category"; public static final String CELL_COUNT = "cellCount"; public static final String CHARACTER_COUNT = "characterCount"; public static final String CHARACTER_COUNT_WS = "characterCountWithSpaces"; public static final String COMMENTS = "comments"; public static final String COMPANY = "company"; public static final String CONTENT_STATUS = "contentStatus"; public static final String CONTENT_TYPE = "companyType"; public static final String CREATOR = "creator"; public static final String CREATION_DATE = "creationDate"; public static final String DOCUMENT_VERSION = "documentVersion"; public static final String DRAW_COUNT = "drawCount"; public static final String EDITING_DURATION = "editingDuration"; public static final String FRAME_COUNT = "frameCount"; public static final String GENERATOR = "generator"; public static final String HIDDEN_COUNT = "hiddenCount"; public static final String HIDDEN_SLIDE_COUNT = "hiddenSlideCount"; public static final String HYPERLINK_BASE = "hyperlinkBase"; public static final String IMAGE_COUNT = "imageCount"; public static final String INITIAL_CREATOR = "initialCreator"; public static final String KEYWORDS = "keywords"; public static final String LAST_MODIFIED_BY = "lastModifiedBy"; public static final String LAST_MODIFIED_DATE = "lastModifiedDate"; public static final String LAST_PRINTED_BY = "lastPrintedBy"; public static final String LAST_PRINTED_DATE = "lastPrintedDate"; public static final String LINE_COUNT = "lineCount"; public static final String MANAGER = "manager"; public static final String MULTIMEDIA_CLIP_COUNT = "multimediaClipCount"; public static final String NOTE_COUNT = "noteCount"; public static final String NW_CHARACTER_COUNT = "nonWhitespaceCharacterCount"; public static final String OBJECT_COUNT = "objectCount"; public static final String OLE_OBJECT_COUNT = "oleObjectCount"; public static final String PAGE_COUNT = "pageCount"; public static final String PARAGRAPH_COUNT = "paragraphCount"; public static final String PRESENTATION_FORMAT = "presentationFormat"; public static final String PRODUCER = "producer"; public static final String PUBLISHER = "publisher"; public static final String REVISION = "revision"; public static final String ROW_COUNT = "rowCount"; public static final String SLIDE_COUNT = "slideCount"; public static final String SECURITY = "security"; public static final String SENTENCE_COUNT = "sentenceCount"; public static final String SUBJECT = "subject"; public static final String SYLLABLE_COUNT = "syllableCount"; public static final String TABLE_COUNT = "tableCount"; public static final String TEMPLATE = "template"; public static final String WORD_COUNT = "wordCount"; private DocumentProperties() { // Private constructor } }
51.765625
80
0.778147
ff913e886aa1b911333e3d44fbabc9deb70fcf4b
1,762
package Entity; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.apache.ibatis.type.Alias; import java.io.Serializable; import java.util.Date; /** * @Author Hekai * @Date 2019/4/3 10:23 * @Description TODO **/ @Alias("User") public class User{ @SerializedName("user_id") private String id; @SerializedName("name") private String name; @SerializedName("email") private String email; @Expose(serialize = false,deserialize = false) private String phoneNumber; @SerializedName("img_head") private String imgHead; @SerializedName("create_time") private Date createTime; @Expose(serialize = false,deserialize = false) private int status; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImgHead() { return imgHead; } public void setImgHead(String imgHead) { this.imgHead = imgHead; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
18.547368
52
0.627128
87595ebce86b75a1ebadadf4c1477d03a87cacdc
2,653
package bus.ticketer.passenger; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.NfcAdapter.CreateNdefMessageCallback; import android.nfc.NfcAdapter.OnNdefPushCompleteCallback; import android.nfc.NfcEvent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.widget.Toast; public class BeamActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback { private NfcAdapter myNFC; private int ticketID; private final int MESSAGE_SENT = 1; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case MESSAGE_SENT: Intent intent = new Intent(BeamActivity.this, CentralActivity.class); intent.putExtra("Waiting", true); startActivity(intent); finish(); break; } } }; @Override public void onNewIntent(Intent intent) { setIntent(intent); } @Override public void onResume() { super.onResume(); if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) processIntent(getIntent()); } private void processIntent(Intent intent) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; String payload = new String(msg.getRecords()[0].getPayload()); Intent i = new Intent(BeamActivity.this, CentralActivity.class); if(payload.equals("Success")) i.putExtra("Success", true); else i.putExtra("Success", false); startActivity(i); finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beam); myNFC = NfcAdapter.getDefaultAdapter(this); if(myNFC == null) { Toast.makeText(this, "You have no NFC, please try with another device that has NFC!", Toast.LENGTH_SHORT).show(); } myNFC.setNdefPushMessageCallback(this, this); myNFC.setOnNdefPushCompleteCallback(this, this); ticketID = getIntent().getIntExtra("ID", -1); } @Override public void onNdefPushComplete(NfcEvent event) { mHandler.obtainMessage(MESSAGE_SENT).sendToTarget(); } @Override public NdefMessage createNdefMessage(NfcEvent event) { String test = "ID:"+ticketID; NdefMessage msg = new NdefMessage(new NdefRecord[] { NdefRecord.createMime("application/bus.ticketer.message", test.getBytes()) }); return msg; } }
26.53
116
0.747456
60b0a2272daf129685b268167981033cf5ca969f
666
package glass.phil.monzo.model.account; import javax.inject.Singleton; import dagger.Binds; import dagger.Module; import dagger.Provides; import glass.phil.monzo.model.Authorized; import glass.phil.monzo.model.Store; import retrofit2.Retrofit; @Module public abstract class AccountModule { @Provides static AccountApi accountApi(@Authorized Retrofit retrofit) { return retrofit.create(AccountApi.class); } @Provides @Singleton static Store<String> accountIdStore(Store.Factory factory) { return factory.create(String.class, "store::account_id"); } @Binds @Singleton abstract AccountManager accountManager(AccountManagerImpl accountManager); }
28.956522
94
0.794294
1c31352d9d00eda87c4695c11773f8b9d3644a5f
15,140
package com.hitzd.his.ReportBuilder.PEAAS.Day; import java.util.List; import com.hitzd.DBUtils.CommonMapper; import com.hitzd.DBUtils.JDBCQueryImpl; import com.hitzd.DBUtils.TCommonRecord; import com.hitzd.Factory.DBQueryFactory; import com.hitzd.Transaction.*; import com.hitzd.his.ReportBuilder.Interfaces.IReportBuilder; import com.hitzd.his.Utils.DateUtils; import com.hitzd.his.Utils.DictCache; import com.hitzd.his.Utils.DrugUtils; import com.hitzd.his.task.Task; import com.hitzd.persistent.Persistent4DB; /** * 药品统计支持部队医院 军委一号的情况 (药房表) * @author jingcong * */ public class DR_OutDrugCostInfo_Force extends Persistent4DB implements IReportBuilder { @Override public String getLogFileName() { // TODO Auto-generated method stub return null; } @Override public String BuildReport(String ADate, Task AOwner) { try { DrugDayCost(ADate); DrugDoctorDeptCost(ADate); DrugPatDDCost(ADate); } catch(Exception e) { e.printStackTrace(); } return "true"; } /** * 按天单药品费用统计 * @param ADate */ private void DrugDayCost(final String ADate) { TransactionTemp tt = new TransactionTemp("PEAAS"); tt.execute(new TransaCallback(null) { @SuppressWarnings ("unchecked") @Override public void ExceuteSqlRecord() { DictCache dc = DictCache.getNewInstance(); CommonMapper cmr = new CommonMapper(); JDBCQueryImpl his = DBQueryFactory.getQuery("HIS"); JDBCQueryImpl query = DBQueryFactory.getQuery("PEAAS"); StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append(" SELECT d.drug_name,d.drug_code,d.drug_spec,d.package_units units,d.firm_id,sum(t.costs)costs,sum(d.quantity)amount,t.ordered_by,t.dispensary"); sqlBuffer.append(" FROM PHARMACY.DRUG_PRESC_MASTER T ,PHARMACY.DRUG_PRESC_DETAIL D"); sqlBuffer.append(" WHERE T.PRESC_NO=D.PRESC_NO AND T.PRESC_DATE=D.PRESC_DATE"); sqlBuffer.append(" AND T.PRESC_DATE>=TO_DATE('"+ADate+"','YYYY-MM-DD') "); sqlBuffer.append(" AND T.PRESC_DATE<TO_DATE('" + DateUtils.getDateAdded(1, ADate)+"','YYYY-MM-DD') and t.presc_source=0 "); sqlBuffer.append(" group by d.drug_name,d.drug_code,d.drug_spec,d.package_units,d.firm_id,t.ordered_by,t.dispensary"); List<TCommonRecord> listDDC = his.query(sqlBuffer.toString(), cmr); query.update("delete dr_drugDayCost where dr_date = to_date('" + ADate + "','yyyy-mm-dd')"); for(TCommonRecord t : listDDC) { t.set("is_anti","0" ); if(DrugUtils.isKJDrug(t.get("drug_code"))) t.set("is_anti", "1"); TCommonRecord tCom = dc.getDrugDictInfo(t.get("Drug_code")); String sql = "insert into dr_drugDayCost(dr_date,drug_code, drug_name, cost, package_spec, amount, firm_id, dept_code, dept_name, dispensary, toxi_property, is_anti, dispensary_name, units) values ( " + "to_date('" + ADate + "','yyyy-mm-dd')" + ",'" + t.get("drug_code",true) + "'" + ",'" + t.get("drug_name",true) + "'" + ",'" + t.get("costs",true) + "'" + ",'" + t.get("drug_spec",true) + "'" + ",'" + t.get("amount",true) + "'" + ",'" + t.get("firm_id",true) + "'" + ",'" + t.get("ordered_by",true) + "'" + ",'" + dc.getDeptName(t.get("ordered_by")) + "'" + ",'" + t.get("dispensary",true) + "'" + ",'" + tCom.get("toxi_property",true) + "'" + ",'" + t.get("is_anti",true) + "'" + ",'" + dc.getDeptName(t.get("dispensary")) + "'" + ",'" + t.get("units",true) + "'" + " )"; query.update(sql); } sqlBuffer = null; cmr = null; query = null; listDDC = null; } }); } /** * 按天医生单药品费用统计 * @param ADate */ private void DrugDoctorDeptCost(final String ADate) { TransactionTemp tt = new TransactionTemp("PEAAS"); tt.execute(new TransaCallback(null) { @SuppressWarnings ("unchecked") @Override public void ExceuteSqlRecord() { DictCache dc = DictCache.getNewInstance(); CommonMapper cmr = new CommonMapper(); JDBCQueryImpl his = DBQueryFactory.getQuery("HIS"); JDBCQueryImpl query = DBQueryFactory.getQuery("PEAAS"); StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append(" SELECT d.drug_name,d.drug_code,d.drug_spec,d.package_units units,d.firm_id,sum(t.costs)costs,sum(d.quantity)amount,t.ordered_by,t.dispensary,t.prescribed_by"); sqlBuffer.append(" FROM PHARMACY.DRUG_PRESC_MASTER T ,PHARMACY.DRUG_PRESC_DETAIL D"); sqlBuffer.append(" WHERE T.PRESC_NO=D.PRESC_NO AND T.PRESC_DATE=D.PRESC_DATE"); sqlBuffer.append(" AND T.PRESC_DATE>=TO_DATE('"+ADate+"','YYYY-MM-DD') "); sqlBuffer.append(" AND T.PRESC_DATE<TO_DATE('"+DateUtils.getDateAdded(1, ADate)+"','YYYY-MM-DD') and t.presc_source=0 "); sqlBuffer.append(" group by d.drug_name,d.drug_code,d.drug_spec,d.package_units,d.firm_id,t.ordered_by,t.dispensary,t.prescribed_by"); List<TCommonRecord> listDDDC = his.query(sqlBuffer.toString(), cmr); query.update("delete DR_DRUGDOCTORDEPTCOST where dr_date = to_date('" + ADate + "','yyyy-mm-dd')"); for(TCommonRecord t : listDDDC) { t.set("is_anti","0" ); if(DrugUtils.isKJDrug(t.get("drug_code"))) t.set("is_anti", "1"); TCommonRecord tCom = dc.getDrugDictInfo(t.get("drug_code")); String sql = "insert into DR_DRUGDOCTORDEPTCOST(" + " dr_date" + ",drug_code" + ",drug_name " + ",doctor_code" + ",doctor_name " + ",amount" + ",cost" + ",package_spec" + ",dept_code" + ",dept_name" + ",toxi_property" + ",firm_id" + ",is_anti" + ",dispensary" + ",dispensary_name" + ",units ) " + " values(" + "to_date('" + ADate + "','yyyy-mm-dd')" + ",'" + t.get("drug_code",true) + "'" + ",'" + t.get("drug_name",true) + "'" + ",'" + t.get("doctor_code",true) + "'" + ",'" + (!"".equals(t.get("prescribed_by"))?t.get("prescribed_by",true):"无") + "'" + ",'" + t.get("amount",true) + "'" + ",'" + t.get("costs",true) + "'" + ",'" + t.get("drug_spec",true) + "'" + ",'" + t.get("ordered_by",true) + "'" + ",'" + dc.getDeptName(t.get("ordered_by")) + "'" + ",'" + tCom.get("toxi_property",true) + "'" + ",'" + t.get("firm_id",true) + "'" + ",'" + t.get("is_anti",true) + "'" + ",'" + t.get("dispensary",true) + "'" + ",'" + dc.getDeptName(t.get("dispensary")) + "'" + ",'" + t.get("units",true) + "'" + ")"; query.update(sql); } cmr = null; query = null; sqlBuffer = null; listDDDC = null; } }); } /** * 按天病人单药品费 * @param ADate */ private void DrugPatDDCost(final String ADate) { TransactionTemp tt = new TransactionTemp("PEAAS"); tt.execute(new TransaCallback(null) { @SuppressWarnings ("unchecked") @Override public void ExceuteSqlRecord() { DictCache dc = DictCache.getNewInstance(); CommonMapper cmr = new CommonMapper(); JDBCQueryImpl his = DBQueryFactory.getQuery("HIS"); JDBCQueryImpl query = DBQueryFactory.getQuery("PEAAS"); StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append(" SELECT t.patient_id,name,identity,charge_type,d.drug_name,d.drug_code,d.drug_spec,d.package_units units,d.firm_id,sum(t.costs)costs,sum(d.quantity)amount,t.ordered_by,t.dispensary,t.prescribed_by"); sqlBuffer.append(" FROM PHARMACY.DRUG_PRESC_MASTER T ,PHARMACY.DRUG_PRESC_DETAIL D"); sqlBuffer.append(" WHERE T.PRESC_NO=D.PRESC_NO AND T.PRESC_DATE=D.PRESC_DATE"); sqlBuffer.append(" AND T.PRESC_DATE>=TO_DATE('"+ADate+"','YYYY-MM-DD') "); sqlBuffer.append(" AND T.PRESC_DATE<TO_DATE('"+DateUtils.getDateAdded(1, ADate)+"','YYYY-MM-DD') and t.presc_source=0 "); sqlBuffer.append(" group by d.drug_name,d.drug_code,d.drug_spec,d.package_units,d.firm_id,t.ordered_by,t.dispensary,t.prescribed_by,t.patient_id,name,identity,charge_type"); List<TCommonRecord> listDDDC = his.query(sqlBuffer.toString(), cmr); query.update("delete DR_DRUGPATDDCOST where dr_date = to_date('" + ADate + "','yyyy-mm-dd')"); for(TCommonRecord t : listDDDC) { t.set("is_anti","0" ); if(DrugUtils.isKJDrug(t.get("drug_code"))) t.set("is_anti", "1"); TCommonRecord tCom = dc.getDrugDictInfo(t.get("drug_code")); String sql = "insert into DR_DRUGPATDDCOST(" + "dr_date" + ",drug_code" + ",drug_name" + ",patient_id" + ",pat_name" + ",pat_sex" + ",pat_age" + ",identity" + ",doctor_code" + ",doctor_name" + ",amount" + ",cost" + ",package_spec" + ",units" + ",dept_code" + ",dept_name" + ",firm_id" + ",charge_type" + ",is_anti" + ",toxi_property" + ",dispensary" + ",dispensary_name" + ") values(" + "to_date('" + ADate + "','yyyy-mm-dd')" + ",'" + t.get("drug_code",true) + "'" + ",'" + t.get("drug_name",true) + "'" + ",'" + (!"".equals(t.get("patient_id"))?t.get("patient_id",true):"无") + "'" + ",'" + t.get("name",true) + "'" + ",'" + t.get("sex",true) + "'" + ",'" + t.get("age",true) + "'" + ",'" + t.get("identity",true) + "'" + ",'" + t.get("doctor_code",true) + "'" + ",'" + (!"".equals(t.get("prescribed_by"))?t.get("prescribed_by",true):"无") + "'" + ",'" + t.get("amount",true) + "'" + ",'" + t.get("costs",true) + "'" + ",'" + t.get("drug_spec",true) + "'" + ",'" + t.get("units",true) + "'" + ",'" + t.get("ordered_by",true) + "'" + ",'" + dc.getDeptName(t.get("ordered_by")) + "'" + ",'" + t.get("firm_id",true) + "'" + ",'" + t.get("charge_type",true) + "'" + ",'" + t.get("is_anti",true) + "'" + ",'" + tCom.get("toxi_property",true) + "'" + ",'" + t.get("dispensary",true) + "'" + ",'" + dc.getDeptName( t.get("dispensary")) + "'" + ")"; query.update(sql); } cmr = null; query = null; sqlBuffer = null; listDDDC = null; } }); } /** * 选择 抓取门诊处方 出去药 药房 * @return private String getFetchDeptCode() { String[] depts = Config.getParamValue("FetchDataOut").split(";"); StringBuffer sbfr = new StringBuffer(); for(String s : depts) { sbfr.append("'").append(s).append("',"); } if(sbfr.length() > 0 ) sbfr.deleteCharAt(sbfr.length() - 1 ); return sbfr.toString(); } */ @Override public String BuildReportWithCR(String ADate, TCommonRecord crPatInfo, Task AOwner) { // TODO Auto-generated method stub return null; } @Override public void buildBegin(String ADate, Task AOwner) { // TODO Auto-generated method stub } @Override public void buildOver(String ADate, Task AOwner) { // TODO Auto-generated method stub } }
48.216561
234
0.428798