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
c0d7f41ea75e8b170317c6648f95cfcc6e0ae2ab
6,296
package com.cwc.mylibrary.utils; /** * Created by Administrator on 2017/4/10. */ import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import com.cwc.mylibrary.Log.MLogHelper; import com.cwc.mylibrary.R; import com.cwc.mylibrary.Toast.MToastHelper; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 其他 */ public class OtherUtils { private static final int[] weightNumber = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1}; private static final int[] checknumber = new int[]{1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2}; /** * @param source * @return 根据字符串获取MD5值 */ public static String getMD5(String source) { return getMD5(source.getBytes()); } /** * 获取MD5值 * * @param source * @return */ private static String getMD5(byte[] source) { String s = null; char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { java.security.MessageDigest md = java.security.MessageDigest .getInstance("MD5"); md.update(source); byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数, // 用字节表示就是 16 个字节 // System.out.println("tem "+new String(tmp)); char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符, // 所以表示成 16 进制需要 32 个字符 int k = 0; // 表示转换结果中对应的字符位置 for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节 // 转换成 16 进制字符的转换 byte byte0 = tmp[i]; // 取第 i 个字节 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, // >>> // 为逻辑右移,将符号位一起右移 str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换 } s = new String(str); // 换后的结果转换为字符串 } catch (Exception e) { e.printStackTrace(); } return s; } /** * 检查密码长度 * * @param s * @param context * @param min * @param max * @return */ public static boolean checkPwd(String s, Context context, int min, int max) { if (s.length() < min) { MToastHelper.showShort(context, "密码长度不能小于" + min + "位"); return false; } if (s.length() > max) { MToastHelper.showShort(context, "密码长度不能大于" + max + "位"); return false; } return true; } /** * 手机号码验证 */ public static boolean checkPhone(String mobiles) { Pattern p = Pattern .compile("^((13[0-9])|(15[^4,\\D])|(14[5,7])|(17[0-9])|(18[0-9])|(19[0-9])|(16[0-9]))\\d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); } /** * 检查身份证格式 * * @param idCardNum * @return */ public static boolean checkIDCard(String idCardNum) { if (idCardNum.length() == 15) { // 如果要进行验证的身份证号码为15位 idCardNum = fifteen2eighteen(idCardNum); // 将其转换为18位 } if (idCardNum.length() != 18) { return false; } String lastNum = idCardNum.substring(17, 18); // 获取要进行验证身份证号码的校验号 if (lastNum.equals(getLastNum(idCardNum))) { // 判断校验码是否正确 return true; } return false; } // 获取身份证号码中的校验码 private static String getLastNum(String idCardNum) { int verify = 0; idCardNum = idCardNum.substring(0, 17); // 获取身份证号码中的前17位 int sum = 0; int[] wi = new int[17]; // 创建int型数组 for (int i = 0; i < 17; i++) { // 循环向数组赋值 String temp = idCardNum.substring(i, i + 1); wi[i] = Integer.parseInt(temp); } for (int i = 0; i < 17; i++) { // 循环遍历数组 sum = sum + weightNumber[i] * wi[i]; // 对17位本利码加权求和 } verify = sum % 11; // 取模 if (verify == 2) { // 如果模为2,则返回"X" return "X"; } else { return String.valueOf(checknumber[verify]); // 否则返回对应的校验码 } } // 将15位身份证号码转为18位身份证号码 private static String fifteen2eighteen(String fifteenNumber) { String eighteenNumberBefore = fifteenNumber.substring(0, 6); // 获取参数身份证号码中的地区码 String eightNumberAfter = fifteenNumber.substring(6, 15); // 获取参数身份证号码中的出生日期码 String eighteenNumber; eighteenNumber = eighteenNumberBefore + "19"; // 将地区码后面加"19" eighteenNumber = eighteenNumber + eightNumberAfter; // 获取地区码加出生日期码 eighteenNumber = eighteenNumber + getLastNum(eighteenNumber); // 获取身份证的校验码 return eighteenNumber; // 将转换后的身份证号码返回 } /** * 将集合用","拼接起来 * @param list * @return */ public static String getStringFromList(List<String> list) { if (list == null || list.size() == 0) { return ""; } String temp = ""; for (String tempStr : list) { temp += (tempStr + ","); } temp = temp.substring(0, temp.length() - 1); MLogHelper.i("getStringFromList",temp); return temp; } public static SpannableString setTextColorWithSpan(Context context, int color, String content, int start, int end) { SpannableString spanString = new SpannableString(content); spanString.setSpan(new ForegroundColorSpan(ActivityCompat.getColor(context, color)), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); return spanString; } /** * 2 * 获取版本号 * 3 * @return 当前应用的版本号 * 4 */ public static String getVersion(Activity activity) { try { PackageManager manager = activity.getPackageManager(); PackageInfo info = manager.getPackageInfo(activity.getPackageName(), 0); String version = info.versionName; return version; } catch (Exception e) { e.printStackTrace(); return ""; } } }
30.415459
120
0.54352
a7d5c80e822c22a8a139e53a4bcebb7c6be24c9f
3,727
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.tools.build.bundletool.splitters; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.stream.Collectors.toList; import com.android.bundle.Files.TargetedNativeDirectory; import com.android.bundle.Targeting.Abi; import com.android.bundle.Targeting.AbiTargeting; import com.android.bundle.Targeting.NativeDirectoryTargeting; import com.android.tools.build.bundletool.model.ModuleEntry; import com.android.tools.build.bundletool.model.ModuleSplit; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import java.util.List; /** Splits the native libraries in the module by ABI. */ public class AbiNativeLibrariesSplitter implements ModuleSplitSplitter { /** Generates {@link ModuleSplit} objects dividing the native libraries by ABI. */ @Override public ImmutableCollection<ModuleSplit> split(ModuleSplit moduleSplit) { if (!moduleSplit.getNativeConfig().isPresent()) { return ImmutableList.of(moduleSplit); } ImmutableList.Builder<ModuleSplit> splits = new ImmutableList.Builder<>(); // Flatten all targeted directories. List<TargetedNativeDirectory> allTargetedDirectories = moduleSplit.getNativeConfig().get().getDirectoryList(); // Currently we only support targeting via ABI, so grouping it by Targeting.equals() should be // enough. ImmutableMultimap<NativeDirectoryTargeting, TargetedNativeDirectory> targetingMap = Multimaps.index(allTargetedDirectories, TargetedNativeDirectory::getTargeting); ImmutableSet<Abi> allAbis = targetingMap .keySet() .stream() .map(NativeDirectoryTargeting::getAbi) .collect(toImmutableSet()); for (NativeDirectoryTargeting targeting : targetingMap.keySet()) { ImmutableList.Builder<ModuleEntry> entriesList = new ImmutableList.Builder<ModuleEntry>() .addAll( targetingMap .get(targeting) .stream() .flatMap(directory -> moduleSplit.findEntriesUnderPath(directory.getPath())) .collect(toList())); ModuleSplit.Builder splitBuilder = moduleSplit .toBuilder() .setTargeting( moduleSplit .getTargeting() .toBuilder() .setAbiTargeting( AbiTargeting.newBuilder() .addValue(targeting.getAbi()) .addAllAlternatives( Sets.difference(allAbis, ImmutableSet.of(targeting.getAbi())))) .build()) .setMasterSplit(false) .setEntries(entriesList.build()); splits.add(splitBuilder.build()); } return splits.build(); } }
41.411111
98
0.677757
40f1e8b0f88204cfa488534caeabb64cc8db32fa
804
package ParseTree.ActionNodes; import java.util.Scanner; import javax.xml.ws.handler.MessageContext.Scope; import LookAheadScanner.LookAheadScanner; import Main.ParserFailureException; import Main.Robot; public class ShieldOnActionNode extends ActionNode { private ShieldOnActionNode() { } @Override public int execute(Robot robot, Main.Scope scope) { robot.setShield(true); return 1; } public String toString() { return "shieldOn;"; } public static ShieldOnActionNode ParseShieldOnActionNode(LookAheadScanner s) { if (!s.hasNext("shieldOn")) { throw new ParserFailureException("Was expecting 'turnL' token"); } s.next(); if (!s.hasNext(";")) { throw new ParserFailureException("Was expecing ';'"); } s.next(); return new ShieldOnActionNode(); } }
19.142857
79
0.722637
63a38a7e2a8ebe218c66479203d15794a46218a8
5,695
/** * ----------------------------------------------------------------------- * HOW TO USE THE METHODS IN (mysqli_query.java) * ----------------------------------------------------------------------- * Query => mysqli_query sql = new mysqli_query(" _SQL_STATEMENT_GOES_HERE_ "); * Rows => sql.mysqli_num_rows(); // get total number of rows * Assoc => Map<String,String> result = sql.mysqli_fetch_assoc( _INDEX_VALUE_IS_NEEDED_HERE_ ); // get data from sql * FETCH_ASSOC_RESULT => result.get(" _COLUMN_NAME_FROM_DATABASE_ "); // sort data like PHP * ERROR_CHECK => sql.result(); // check for errors (RETURNS True(for no errors) or Error message) * */ /** * ----------------------------------------------------------------------- * !NOTE! * ----------------------------------------------------------------------- * Only the MySQL service in xampp will work * */ package config; import java.sql.*; import java.util.*; /** * @author YoungFox * YoungFox is my nickname, username and gaming name * REAL NAME - Osunrinde Adebayo Stephen */ public class mysqli_query { //public variables public static String query; public static int length = 0; public static String result = ""; public static ArrayList<String> db_table = new ArrayList<>(); public static String exception; // class constructor public mysqli_query(String qry){ query = qry; // assign query to public variable try{ Class.forName("com.mysql.jdbc.Driver"); String db_name = "e_administration"; // database name String db_url = "jdbc:mysql://localhost:3306/"+db_name; // database url String db_user = "root"; // database username String db_pass = ""; // database password // connect to MySQL database try (Connection con = DriverManager.getConnection( db_url, db_user, db_pass)) { Statement stmt = con.createStatement(); String arr[] = query.split(" ", 2); if( arr[0].equals("DELETE") || arr[0].equals("UPDATE") || arr[0].equals("ALTER") || arr[0].equals("INSERT")){ int affRows = stmt.executeUpdate(query); // execute modification query length = affRows; } else { ResultSet rs = stmt.executeQuery(query); // execute query if(rs != null){ ResultSetMetaData rsmd = rs.getMetaData(); rs.last(); // jump to the last item in resultset [to get total number of items in resultSet] length = rs.getRow(); // store total number of rows in length variable rs.beforeFirst(); // jump back to the top /** * ---------------------------- * UPDATE db_table ArrayList * ---------------------------- * Go through the result to update the ArrayList */ int conlen = rsmd.getColumnCount(); while(rs.next()) { // iterate rows HashMap<String, String> tableRow = new HashMap<>(); String rowData = ""; String colName; String colValue; for (int c = 1; c < conlen; c++){ // iterate column colName = rsmd.getColumnName(c); // column name colValue = rs.getString(c); // column value tableRow.put(colName, colValue); // store column pair in array rowData += colValue; // DEBUG: stores only the column values } db_table.add(tableRow.toString()); // update db_table array with new row data } } try { rs.close(); } catch (SQLException e) { /* ignored */ } try { stmt.close(); } catch (SQLException e) { /* ignored */ } } try { con.close(); } catch (SQLException e) { /* ignored */ } } }catch(ClassNotFoundException | SQLException e){ //Error encountered: could not connect to database exception = e.getLocalizedMessage(); } } public int mysqli_num_rows(){ // fetches total number of rows from executed query return length; } public Map<String, String> mysqli_fetch_assoc(int index){ String rowData = db_table.get(index); // get row by index from db_table /** * ----------------------------- * VARIABLE CONVERSION * ----------------------------- * get map from rowData string * convert the string back to map * and use the value as the method return value **/ rowData = rowData.substring(1, rowData.length()-1); //remove curly brackets String[] keyValuePairs = rowData.split(",");//split the string to create key-value pairs Map<String,String> map = new HashMap<>(); for(String pair : keyValuePairs) //iterate over the pairs { String[] entry = pair.split("="); //split the pairs to get key and value map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces } return map; } public String result(){ // method used to check for errors if(length > 0 && result != null){ result = "true"; } else { result += "<br>SQL Syntax: "+query; result += "<br>Exception: "+exception; result += " <font style='font-weight: bold;' color='res'>FAILED</font><br>"; } return result; } }
41.569343
116
0.512906
aef93908f34034648bc542e0f74522710ebd70ee
1,964
package org.insightcentre.nlp.saffron.data.connections; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author jmccrae */ public class TermTermTest { public TermTermTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void test() throws IOException { ObjectMapper mapper = new ObjectMapper(); final String data = "{\""+ TermTerm.JSON_TERM1_ID + "\": \"t1\", \""+ TermTerm.JSON_TERM2_ID + "\": \"t2\", \""+ TermTerm.JSON_SIMILARITY + "\": 0.3 }"; final TermTerm tt = mapper.readValue(data, TermTerm.class); assertEquals("t1", tt.getTerm1()); assertEquals("t2", tt.getTerm2()); assertEquals(0.3, tt.getSimilarity(), 0.0); final String json = mapper.writeValueAsString(tt); assertEquals(tt, mapper.readValue(json, TermTerm.class)); } /** * Test compatibility with data from Saffron 3.3 * * To be deprecated in version 4 * @throws IOException */ @Test public void test2() throws IOException { ObjectMapper mapper = new ObjectMapper(); final String data = "{\""+ "topic1_id" + "\": \"t1\", \""+ "topic2_id" + "\": \"t2\", \""+ TermTerm.JSON_SIMILARITY + "\": 0.3 }"; final TermTerm tt = mapper.readValue(data, TermTerm.class); assertEquals("t1", tt.getTerm1()); assertEquals("t2", tt.getTerm2()); assertEquals(0.3, tt.getSimilarity(), 0.0); final String json = mapper.writeValueAsString(tt); assertEquals(tt, mapper.readValue(json, TermTerm.class)); } }
28.463768
160
0.617108
94b7549a0dc06068022fe0acf228bd7f1914523b
284
package example.repo; import example.model.Customer1031; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1031Repository extends CrudRepository<Customer1031, Long> { List<Customer1031> findByLastName(String lastName); }
21.846154
84
0.830986
1de123f54eabe4b057fff39c40c8c6a238e6a9c8
136
import java.util.*; class T { void f(Set<String> t, String[] f, int a, int b) { t.addAll(Arrays.asList(f).subList(a, b)); } }
19.428571
51
0.580882
c56b5ec514f1b437ef801d4313f3364236482a4a
723
package org.hanframework.beans.parse.exception; /** * @author liuxin * @version Id: BeanDefinitionParserException.java, v 0.1 2019-01-31 14:54 */ public class BeanDefinitionParserException extends RuntimeException { public BeanDefinitionParserException(String message) { super(message); } public BeanDefinitionParserException(String message, Throwable cause) { super(message, cause); } public BeanDefinitionParserException(Throwable cause) { super(cause); } public BeanDefinitionParserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
28.92
130
0.738589
1ebbd01b2b1c844f7922c54546b3827b7c6ee693
400
package com.example.coolweather.gson; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Administrator on 2017/6/15. */ public class Weather { public String status; public Basic basic; public AQI aqi; public Now now; public Suggestion suggestion; @SerializedName("daily_forecast") public List<Forecast> forecastList; }
20
50
0.7125
c43c6b7ed83ac6805dd4fab3dd8e395cc2bf82dd
5,889
//This is a java program to search an element in binary search tree import java.util.Random; import java.util.Scanner; /* Class BSTNode */ class BSTNode { BSTNode left, right; int data; /* Constructor */ public BSTNode() { left = null; right = null; data = 0; } /* Constructor */ public BSTNode(int n) { left = null; right = null; data = n; } /* Function to set left node */ public void setLeft(BSTNode n) { left = n; } /* Function to set right node */ public void setRight(BSTNode n) { right = n; } /* Function to get left node */ public BSTNode getLeft() { return left; } /* Function to get right node */ public BSTNode getRight() { return right; } /* Function to set data to node */ public void setData(int d) { data = d; } /* Function to get data from node */ public int getData() { return data; } } /* Class BST */ class BST { private BSTNode root; /* Constructor */ public BST() { root = null; } /* Function to check if tree is empty */ public boolean isEmpty() { return root == null; } /* Functions to insert data */ public void insert(int data) { root = insert(root, data); } /* Function to insert data recursively */ private BSTNode insert(BSTNode node, int data) { if (node == null) node = new BSTNode(data); else { if (data <= node.getData()) node.left = insert(node.left, data); else node.right = insert(node.right, data); } return node; } /* Functions to delete data */ public void delete(int k) { if (isEmpty()) System.out.println("Tree Empty"); else if (search(k) == false) System.out.println("Sorry " + k + " is not present"); else { root = delete(root, k); System.out.println(k + " deleted from the tree"); } } private BSTNode delete(BSTNode root, int k) { BSTNode p, p2, n; if (root.getData() == k) { BSTNode lt, rt; lt = root.getLeft(); rt = root.getRight(); if (lt == null && rt == null) return null; else if (lt == null) { p = rt; return p; } else if (rt == null) { p = lt; return p; } else { p2 = rt; p = rt; while (p.getLeft() != null) p = p.getLeft(); p.setLeft(lt); return p2; } } if (k < root.getData()) { n = delete(root.getLeft(), k); root.setLeft(n); } else { n = delete(root.getRight(), k); root.setRight(n); } return root; } /* Functions to count number of nodes */ public int countNodes() { return countNodes(root); } /* Function to count number of nodes recursively */ private int countNodes(BSTNode r) { if (r == null) return 0; else { int l = 1; l += countNodes(r.getLeft()); l += countNodes(r.getRight()); return l; } } /* Functions to search for an element */ public boolean search(int val) { return search(root, val); } /* Function to search for an element recursively */ private boolean search(BSTNode r, int val) { boolean found = false; while ((r != null) && !found) { int rval = r.getData(); if (val < rval) r = r.getLeft(); else if (val > rval) r = r.getRight(); else { found = true; break; } found = search(r, val); } return found; } /* Function for inorder traversal */ public void inorder() { inorder(root); } private void inorder(BSTNode r) { if (r != null) { inorder(r.getLeft()); System.out.print(r.getData() + " "); inorder(r.getRight()); } } /* Function for preorder traversal */ public void preorder() { preorder(root); } private void preorder(BSTNode r) { if (r != null) { System.out.print(r.getData() + " "); preorder(r.getLeft()); preorder(r.getRight()); } } /* Function for postorder traversal */ public void postorder() { postorder(root); } private void postorder(BSTNode r) { if (r != null) { postorder(r.getLeft()); postorder(r.getRight()); System.out.print(r.getData() + " "); } } } public class Search_Element_BST { public static int N = 20; public static void main(String args[]) { Random random = new Random(); BST bst = new BST(); for (int i = 0; i < N; i++) bst.insert(Math.abs(random.nextInt(100))); System.out.print("In order traversal of the tree :\n"); bst.inorder(); System.out.println("\nEnter the element to be searched: "); Scanner sc = new Scanner(System.in); System.out.println("Search result : " + bst.search(sc.nextInt())); sc.close(); } }
21.336957
74
0.452199
d794e1cdec0008aad24c2b284ccf5bac703cc304
347
package saqib.rasul.server; import java.rmi.RemoteException; import saqib.rasul.Compute; import saqib.rasul.Task; public class ComputeEngine implements Compute { @Override public <T> T executeTask(Task<T> t) throws RemoteException { System.out.println("got compute task: " + t); return t.execute(); } }
19.277778
53
0.674352
f4436011d635ad1f1ea8023c053e69a997aa5b4d
317
package com.liveramp.hank.ui; import com.liveramp.hank.generated.ClientMetadata; import java.util.Comparator; public class ClientMetadataComparator implements Comparator<ClientMetadata> { @Override public int compare(ClientMetadata a, ClientMetadata b) { return a.get_host().compareTo(b.get_host()); } }
24.384615
77
0.782334
3629ff8e8a1f980cb51b1dacbb6779ea449a5991
4,689
/* * @(#)Question.java * Copyright © 2020 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.gift.parser; import java.text.Normalizer; import java.util.LinkedList; import java.util.StringTokenizer; /** * Question. * * @author Werner Randelshofer */ public class Question { private String id; private String title; private LinkedList<Object> body; private int startPosition; private int endPosition; /** * Creates a new instance. */ public Question() { body = new LinkedList<Object>(); } public void setTitle(String newValue) { title = newValue; } public String getTitle() { return title; } public void setId(String newValue) { id = newValue; } public String getId() { return id; } /** * Returns the title of the question. If the question does not have a * title, returns the first few words of the question text with an * ellipsis added to them. */ public String getDescriptiveTitle() { String str = getTitle(); if (str == null) { // Get the first two words StringBuilder buf = new StringBuilder(); bodyLoop: for (Object o : getBody()) { if (o instanceof String) { StringTokenizer st = new StringTokenizer((String) o); while (st.hasMoreTokens()) { if (buf.length() == 0) { buf.append(st.nextToken()); } else { buf.append(' '); buf.append(st.nextToken()); break bodyLoop; } } } } // Append an elipsis to the words if (buf.length() > 0) { buf.append("..."); str = buf.toString(); } else { str = ""; } } return str; } /** * Returns the descriptive title of the question converted to lower * case and all special characters removed. */ public String getDescriptiveURL() { String str = Normalizer.normalize(getDescriptiveTitle().toLowerCase(), Normalizer.Form.NFKD); StringBuilder buf = new StringBuilder(str.length()); for (int i = 0, n = str.length(); i < n; i++) { char ch = str.charAt(i); if (ch <= ' ' && buf.length() > 0 && buf.charAt(buf.length() - 1) != '_') { buf.append('_'); } else if (ch >= 'a' && ch <= 'z') { buf.append(ch); } } if (buf.length() > 24) { buf.setLength(24); } return buf.toString(); } public LinkedList<Object> getBody() { return body; } public void addQuestionText(String newValue) { body.add(newValue); } public void addAnswerList(AnswerList newValue) { body.add(newValue); } public String toString() { StringBuilder buf = new StringBuilder(); if (title != null) { buf.append("title: "); buf.append(title); buf.append('\n'); } buf.append("body: "); buf.append(body.toString()); return buf.toString(); } /** * Returns true, if the question text is missing, or if no answer list * is defined. */ public boolean isIncomplete() { boolean isIncomplete = false; if (getBody().size() == 0) { isIncomplete = true; } else { boolean hasQuestionText = false; boolean hasAnswerList = false; boolean isExternalAnswerList = false; for (Object o : getBody()) { if (o instanceof String) { hasQuestionText = true; } if (o instanceof AnswerList) { hasAnswerList = true; AnswerList al = (AnswerList) o; isExternalAnswerList = isExternalAnswerList | al.getType() == AnswerListType.EXTERNAL; } } isIncomplete = (!hasQuestionText && !isExternalAnswerList) /*|| ! hasAnswerList*/; } return isIncomplete; } public int getStartPosition() { return startPosition; } public void setStartPosition(int start) { this.startPosition = start; } public int getEndPosition() { return endPosition; } public void setEndPosition(int end) { this.endPosition = end; } }
27.261628
106
0.507997
5995b49b964a0fef2208a5bbf0cef2012f70b627
543
package com.diamondq.common.lambda.interfaces; public interface CancelableSupplier<R> extends Supplier<R>, java.util.function.Supplier<R>, Cancelable { public static final class NoopCancelableSupplier<R> implements CancelableSupplier<R> { private final Supplier<R> mDelegate; public NoopCancelableSupplier(Supplier<R> pDelegate) { mDelegate = pDelegate; } @Override public R get() { return mDelegate.get(); } @Override public void cancel() { } } @Override public void cancel(); }
20.884615
104
0.694291
4ce95cd4feb52e0656563bf9c3caee3235915771
649
package cn.amarone.model.sys.common.bizEnum; /** * @Description: * @Author: Amarone * @Created Date: 2019年03月27日 * @LastModifyDate: * @LastModifyBy: * @Version: */ public enum CommEnum { success("200", "操作成功!"), error("500", "操作失败!"); private String code; private String msg; CommEnum(String code, String msg) { this.code = code; this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}
17.540541
51
0.57319
ee2703c285bc2cf69adc4c377d5089d51f394756
507
package com.nickamor.movieclub.controller; import android.os.AsyncTask; import com.nickamor.movieclub.model.MovieModel; /** * Background task to set new rating. */ public class SetRatingTask extends AsyncTask<String, Void, Void> { private final float rating; public SetRatingTask(float rating) { this.rating = rating; } @Override protected Void doInBackground(String... params) { MovieModel.getInstance().setRating(params[0], rating); return null; } }
22.043478
66
0.696252
b4efda3da18d623fea699ac9c4ff5cc131f4cbfe
1,950
package com.easyt.service.impl; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.easyt.constant.MessagesErroEnum; import com.easyt.constant.ProfileEnum; import com.easyt.constant.StatusEnum; import com.easyt.converter.ConverterHelper; import com.easyt.entity.User; import com.easyt.exception.ApplicationException; import com.easyt.repository.UserRepository; import com.easyt.response.UserResponse; import com.easyt.service.DriverService; @Service @Transactional public class DriverServiceImpl implements DriverService { @Autowired private UserRepository userRepository; @Override public void deleteDriver(Long driverId) throws ApplicationException { if (driverId == null) throw new ApplicationException(MessagesErroEnum.PARAMETER_EMPTY_OR_NULL.getMessage()); Optional<User> driverDB = userRepository .findOneByIdAndProfileAndStatusNot( driverId, ProfileEnum.DRIVER, StatusEnum.INACTIVE); if (driverDB == null || !driverDB.isPresent()) throw new ApplicationException(MessagesErroEnum.USER_NOT_FOUND.getMessage()); driverDB.get().setEditionDate(Calendar.getInstance()); driverDB.get().setStatus(StatusEnum.INACTIVE); userRepository.save(driverDB.get()); } @Override public List<UserResponse> listAllDriver() throws ApplicationException { List<UserResponse> drivers = new ArrayList<>(); userRepository .findAllByStatusNotAndProfileOrderByNameAsc(StatusEnum.INACTIVE, ProfileEnum.DRIVER) .forEach(user->{ UserResponse objectUser = new UserResponse(); objectUser = ConverterHelper.convertUserToResponse(user, null, null); drivers.add(objectUser); }); return drivers; } }
34.821429
90
0.772821
46ab2f81fd0da57930bf428fd3cf916e76cf147e
811
package com.hendyirawan.jws1036; import org.springframework.data.rest.webmvc.spi.BackendIdConverter; import org.springframework.stereotype.Component; import java.io.Serializable; @Component public class CountryLanguageIdConverter implements BackendIdConverter { @Override public Serializable fromRequestId(String id, Class<?> entityType) { String[] parts = id.split("-"); return new CountryLanguage.PK(parts[0], parts[1]); } @Override public String toRequestId(Serializable id, Class<?> entityType) { CountryLanguage.PK pk = (CountryLanguage.PK) id; return String.format("%s-%s", pk.getCountryCode(), pk.getLanguage()); } @Override public boolean supports(Class<?> delimiter) { return delimiter.equals(CountryLanguage.class); } }
30.037037
77
0.711467
62dc54fcc8bae8b87a9c33f503e190d7746f5e44
741
package org.apereo.cas.configuration.model.core.audit; import org.apereo.cas.configuration.model.support.couchbase.BaseCouchbaseProperties; import org.apereo.cas.configuration.support.RequiresModule; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; /** * This is {@link AuditCouchbaseProperties}. * * @author Misagh Moayyed * @since 6.0.0 */ @RequiresModule(name = "cas-server-support-audit-couchbase") @Getter @Setter @Accessors(chain = true) public class AuditCouchbaseProperties extends BaseCouchbaseProperties { private static final long serialVersionUID = 580545095591694L; /** * Whether audit records should be executed asynchronously. */ private boolean asynchronous; }
26.464286
84
0.775978
97628b82523648ce00ae05dce296f3d60378f931
1,331
package com.hltech.store.versioning; /** * In this strategy multiple versions of the event are up-casted to the latest version using registered transformation. * In opposite to {@link MultipleVersionsBasedVersioning} the application code has to support only the latest version of the event * * <p>Please note that using this strategy is recommended only if you have one instance of your application running at the same time. * Using this strategy in multi instance case, leads to the situation where all instance must be updated * to understand latest event version before any instance produces it. For multi instance case consider using {@link MappingBasedVersioning} */ public class UpcastingBasedVersioning<E> implements EventVersioningStrategy<E> { @Override public E toEvent(String eventJson, String eventName, int eventVersion) { throw new IllegalStateException("Not yet implemented"); } @Override public String toName(Class<? extends E> eventType) { throw new IllegalStateException("Not yet implemented"); } @Override public int toVersion(Class<? extends E> eventType) { throw new IllegalStateException("Not yet implemented"); } @Override public String toJson(E event) { throw new IllegalStateException("Not yet implemented"); } }
39.147059
140
0.744553
a3e6c1c79435c327595ef0ad4a74342dbd0cc76a
15,777
package com.thirdpart.tasktrackerpms.ui; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.http.Header; import android.R.integer; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLayoutChangeListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.jameschen.comm.utils.Log; import com.jameschen.comm.utils.MyHttpClient; import com.jameschen.framework.base.BaseEditActivity; import com.jameschen.widget.CustomSelectPopupWindow.Category; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.thirdpart.model.IssueManager; import com.thirdpart.model.ManagerService.OnReqHttpCallbackListener; import com.thirdpart.model.ManagerService.OnUploadReqHttpCallbackListener; import com.thirdpart.model.MediaManager; import com.thirdpart.model.Config.ReqHttpMethodPath; import com.thirdpart.model.MediaManager.MediaChooseListener; import com.thirdpart.model.TeamMemberManager; import com.thirdpart.model.UploadFileManager; import com.thirdpart.model.TeamMemberManager.LoadUsersListener; import com.thirdpart.model.WidgetItemInfo; import com.thirdpart.model.entity.IssueResult; import com.thirdpart.model.entity.RollingPlan; import com.thirdpart.model.entity.WorkStep; import com.thirdpart.tasktrackerpms.R; import com.thirdpart.widget.AddItemView; import com.thirdpart.widget.AddItemView.AddItem; import com.thirdpart.widget.ChooseItemView; import com.thirdpart.widget.EditItemView; import com.thirdpart.widget.UserInputItemView; public class IssueFeedbackActivity extends BaseEditActivity implements OnUploadReqHttpCallbackListener { List<Category> mFiles = new ArrayList<Category>(); List<Category> mGuanzhuList = new ArrayList<Category>(); IssueManager sIssueManager; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); mediaManager.onActivityResult(requestCode, resultCode, data); } UserInputItemView issueDescView; EditItemView issueTopic; AddItemView addFile, addPerson; ChooseItemView solverMan; RollingPlan rollingPlan; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setTitle("问题反馈"); rollingPlan = (RollingPlan) getIntent().getSerializableExtra("feedback"); initInfo(); bindView(); sIssueManager = (IssueManager) IssueManager.getNewManagerService(this, IssueManager.class, this); teamMemberManager = new TeamMemberManager(this); teamMemberManager.filterDepart = false; mediaManager = new MediaManager(this); } public void onAttachedToWindow() { super.onAttachedToWindow(); getDeliveryList(false, solverMan); }; TeamMemberManager teamMemberManager; MediaManager mediaManager; UploadFileManager uploadFileManager; private void bindView() { // TODO Auto-generated method stub findViewById(R.id.issue_feedback_container).addOnLayoutChangeListener( new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // TODO Auto-generated method stub int addItem = bottom - oldBottom; if (addItem > 0 && oldBottom > 0) { ScrollView scrollView = (ScrollView) findViewById(R.id.container); Log.i(TAG, "deltaHeight=" + addItem + ";bottom=" + bottom + ";oldBottom=" + oldBottom); scrollView.scrollBy(0, addItem); } } }); issueDescView = (UserInputItemView) findViewById(R.id.issue_desc); issueTopic = (EditItemView) findViewById(R.id.issue_topic); addFile = (AddItemView) findViewById(R.id.issue_add_file); solverMan = (ChooseItemView) findViewById(R.id.issue_choose_deliver); solverMan.setContent("选择解决人"); addPerson = (AddItemView) findViewById(R.id.issue_add_person); addPerson.setVisibility(View.GONE); solverMan.setChooseItemClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub getDeliveryList(true, solverMan); } }); addFile.setOnCreateItemViewListener(addfileListenr); addPerson.setOnCreateItemViewListener(addfoucsPersonCreateListenr); } AddItemView.CreateItemViewListener addfileListenr = new AddItemView.CreateItemViewListener() { @Override public void oncreateItem(String tag, View convertView) { // TODO Auto-generated method stub mFiles.add(new Category(tag));// empty } @Override public void deleteItem(int index) { // TODO Auto-generated method stub mFiles.remove(index); } @Override public void chooseItem(int index, View convertView) { // TODO Auto-generated method stub chooseMedia(convertView); } }; AddItemView.CreateItemViewListener addfoucsPersonCreateListenr = new AddItemView.CreateItemViewListener() { @Override public void oncreateItem(String tag, View convertView) { // TODO Auto-generated method stub mGuanzhuList.add(new Category(tag));// empty } @Override public void deleteItem(int index) { // TODO Auto-generated method stub mGuanzhuList.remove(index); } @Override public void chooseItem(int index, View convertView) { // TODO Auto-generated method stub getDeliveryList(true, convertView); } }; IssueResult issueResult = new IssueResult(); Category solverCategory; private void getDeliveryList(boolean showWindowView, final View view) { // TODO Auto-generated method stub // showLoadingView(true); teamMemberManager.findDepartmentInfos(showWindowView, view, new LoadUsersListener() { @Override public void onSelcted(Category mParent, Category category) { // TODO Auto-generated method stub if (view == solverMan) { solverCategory = category; solverMan.setContent(category.getName()); } else {// check is foucs choose person ChooseItemView chooseItemView = (ChooseItemView) view .findViewById(R.id.common_add_item_title); for (Category mCategory : mGuanzhuList) { if (category.getId().equals(mCategory.getId())) { // modify do nothing. if (!category.getName().equals( chooseItemView.getContent())) { showToast("该关注人已经在列表了");// not in // current // chooseItem,but // other already // has this // name. } return; } } chooseItemView.setContent(category.getName()); AddItem addItem = (AddItem) chooseItemView.getTag(); // 关注人是否已经存在,就只更新 for (Category mCategory : mGuanzhuList) { if (addItem.tag.equals(mCategory.tag)) { // modify . mCategory.setName(category.getName()); mCategory.setId(category.getId()); return; } } Log.i(TAG, "can not find the select item from fouc:"); } } @Override public void loadEndSucc(int type) { // TODO Auto-generated method stub } @Override public void loadEndFailed(int type) { // TODO Auto-generated method stub } @Override public void beginLoad(int type) { // TODO Auto-generated method stub } }); } protected void chooseMedia(final View convertView) { // TODO Auto-gener mediaManager.showMediaChooseDialog(new MediaChooseListener() { @Override public void chooseImage(int reqCodeTakePicture, String filePath) { String fileName = filePath; View chooseItemView = convertView .findViewById(R.id.common_add_item_title); View imgItemView = convertView.findViewById(R.id.img_container); TextView sTextView = (TextView) convertView .findViewById(R.id.common_add_item_content); AddItem addItem = (AddItem) chooseItemView.getTag(); for (Category mCategory : mFiles) { if (fileName.equals(mCategory.getName())) { // modify do nothing. if (!fileName.equals(sTextView.getTag())) { showToast("该文件在列表了");// not in current // chooseItem,but other // already has this name. } return; } } imgItemView.setVisibility(View.VISIBLE); // load image ImageView prewImg = (ImageView) convertView .findViewById(R.id.common_prew_img); if (imageLoader == null) { imageLoader = ImageLoader.getInstance(); } imageLoader.displayImage("file://" + filePath, prewImg, options); sTextView.setText(new File(fileName).getName()); sTextView.setTag(fileName); // 衣衣对应 是否已经存在,就只更新 for (Category mCategory : mFiles) { if (addItem.tag.equals(mCategory.tag)) { // modify . mCategory.setName(fileName); return; } } Log.i(TAG, "can not find the select item from file:"); } }); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (imageLoader != null) { imageLoader.clearMemoryCache(); } } private ImageLoader imageLoader; DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_launcher) .imageScaleType(ImageScaleType.IN_SAMPLE_INT) .bitmapConfig(Bitmap.Config.RGB_565) .showImageOnFail(R.drawable.ic_launcher) .considerExifParams(true).cacheInMemory(true).cacheOnDisc(true) .build(); /** * {"witnessdateaqc1":null,"operatedesc":"s","witnessdateaqc2":null, * * "rollingPlan":{"technologyAsk":null,"remark":null,"qcsign":0,"consteam": * "21", "consdate":1426348800000,"qualityRiskCtl":null,"welder":null, * "updatedBy":null, * "id":28,"assigndate":1432957400000,"drawno":"07060DY-JPS01-JPD-003" * ,"qualitynum":1, * "weldno":"M1","areano":"DY","updatedOn":null,"qcdate":null,"qcman":null, * "qualityplanno" * :"NZPT-TQP-0DY-JPD-P-20519","speciality":"GDHK","plandate": * "2015-05-30至2015-05-31", * "materialtype":"CS","workTool":null,"weldlistno": * "HJKZ-TQP-20519-00518","isend":1,"experienceFeedback":null, * "createdOn":1432957324000 * ,"createdBy":"admin","unitno":"0","planfinishdate" * :1432915200000,"consendman":"22", * "doissuedate":null,"enddate":null,"worktime" * :1,"securityRiskCtl":null,"workpoint":0.325,"rccm":"NA"}, * * "operater":"dd","witnesseraqa":null,"updatedBy":"zhangxu","noticed":null, * "witnesserb" * :null,"id":61,"witnesserc":null,"witnesserd":null,"operatedate" * :1432979974000,"noticeaqa":null, * "noticeb":null,"noticec":null,"updatedOn" * :1432979977000,"stepname":"坡口加工","witnessdateaqa":null, * "stepflag":"DONE","noticeainfo":null,"stepno":1,"noticeresul * * * * * * * * * * tdesc":null,"createdOn":1432957324000,"" + * "createdBy":"admin","noticeresult" * :null,"witnesseraqc2":null,"witnesseraqc1":null,"witnessdatec":null, * "witnessdated" * :null,"noticeaqc1":null,"noticeaqc2":null,"witnessdateb":null} */ /* * params.put("workstepid", issue.getWorstepid()); params.put("workstepno", * issue.getStepno()); params.put("stepname", issue.getStepname()); * params.put("questionname", issue.getQuestionname()); * params.put("describe", issue.getDescribe()); params.put("solverid", * issue.getSolverid()); params.put("concernman", issue.getConcerman()); */ @Override public void callCommitBtn(View v) { // TODO Auto-generated method stub if (TextUtils.isEmpty(issueTopic.getContent())) { showToast("请填写问题主题"); return; } if (TextUtils.isEmpty(issueDescView.getContent())) { showToast("请填写问题描述"); return; } if (solverCategory == null) { showToast("请选择解决人"); return; } issueResult.setSolverid(solverCategory.getId()); String concerman = getConcerMan(); issueResult.setConcerman(concerman); List<File> mFiles = getFiles(); issueResult.setQuestionname(issueTopic.getContent().toString()); issueResult.setDescribe(issueDescView.getContent().toString()); // issueResult.setStepno(rollingPlan.gets); // issueResult.setStepname(workStep.getStepname()); // issueResult.setWorstepid(workStep.getId()); issueResult.rollingPlanId = rollingPlan.getId(); sIssueManager.createIssue(issueResult, mFiles); super.callCommitBtn(v); } HashSet<File> getHashFileSet(List<File> mList) { HashSet<File> mHashSet = new HashSet<File>(); for (File file : mList) { mHashSet.add(file); } return mHashSet; } private List<File> getFiles() { // TODO Auto-generated method stub List<File> mFileLists = new ArrayList<File>(); for (Category category : mFiles) { if (category.getName() == null) { Log.i(TAG, "no file seleted=" + category.tag); continue; } mFileLists.add(new File(category.getName())); } return mFileLists; } private String getConcerMan() { // TODO Auto-generated method stub String concerman = ""; if (mGuanzhuList.size()==1) { return mGuanzhuList.get(0).getId(); } if (mGuanzhuList.size()>1) { for (int i = 0; i < mGuanzhuList.size(); i++) { Category category = mGuanzhuList.get(i); if (i==0) { concerman += category.getId() ; }else { concerman += "|"+ category.getId(); } } } return concerman; } @Override public void failed(String name, int statusCode, Header[] headers, String response) { // TODO Auto-generated method stub super.failed(name, statusCode, headers, response); } @Override public void succ(String name, int statusCode, Header[] headers, Object response) { // TODO Auto-generated method stub super.succ(name, statusCode, headers, response); showToast("提交成功"); WorkStepFragment.CallSucc(WorkStepFragment.callsucc); setResult(RESULT_OK); finish(); } private void initInfo() { final List<WidgetItemInfo> itemInfos = new ArrayList<WidgetItemInfo>(); // R.id. in array String itemInfos.add(new WidgetItemInfo(null, null, null, 0, false)); createItemListToUI(itemInfos, R.id.edit_container, new CreateItemViewListener() { @Override public View oncreateItem(int index, View convertView, ViewGroup viewgroup) { // TODO Auto-generated method stub // if exsit just update , otherwise create it. final WidgetItemInfo widgetItemInfo = itemInfos .get(index); if (convertView == null) { // create LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate( R.layout.issue_feedback_ui, viewgroup, false); } else { } // bind tag convertView.setTag(widgetItemInfo); return convertView; } }, false); // make container } @Override protected void initView() { setContentView(R.layout.edit_ui);// TODO Auto-generated method stub super.initView(); } @Override public void onProgress(String name, int statusCode, int totalSize, String response) { // TODO Auto-generated method stub if (mFiles.size() > 0) { Log.i(TAG, "progress content = " + response); showProgressDialog("上传图片", response, null); } } }
29.325279
108
0.704126
60a233bbad5e299adc444982757f5d2810bce15e
2,368
package org.erp.tarak.purchaseorder; import java.util.List; import org.erp.tarak.product.Product; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository("purchaseOrderDao") public class PurchaseOrderDaoImpl implements PurchaseOrderDao { @Autowired private SessionFactory sessionFactory; public void addPurchaseOrder(PurchaseOrder purchaseOrder) { if (purchaseOrder.getPurchaseOrderId() > 0) { sessionFactory.getCurrentSession().update(purchaseOrder); } else { sessionFactory.getCurrentSession().save(purchaseOrder); } } @SuppressWarnings("unchecked") public List<PurchaseOrder> listPurchaseOrders(String finYear) { return (List<PurchaseOrder>) sessionFactory.getCurrentSession() .createCriteria(PurchaseOrder.class).add(Restrictions.eq("finYear",finYear)).list(); } public PurchaseOrder getPurchaseOrder(long purchaseOrderId,String finYear) { Criteria crit = sessionFactory.getCurrentSession().createCriteria( PurchaseOrder.class); crit.add(Restrictions.eq("finYear",finYear)); crit.add(Restrictions.eq("purchaseOrderId", purchaseOrderId)); List results = crit.list(); return (PurchaseOrder)results.get(0); } public void deletePurchaseOrder(PurchaseOrder purchaseOrder) { sessionFactory .getCurrentSession() .createQuery( "DELETE FROM PurchaseOrder WHERE purchaseOrderId = " + purchaseOrder.getPurchaseOrderId()+" and finYear='"+purchaseOrder.getFinYear()+"'").executeUpdate(); } @Override public List<PurchaseOrder> listPendingPurchaseOrders(String finYear) { Criteria crit = sessionFactory.getCurrentSession().createCriteria( PurchaseOrder.class); crit.add(Restrictions.eq("finYear",finYear)); crit.add(Restrictions.eq("processed", false)); List results = crit.list(); return results; } @Override public List<PurchaseOrder> listProcessedPurchaseOrders(String finYear) { Criteria crit = sessionFactory.getCurrentSession().createCriteria( PurchaseOrder.class); crit.add(Restrictions.eq("finYear",finYear)); crit.add(Restrictions.eq("processed", true)); List results = crit.list(); return results; } }
33.352113
111
0.750845
76a4ce3509b2a950d3d64471aa430e9ec8b54e18
9,628
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.analyze; import io.crate.data.RowN; import io.crate.metadata.FulltextAnalyzerResolver; import io.crate.planner.PlannerContext; import io.crate.planner.node.ddl.CreateAnalyzerPlan; import io.crate.planner.operators.SubQueryResults; import io.crate.test.integration.CrateDummyClusterServiceUnitTest; import io.crate.testing.SQLExecutor; import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest; import org.elasticsearch.analysis.common.CommonAnalysisPlugin; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.settings.Settings; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import static io.crate.metadata.FulltextAnalyzerResolver.CustomType.ANALYZER; import static io.crate.metadata.FulltextAnalyzerResolver.CustomType.CHAR_FILTER; import static io.crate.metadata.FulltextAnalyzerResolver.CustomType.TOKENIZER; import static io.crate.metadata.FulltextAnalyzerResolver.CustomType.TOKEN_FILTER; import static io.crate.testing.SettingMatcher.hasEntry; import static org.hamcrest.Matchers.allOf; public class CreateAnalyzerAnalyzerTest extends CrateDummyClusterServiceUnitTest { private SQLExecutor e; private PlannerContext plannerContext; @Before public void prepare() throws IOException { e = SQLExecutor.builder(clusterService, 1, Randomness.get(), List.of(new CommonAnalysisPlugin())) .enableDefaultTables() .build(); plannerContext = e.getPlannerContext(clusterService.state()); } private ClusterUpdateSettingsRequest analyze(String stmt, Object... arguments) { AnalyzedCreateAnalyzer analyzedStatement = e.analyze(stmt); return CreateAnalyzerPlan.createRequest( analyzedStatement, plannerContext.transactionContext(), plannerContext.nodeContext(), new RowN(arguments), SubQueryResults.EMPTY, e.fulltextAnalyzerResolver()); } @Test public void testCreateAnalyzerSimple() throws Exception { ClusterUpdateSettingsRequest request = analyze( "CREATE ANALYZER a1 (TOKENIZER lowercase)"); assertThat( extractAnalyzerSettings("a1", request.persistentSettings()), allOf( hasEntry("index.analysis.analyzer.a1.tokenizer", "lowercase"), hasEntry("index.analysis.analyzer.a1.type", "custom") ) ); } @Test public void testCreateAnalyzerWithCustomTokenizer() throws Exception { ClusterUpdateSettingsRequest request = analyze( "CREATE ANALYZER a2 (" + " TOKENIZER tok2 with (" + " type='ngram'," + " \"min_ngram\"=2," + " \"token_chars\"=['letter', 'digits']" + " )" + ")"); assertThat( extractAnalyzerSettings("a2", request.persistentSettings()), allOf( hasEntry("index.analysis.analyzer.a2.tokenizer", "a2_tok2"), hasEntry("index.analysis.analyzer.a2.type", "custom") ) ); var tokenizerSettings = FulltextAnalyzerResolver.decodeSettings( request.persistentSettings().get(TOKENIZER.buildSettingName("a2_tok2"))); assertThat( tokenizerSettings, allOf( hasEntry("index.analysis.tokenizer.a2_tok2.min_ngram", "2"), hasEntry("index.analysis.tokenizer.a2_tok2.type", "ngram"), hasEntry("index.analysis.tokenizer.a2_tok2.token_chars", "[letter, digits]") ) ); } @Test public void testCreateAnalyzerWithCharFilters() throws Exception { ClusterUpdateSettingsRequest request = analyze( "CREATE ANALYZER a3 (" + " TOKENIZER lowercase," + " CHAR_FILTERS (" + " \"html_strip\"," + " my_mapping WITH (" + " type='mapping'," + " mappings=['ph=>f', 'ß=>ss', 'ö=>oe']" + " )" + " )" + ")"); assertThat( extractAnalyzerSettings("a3", request.persistentSettings()), allOf( hasEntry("index.analysis.analyzer.a3.tokenizer", "lowercase"), hasEntry("index.analysis.analyzer.a3.char_filter", "[html_strip, a3_my_mapping]") ) ); var charFiltersSettings = FulltextAnalyzerResolver.decodeSettings( request.persistentSettings().get(CHAR_FILTER.buildSettingName("a3_my_mapping"))); assertThat( charFiltersSettings, allOf( hasEntry("index.analysis.char_filter.a3_my_mapping.mappings", "[ph=>f, ß=>ss, ö=>oe]"), hasEntry("index.analysis.char_filter.a3_my_mapping.type", "mapping") ) ); } @Test public void testCreateAnalyzerWithTokenFilters() throws Exception { ClusterUpdateSettingsRequest request = analyze( "CREATE ANALYZER a11 (" + " TOKENIZER standard," + " TOKEN_FILTERS (" + " lowercase," + " mystop WITH (" + " type='stop'," + " stopword=['the', 'over']" + " )" + " )" + ")"); assertThat( extractAnalyzerSettings("a11", request.persistentSettings()), allOf( hasEntry("index.analysis.analyzer.a11.tokenizer", "standard"), hasEntry("index.analysis.analyzer.a11.filter", "[lowercase, a11_mystop]") ) ); var tokenFiltersSettings = FulltextAnalyzerResolver.decodeSettings( request.persistentSettings().get(TOKEN_FILTER.buildSettingName("a11_mystop"))); assertThat( tokenFiltersSettings, allOf( hasEntry("index.analysis.filter.a11_mystop.type", "stop"), hasEntry("index.analysis.filter.a11_mystop.stopword", "[the, over]") ) ); } @Test public void testCreateAnalyzerExtendingBuiltin() throws Exception { ClusterUpdateSettingsRequest request = analyze( "CREATE ANALYZER a4 EXTENDS " + "german WITH (" + " \"stop_words\"=['der', 'die', 'das']" + ")"); assertThat( extractAnalyzerSettings("a4", request.persistentSettings()), allOf( hasEntry("index.analysis.analyzer.a4.stop_words", "[der, die, das]"), hasEntry("index.analysis.analyzer.a4.type", "german") ) ); } @Test public void createAnalyzerWithoutTokenizer() throws Exception { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("Tokenizer missing from non-extended analyzer"); analyze( "CREATE ANALYZER a6 (" + " TOKEN_FILTERS (" + " lowercase" + " )" + ")"); } @Test public void overrideDefaultAnalyzer() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Overriding the default analyzer is forbidden"); analyze( "CREATE ANALYZER \"default\" (" + " TOKENIZER whitespace" + ")"); } @Test public void overrideBuiltInAnalyzer() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Cannot override builtin analyzer 'keyword'"); analyze( "CREATE ANALYZER \"keyword\" (" + " CHAR_FILTERS (" + " html_strip" + " )," + " TOKENIZER standard" + ")"); } @Test public void missingParameterInCharFilter() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("CHAR_FILTER of type 'mapping' needs additional parameters"); analyze( "CREATE ANALYZER my_mapping_analyzer (" + " CHAR_FILTERS (" + " \"mapping\"" + " )," + " TOKENIZER whitespace" + ")"); } private static Settings extractAnalyzerSettings(String name, Settings persistentSettings) throws IOException { return FulltextAnalyzerResolver .decodeSettings(persistentSettings.get(ANALYZER.buildSettingName(name))); } }
38.206349
114
0.621728
d763c7c715e91c84d15d4d2d79784f00eafebc62
8,398
package com.example.xyzreader.ui; import android.app.Fragment; import android.app.FragmentManager; import android.app.LoaderManager; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v13.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.format.DateUtils; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.xyzreader.R; import com.example.xyzreader.data.ArticleLoader; import com.example.xyzreader.data.ItemsContract; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; /** * An activity representing a single Article detail screen, letting you swipe between articles. */ public class ArticleDetailActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private static final String LOG_TAG = ArticleDetailActivity.class.getSimpleName(); private Cursor mCursor; private long mStartId; private ViewPager mPager; private MyPagerAdapter mPagerAdapter; private ImageView mPhotoView; private TextView mArticleTitleTextView; private TextView mBylineTextView; private FloatingActionButton mShareFab; private Toolbar mToolbar; private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss"); // Use default locale format private SimpleDateFormat outputFormat = new SimpleDateFormat(); // Most time functions can only handle 1902 - 2037 private GregorianCalendar START_OF_EPOCH = new GregorianCalendar(2,1,1); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_article_detail); bindViews(); getLoaderManager().initLoader(0, null, this); mPagerAdapter = new MyPagerAdapter(getFragmentManager()); mPager.setAdapter(mPagerAdapter); mPager.setPageMargin((int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())); mPager.setPageMarginDrawable(new ColorDrawable(0x22000000)); mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageSelected(int position) { if (mCursor != null) { mCursor.moveToPosition(position); } updateLayout(); } @Override public void onPageScrollStateChanged(int state) {} }); if (savedInstanceState == null) { if (getIntent() != null && getIntent().getData() != null) { mStartId = ItemsContract.Items.getItemId(getIntent().getData()); } } } private void bindViews(){ mPager = (ViewPager) findViewById(R.id.pager); mPhotoView = (ImageView) findViewById(R.id.photo); mArticleTitleTextView = (TextView) findViewById(R.id.article_title); mBylineTextView = (TextView) findViewById(R.id.article_byline); mShareFab = (FloatingActionButton) findViewById(R.id.share_fab); mShareFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); String shareText = String.format( getString(R.string.share_text, mArticleTitleTextView.getText().toString())); shareIntent.putExtra(Intent.EXTRA_TEXT, shareText); shareIntent.setType("text/plain"); startActivity(Intent.createChooser( shareIntent, getString(R.string.share_title))); } }); mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void updateLayout(){ if (mCursor != null) { mArticleTitleTextView.setText(mCursor.getString(ArticleLoader.Query.TITLE)); Date publishedDate = parsePublishedDate(); if (!publishedDate.before(START_OF_EPOCH.getTime())) { mBylineTextView.setText(Html.fromHtml( DateUtils.getRelativeTimeSpanString( publishedDate.getTime(), System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL).toString() + " by " + mCursor.getString(ArticleLoader.Query.AUTHOR) + "</font>")); } else { // If date is before 1902, just show the string mBylineTextView.setText(Html.fromHtml( outputFormat.format(publishedDate) + " by <font color='#ffffff'>" + mCursor.getString(ArticleLoader.Query.AUTHOR) + "</font>")); } Glide .with(this).load(mCursor.getString(ArticleLoader.Query.PHOTO_URL)) .error(R.drawable.logo) .centerCrop() .into(mPhotoView); } else { mArticleTitleTextView.setText("N/A"); mBylineTextView.setText("N/A" ); } } private Date parsePublishedDate() { try { String date = mCursor.getString(ArticleLoader.Query.PUBLISHED_DATE); return dateFormat.parse(date); } catch (ParseException ex) { Log.e(LOG_TAG, ex.getMessage()); Log.i(LOG_TAG, "passing today's date"); return new Date(); } } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return ArticleLoader.newAllArticlesInstance(this); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { mCursor = cursor; mPagerAdapter.notifyDataSetChanged(); // Select the start ID if (mStartId > 0) { mCursor.moveToFirst(); // TODO: optimize while (!mCursor.isAfterLast()) { if (mCursor.getLong(ArticleLoader.Query._ID) == mStartId) { final int position = mCursor.getPosition(); mPager.setCurrentItem(position, false); break; } mCursor.moveToNext(); } mStartId = 0; } updateLayout(); } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { mCursor = null; mPagerAdapter.notifyDataSetChanged(); } private class MyPagerAdapter extends FragmentStatePagerAdapter { public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object); ArticleDetailFragment fragment = (ArticleDetailFragment) object; } @Override public Fragment getItem(int position) { mCursor.moveToPosition(position); return ArticleDetailFragment.newInstance(mCursor.getLong(ArticleLoader.Query._ID)); } @Override public int getCount() { return (mCursor != null) ? mCursor.getCount() : 0; } } }
36.513043
103
0.633008
27e6db87360d9c8435c5b4ceeb99041dc0c73b46
168
package org.code4everything.demo.sofarpc.service; /** * @author pantao * @since 2019/10/23 */ public interface SofaService { String sayHello(String string); }
15.272727
49
0.714286
89ec17bd5f6b15154e332c16bf2796e80a0a66b5
2,049
/* Derby - Class org.apache.derby.impl.sql.compile.Level2CostEstimateImpl Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.sql.compile; import org.apache.derby.iapi.sql.compile.CostEstimate; import org.apache.derby.iapi.store.access.StoreCostResult; import org.apache.derby.iapi.services.sanity.SanityManager; import org.apache.derby.impl.sql.compile.CostEstimateImpl; public class Level2CostEstimateImpl extends CostEstimateImpl { public Level2CostEstimateImpl() { } public Level2CostEstimateImpl(double theCost, double theRowCount, double theSingleScanRowCount) { super(theCost, theRowCount, theSingleScanRowCount); } /** @see CostEstimate#cloneMe */ public CostEstimate cloneMe() { return new Level2CostEstimateImpl(cost, rowCount, singleScanRowCount); } public String toString() { return "Level2CostEstimateImpl: at " + hashCode() + ", cost == " + cost + ", rowCount == " + rowCount + ", singleScanRowCount == " + singleScanRowCount; } public CostEstimateImpl setState(double theCost, double theRowCount, CostEstimateImpl retval) { if (retval == null) { retval = new Level2CostEstimateImpl(); } return super.setState(theCost, theRowCount, retval); } }
28.458333
75
0.734993
9abd87953e3f87cf8caa77cc75a6c23e4127f4b7
2,501
package com.selegant.kettle.model; import cn.hutool.core.date.DatePattern; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; @Data @TableName(value = "kettle_repository") public class KettleRepository { /** * ID */ @TableId(value = "repository_id", type = IdType.AUTO) private Integer repositoryId; /** * 资源库名称 */ @TableField(value = "repository_name") private String repositoryName; /** * 登录用户名 */ @TableField(value = "repository_username") private String repositoryUsername; /** * 登录密码 */ @TableField(value = "repository_password") private String repositoryPassword; /** * 资源库数据库类型(MYSQL、ORACLE) */ @TableField(value = "repository_type") private String repositoryType; /** * 资源库数据库访问模式("Native", "ODBC", "OCI", "Plugin", "JNDI") */ @TableField(value = "database_access") private String databaseAccess; /** * 资源库数据库主机名或者IP地址 */ @TableField(value = "database_host") private String databaseHost; /** * 资源库数据库端口号 */ @TableField(value = "database_port") private String databasePort; /** * 资源库数据库名称 */ @TableField(value = "database_name") private String databaseName; /** * 数据库登录账号 */ @TableField(value = "database_username") private String databaseUsername; /** * 数据库登录密码 */ @TableField(value = "database_password") private String databasePassword; /** * 添加时间 */ @TableField(value = "add_time") @JsonFormat(pattern= DatePattern.NORM_DATETIME_PATTERN,timezone = "GMT+8") private Date addTime; /** * 添加者 */ @TableField(value = "add_user") private Integer addUser; /** * 编辑时间 */ @TableField(value = "edit_time") @JsonFormat(pattern= DatePattern.NORM_DATETIME_PATTERN,timezone = "GMT+8") private Date editTime; /** * 编辑者 */ @TableField(value = "edit_user") private Integer editUser; /** * 是否删除(1:存在;0:删除) */ @TableField(value = "del_flag") private Integer delFlag; /** * 是否使用(1:使用;0:未使用) */ @TableField(value = "use_flag") private Integer useFlag; }
20.841667
78
0.626549
d5997a710426f61e84f12a3136118b53d8bc618f
342
package com.sborzenko.materialtoolbarspinner; /** * Created at Magora Systems (http://magora-systems.com) on 08.07.16 * * @author Stanislav S. Borzenko */ public class UserGroup { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
18
68
0.643275
634ebf7d500800e25ce7db39d4e1af9da666982d
22,071
package org.kuse.payloadbuilder.core.parser; import static java.util.Objects.requireNonNull; import static org.apache.commons.lang3.StringUtils.lowerCase; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import org.antlr.v4.runtime.Token; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.kuse.payloadbuilder.core.catalog.TableMeta.DataType; import org.kuse.payloadbuilder.core.codegen.CodeGeneratorContext; import org.kuse.payloadbuilder.core.codegen.ExpressionCode; import org.kuse.payloadbuilder.core.operator.ExecutionContext; import org.kuse.payloadbuilder.core.operator.Tuple; import org.kuse.payloadbuilder.core.utils.MapUtils; /** * Expression of a qualified name type. Column reference with a nested path. Ie. field.subField.value **/ public class QualifiedReferenceExpression extends Expression implements HasIdentifier { private static final Map<DataType, String> TUPLE_ACCESSOR_METHOD = MapUtils.ofEntries( MapUtils.entry(DataType.INT, "getInt"), MapUtils.entry(DataType.LONG, "getLong"), MapUtils.entry(DataType.FLOAT, "getFloat"), MapUtils.entry(DataType.DOUBLE, "getDouble"), MapUtils.entry(DataType.BOOLEAN, "getBool")); private static final ResolvePath[] EMPTY = new ResolvePath[0]; private final QualifiedName qname; /** * <pre> * If this references a lambda parameter, this points to it's unique id in current scope. * Used to retrieve the current lambda value from evaluation context * </pre> */ private final int lambdaId; private final Token token; /** * Mutable property. Temporary until query parser is rewritten to and a 2 pass analyze phase is done that resolves this. */ private ResolvePath[] resolvePaths; public QualifiedReferenceExpression(QualifiedName qname, int lambdaId, Token token) { this.qname = requireNonNull(qname, "qname"); this.lambdaId = lambdaId; this.token = token; } public QualifiedName getQname() { return qname; } public int getLambdaId() { return lambdaId; } public Token getToken() { return token; } /** Set resolve path, will be removed when a 2 phase operator build is in place */ @Deprecated public void setResolvePaths(List<ResolvePath> resolvePaths) { if (this.resolvePaths != null) { return; } requireNonNull(resolvePaths, "resolvePaths"); if (resolvePaths.isEmpty()) { throw new IllegalArgumentException("Empty resolve path"); } this.resolvePaths = resolvePaths.toArray(EMPTY); } @Deprecated public ResolvePath[] getResolvePaths() { return ObjectUtils.defaultIfNull(resolvePaths, EMPTY); } @Override public String identifier() { return qname.getLast(); } @Override public DataType getDataType() { if (resolvePaths == null) { return DataType.ANY; } int size = resolvePaths.length; DataType prev = null; for (int i = 0; i < size; i++) { if (prev == null) { prev = resolvePaths[i].columnType; } else if (prev != resolvePaths[i].columnType) { return DataType.ANY; } } return prev; } @Override public Object eval(ExecutionContext context) { Object value = null; int partIndex = 0; String[] parts = ArrayUtils.EMPTY_STRING_ARRAY; Tuple tuple = context.getStatementContext().getTuple(); // Expression mode / test mode // We have no resolve path, simply use the full qualified name as column if (resolvePaths == null) { parts = qname.getParts().toArray(ArrayUtils.EMPTY_STRING_ARRAY); if (lambdaId >= 0) { value = context.getStatementContext().getLambdaValue(lambdaId); partIndex++; } else if (tuple != null) { int ordinal = tuple.getColumnOrdinal(lowerCase(parts[partIndex++])); value = tuple.getValue(ordinal); } } else { if (lambdaId >= 0) { value = context.getStatementContext().getLambdaValue(lambdaId); // If the lambda value was a Tuple, set tuple field // else null it to not resolve further down //CSOFF if (value instanceof Tuple) //CSON { tuple = (Tuple) value; } else { tuple = null; } } // TODO: sorceTupleOrdinal ResolvePath path = resolvePaths[0]; parts = path.unresolvedPath; if (tuple != null) { value = resolve(tuple, path); //CSOFF if (value instanceof Tuple) //CSON { value = resolveValue((Tuple) value, path, partIndex); } partIndex++; } } if (value == null || partIndex >= parts.length) { return value; } if (value instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) value; return MapUtils.traverse(map, partIndex, parts); } throw new IllegalArgumentException("Cannot dereference value " + value); } @Override public <TR, TC> TR accept(ExpressionVisitor<TR, TC> visitor, TC context) { return visitor.visit(this, context); } @Override public boolean isCodeGenSupported() { if (resolvePaths == null || lambdaId >= 0 || resolvePaths.length != 1 || resolvePaths[0].subTupleOrdinals.length != 0 // Multi part path ie. map access etc. not supported yet || resolvePaths[0].unresolvedPath.length > 1 // Tuple access not supported yet || (resolvePaths[0].unresolvedPath.length == 0 && resolvePaths[0].columnOrdinal == -1)) { return false; } return true; } //CSOFF @Override //CSON public ExpressionCode generateCode(CodeGeneratorContext context) { ExpressionCode code = context.getExpressionCode(); // TODO: lambda // TODO: only supported for single source tuple ordinals for now // TODO: map access etc. int targetOrdinal = -1; String column = lowerCase(qname.toString()); int columnOrdinal = -1; DataType type = DataType.ANY; if (resolvePaths != null) { targetOrdinal = resolvePaths[0].targetTupleOrdinal; columnOrdinal = resolvePaths[0].columnOrdinal; if (columnOrdinal == -1) { column = resolvePaths[0].unresolvedPath[0]; } type = resolvePaths[0].columnType; } String typeMethod = TUPLE_ACCESSOR_METHOD.get(type); // Special get-methods on tuple (getInt, getFloat etc.) if (typeMethod != null) { if (targetOrdinal == -1) { /* tupleOrdinal == -1 * * <primitive> v_X = <default>; * boolean isNull_X = true; * { * int c = tuple.getColumnOrdinal(-1, "col"); * isNull_X = c >= 0 ? tuple.isNull(c) : true; * v_X = isNull_x ? v_X : tuple.get<Primitive>(-1, c); * } */ code.setCode(String.format("//%s\n" // qname + "%s %s = %s;\n" // dataType, resVar, defaultDataType + "boolean %s = true;\n" // nullVar + "{\n" + " int c = %s;\n" // columnOrdinal or tuple.getColumnOrdinal(-1, \"%s\"), column + " %s = c >= 0 ? %s.isNull(c) : true;\n" // nullVar, context tupleVar + " %s = %s ? %s : %s.%s(c);\n" // resVar, nullVar, resVar, context tupleVar, dataType (capitalize) + "}\n", qname, type.getJavaTypeString(), code.getResVar(), type.getJavaDefaultValue(), code.getNullVar(), columnOrdinal >= 0 ? columnOrdinal : String.format("%s.getColumnOrdinal(\"%s\")", context.getTupleFieldName(), column), code.getNullVar(), context.getTupleFieldName(), code.getResVar(), code.getNullVar(), code.getResVar(), context.getTupleFieldName(), typeMethod)); } else { /* * tupleOrdinal >= 0 * * Object t_v_X = tuple.getTuple(targetOrdinal); * boolean isNull_X = true; * <primitive> v_X = <default>; * if (t_v_X instanceof Tuple) * { * int c = ((Tuple) t_v_X).getColumnOrdinal(targetOrdinal, "col"); * isNull_X = c >= 0 ? ((Tuple) t_v_X).isNull(c) : true; * v_x = isNull_x ? v_x : ((Tuple) t_v_X).get<Primitive>(targetOrdinal, c); * } */ String tupleVar = "t_" + code.getResVar(); code.setCode(String.format("//%s\n" + "Tuple %s = %s.getTuple(%d);\n" // tupleVar, context tupleVar, targetOrdinal + "boolean %s = true;\n" // nullVar + "%s %s = %s;\n" // dataType, resVar, defaultValue + "if (%s != null)\n" // tupleVar + "{\n" + " int c = %s;\n" // columnOrdinal else ((Tuple) %s).getColumnOrdinal(\"%s\") => tupleVar, targetOrdinal, columnName + " %s = c >= 0 ? %s.isNull(c) : true;\n" // nullvar, tupleVar + " %s = %s ? %s : %s.%s(c);\n" // resVar, nullVar, resVar, tupleVar, dataType (capitalize) + "}\n", qname, tupleVar, context.getTupleFieldName(), targetOrdinal, code.getNullVar(), type.getJavaTypeString(), code.getResVar(), type.getJavaDefaultValue(), tupleVar, columnOrdinal >= 0 ? columnOrdinal : String.format("%s.getColumnOrdinal(\"%s\")", tupleVar, column), code.getNullVar(), tupleVar, code.getResVar(), code.getNullVar(), code.getResVar(), tupleVar, typeMethod)); } } else if (targetOrdinal == -1) { /* tupleOrdinal == -1 * * Object v_X = null; * boolean isNull_X = true; * { * int c = tuple.getColumnOrdinal(-1, "col"); * v_X = c >= 0 ? tuple.getValue(-1, c) : null; * isNull_X = v_X == null; * } */ code.setCode(String.format("//%s\n" // qname + "Object %s = null;\n" // resVar + "boolean %s = true;\n" // nullVar + "{\n" + " int c = %s;\n" // columnOrdinal or tuple.getColumnOrdinal(-1, \"%s\"), column + " %s = c >= 0 ? %s.getValue(c) : null;\n" // resVar, context tupleVar + " %s = %s == null;\n" // nullVar, resVar + "}\n", qname, code.getResVar(), code.getNullVar(), columnOrdinal >= 0 ? columnOrdinal : String.format("%s.getColumnOrdinal(\"%s\")", context.getTupleFieldName(), column), code.getResVar(), context.getTupleFieldName(), code.getNullVar(), code.getResVar())); } else { /* * tupleOrdinal >= 0 * * Object t_v_X = tuple.getTuple(targetOrdinal); * boolean isNull_X = true; * Object v_X = null; * if (t_v_X instanceof Tuple) * { * int c = ((Tuple) t_v_X).getColumnOrdinal(targetOrdinal, "col"); * v_X = c >= 0 ? tuple.getValue(-1, c) : null; * isNull_X = v_X == null; * } */ String tupleVar = "t_" + code.getResVar(); code.setCode(String.format("//%s\n" + "Tuple %s = %s.getTuple(%d);\n" // tupleVar, context tupleVar, targetOrdinal + "boolean %s = true;\n" // nullVar + "Object %s = null;\n" // resVar + "if (%s != null)\n" // tupleVar + "{\n" + " int c = %s;\n" // columnOrdinal else ((Tuple) %s).getColumnOrdinal(\"%s\") => tupleVar, columnName + " %s = c >= 0 ? %s.getValue(c) : null;\n" // resVar, tupleVar + " %s = %s == null;\n" // nullvar, resVar + "}\n", qname, tupleVar, context.getTupleFieldName(), targetOrdinal, code.getNullVar(), code.getResVar(), tupleVar, columnOrdinal >= 0 ? columnOrdinal : String.format("%s.getColumnOrdinal(\"%s\")", tupleVar, column), code.getResVar(), tupleVar, code.getNullVar(), code.getResVar())); } return code; } /** Traverses to the target tuple with provided path */ private Object resolve(Tuple tuple, ResolvePath path) { Object result = tuple; if (path.targetTupleOrdinal >= 0) { result = tuple.getTuple(path.targetTupleOrdinal); } if (result == null) { return null; } if (path.subTupleOrdinals.length > 0) { int length = path.subTupleOrdinals.length; for (int i = 0; i < length; i++) { result = getTuple(result).getSubTuple(path.subTupleOrdinals[i]); if (result == null) { return null; } } } return result; } private Tuple getTuple(Object obj) { if (obj != null && !(obj instanceof Tuple)) { throw new IllegalArgumentException("Expected a Tuple but got " + obj); } return (Tuple) obj; } /** Resolves value from provided with with provided path */ private Object resolveValue(Tuple tuple, ResolvePath path, int partIndex) { // Nothing more to resolve here return tuple if (tuple == null || (path.columnOrdinal == -1 && path.unresolvedPath.length == 0)) { return tuple; } // Get value for first part int ordinal = path.columnOrdinal >= 0 ? path.columnOrdinal : tuple.getColumnOrdinal(path.unresolvedPath[partIndex]); return tuple.getValue(ordinal); } @Override public int hashCode() { return qname.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof QualifiedReferenceExpression) { QualifiedReferenceExpression that = (QualifiedReferenceExpression) obj; return qname.equals(that.qname) && lambdaId == that.lambdaId; // && Objects.equals(resolvePaths, that.resolvePaths); } return false; } @Override public String toString() { return qname.toString(); } /** * Resolve information for a qualified reference - An optional pointer to an tuple ordinal - Unresolved path **/ public static class ResolvePath { /** * The source tuple ordinal that this path refers to. In case this qualifier is part of a multi tuple ordinal expression this value specifies * if the path to use when the source tuple ordinal matches * * <pre> * ie. unionall(aliasA, aliasB).map(x -> x.aliasC.id) * * Here the reference x.aliasC.id is pointing to both aliasA and aliasB * so depending on which one we get runtime we will end up with different target * tuple ordinals for x.aliasC * </pre> */ final int sourceTupleOrdinal; /** * The target tuple ordinal that this path refers to. */ final int targetTupleOrdinal; /** * Any left over path that needs to be resolved. * * <pre> * ie. aliasA.aliasB.col.key.subkey * * We found a target tuple ordinal for aliasA.aliasB * then we have col.key.subkey left to resolve runtime from the target tuple * </pre> */ final String[] unresolvedPath; /** Pre defined column ordinal. Typically a computed expression or similar */ final int columnOrdinal; /** When resolved into a temp tables sub alias, this ordinal points to it */ final int[] subTupleOrdinals; /** Column type if any */ final DataType columnType; public ResolvePath(ResolvePath source, List<String> unresolvedPath) { this(source.sourceTupleOrdinal, source.targetTupleOrdinal, unresolvedPath, source.columnOrdinal, source.subTupleOrdinals, null); } public ResolvePath(int sourceTupleOrdinal, int targetTupleOrdinal, List<String> unresolvedPath, int columnOrdinal) { this(sourceTupleOrdinal, targetTupleOrdinal, unresolvedPath, columnOrdinal, ArrayUtils.EMPTY_INT_ARRAY, null); } public ResolvePath(int sourceTupleOrdinal, int targetTupleOrdinal, List<String> unresolvedPath, int columnOrdinal, DataType columnType) { this(sourceTupleOrdinal, targetTupleOrdinal, unresolvedPath, columnOrdinal, ArrayUtils.EMPTY_INT_ARRAY, columnType); } public ResolvePath(int sourceTupleOrdinal, int targetTupleOrdinal, List<String> unresolvedPath, int columnOrdinal, int[] subTupleOrdinals) { this(sourceTupleOrdinal, targetTupleOrdinal, unresolvedPath, columnOrdinal, subTupleOrdinals, null); } public ResolvePath(int sourceTupleOrdinal, int targetTupleOrdinal, List<String> unresolvedPath, int columnOrdinal, int[] subTupleOrdinals, DataType columnType) { this.sourceTupleOrdinal = sourceTupleOrdinal; this.targetTupleOrdinal = targetTupleOrdinal; this.unresolvedPath = requireNonNull(unresolvedPath, "unresolvedPath").toArray(ArrayUtils.EMPTY_STRING_ARRAY); this.columnOrdinal = columnOrdinal; this.subTupleOrdinals = subTupleOrdinals; this.columnType = columnType != null ? columnType : DataType.ANY; } public int getSourceTupleOrdinal() { return sourceTupleOrdinal; } public int getTargetTupleOrdinal() { return targetTupleOrdinal; } public String[] getUnresolvedPath() { return unresolvedPath; } @Override public int hashCode() { return Objects.hash(sourceTupleOrdinal, targetTupleOrdinal); } @Override public boolean equals(Object obj) { if (obj instanceof ResolvePath) { ResolvePath that = (ResolvePath) obj; return sourceTupleOrdinal == that.sourceTupleOrdinal && targetTupleOrdinal == that.targetTupleOrdinal && columnOrdinal == that.columnOrdinal && Arrays.equals(unresolvedPath, that.unresolvedPath) && Arrays.equals(subTupleOrdinals, that.subTupleOrdinals); } return false; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } } }
37.728205
176
0.502333
e08e99d84bdbebb5abf4d5224e282d3a8e073b31
547
package com.kingdee.patchcheck.service; import com.kingdee.patchcheck.model.Item; import com.kingdee.patchcheck.model.User; import com.kingdee.patchcheck.model.patchLog; import org.springframework.data.domain.Page; import java.util.List; import java.util.Optional; /** * description: IlogService <br> * date: 2020\2\4 0008 15:26 <br> * author: Administrator <br> * version: 1.0 <br> * 日志业务逻辑层 */ public interface IlogService { public Page<patchLog> getpatchlog(); public Page<patchLog> getpatchlog(Integer page, Integer size); }
23.782609
66
0.749543
b4545f2012c1bcd109e7a3376786dffec6f4bb6d
1,959
package com.example.springbootshiro.controller; import com.example.springbootshiro.constants.CommonConstants; import com.example.springbootshiro.domain.vo.ResponseVO; import com.example.springbootshiro.enums.ResponseStatusEnum; import com.example.springbootshiro.utils.ResultUtil; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.UnauthorizedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.lang.reflect.UndeclaredThrowableException; /** * 统一异常处理类<br> * 捕获程序所有异常,针对不同异常,采取不同的处理方式 */ @ControllerAdvice public class ExceptionHandleController { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandleController.class); // @ResponseBody @ExceptionHandler(UnauthorizedException.class) public String handleShiroException(Exception ex) { return "redirect:/error/403"; } // @ResponseBody @ExceptionHandler(AuthorizationException.class) public String AuthorizationException(Exception ex) { return "redirect:/error/401"; } @ExceptionHandler(value = Exception.class) @ResponseBody public ResponseVO handle(Throwable e) { e.printStackTrace(); // 打印异常栈 if (e instanceof UndeclaredThrowableException) { e = ((UndeclaredThrowableException) e).getUndeclaredThrowable(); } ResponseStatusEnum responseStatus = ResponseStatusEnum.getResponseStatus(e.getMessage()); if (responseStatus != null) { LOGGER.error(responseStatus.getMessage()); return ResultUtil.error(responseStatus.getCode(), responseStatus.getMessage()); } return ResultUtil.error(CommonConstants.DEFAULT_ERROR_CODE, ResponseStatusEnum.ERROR.getMessage()); } }
36.962264
107
0.759571
44dadddd3294a1cfad8e70e1570ea67e2524093a
6,173
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.environment.commands; import com.google.inject.Inject; import io.github.nucleuspowered.nucleus.modules.environment.EnvironmentKeys; import io.github.nucleuspowered.nucleus.modules.environment.EnvironmentPermissions; import io.github.nucleuspowered.nucleus.modules.environment.config.EnvironmentConfig; import io.github.nucleuspowered.nucleus.modules.environment.parameter.WeatherParameter; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandExecutor; import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandResult; import io.github.nucleuspowered.nucleus.core.scaffold.command.NucleusParameters; import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.Command; import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.CommandModifier; import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.EssentialsEquivalent; import io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.CommandModifiers; import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection; import io.github.nucleuspowered.nucleus.core.services.interfaces.IMessageProviderService; import io.github.nucleuspowered.nucleus.core.services.interfaces.IReloadableService; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.exception.CommandException; import org.spongepowered.api.command.parameter.Parameter; import org.spongepowered.api.registry.RegistryTypes; import org.spongepowered.api.scheduler.Task; import org.spongepowered.api.util.Ticks; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.api.world.weather.WeatherType; import java.time.Duration; import java.util.Optional; @EssentialsEquivalent({"thunder", "sun", "weather", "sky", "storm", "rain"}) @Command( aliases = {"weather"}, basePermission = EnvironmentPermissions.BASE_WEATHER, commandDescriptionKey = "weather", modifiers = { @CommandModifier(value = CommandModifiers.HAS_COOLDOWN, exemptPermission = EnvironmentPermissions.EXEMPT_COOLDOWN_WEATHER), @CommandModifier(value = CommandModifiers.HAS_WARMUP, exemptPermission = EnvironmentPermissions.EXEMPT_WARMUP_WEATHER), @CommandModifier(value = CommandModifiers.HAS_COST, exemptPermission = EnvironmentPermissions.EXEMPT_COST_WEATHER) }, associatedPermissions = EnvironmentPermissions.WEATHER_EXEMPT_LENGTH ) public class WeatherCommand implements ICommandExecutor, IReloadableService.Reloadable { private final Parameter.Value<WeatherType> weatherParameter; @Inject public WeatherCommand(final IMessageProviderService messageProviderService) { this.weatherParameter = Parameter.builder(WeatherType.class) .addParser(new WeatherParameter(messageProviderService)) .key("weather") .build(); } private long max = Long.MAX_VALUE; @Override public void onReload(final INucleusServiceCollection serviceCollection) { this.max = serviceCollection.configProvider().getModuleConfig(EnvironmentConfig.class).getMaximumWeatherTimespan(); } @Override public Parameter[] parameters(final INucleusServiceCollection serviceCollection) { return new Parameter[] { NucleusParameters.ONLINE_WORLD_OPTIONAL, this.weatherParameter, NucleusParameters.OPTIONAL_DURATION }; } @Override public ICommandResult execute(final ICommandContext context) throws CommandException { // We can predict the weather on multiple worlds now! final ServerWorld w = context.getWorldPropertiesOrFromSelf(NucleusParameters.ONLINE_WORLD_OPTIONAL); // Get whether we locked the weather. if (context.getServiceCollection().storageManager().getWorldOnThread(w.key()) .map(x -> x.get(EnvironmentKeys.LOCKED_WEATHER).orElse(false)).orElse(false)) { // Tell the user to unlock first. return context.errorResult("command.weather.locked", w.key().asString()); } // Houston, we have a world! Now, what was the forecast? final WeatherType we = context.requireOne(this.weatherParameter); // Have we gotten an accurate forecast? Do we know how long this weather spell will go on for? final Optional<Long> oi = context.getOne(NucleusParameters.OPTIONAL_DURATION).map(Duration::getSeconds); // Even weather masters have their limits. Sometimes. if (this.max > 0 && oi.orElse(Long.MAX_VALUE) > this.max && !context.testPermission(EnvironmentPermissions.WEATHER_EXEMPT_LENGTH)) { return context.errorResult("command.weather.toolong", context.getTimeString(this.max)); } if (oi.isPresent()) { // YES! I should get a job at the weather service and show them how it's done! Sponge.server().scheduler().submit(Task.builder() .execute(() -> w.setWeather(we, Ticks.ofWallClockSeconds(Sponge.server(), oi.get().intValue()))) .plugin(context.getServiceCollection().pluginContainer()).build()); context.sendMessage("command.weather.time", we.key(RegistryTypes.WEATHER_TYPE).asString(), w.key().asString(), context.getTimeString(oi.get())); } else { // No, probably because I've already gotten a job at the weather service... Sponge.server().scheduler().submit( Task.builder().execute(() -> w.setWeather(we)).plugin(context.getServiceCollection().pluginContainer()).build() ); context.sendMessage("command.weather.set", we.key(RegistryTypes.WEATHER_TYPE).asString(), w.key().asString()); } // The weather control device has been activated! return context.successResult(); } }
52.313559
140
0.734003
4d46bab6ba778e5a91ec7808683c49d39cf7af25
3,778
/* Copyright (c) 2010, NHIN Direct Project All rights reserved. Authors: Greg Meyer gm2552@cerner.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the The NHIN Direct Project (nhindirect.org). nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.nhindirect.stagent.cert.tools.certgen; import java.io.File; import java.security.Key; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Map; /** * Container for fields related to generating certificates. * @author Greg Meyer * */ ///CLOVER:OFF public class CertCreateFields { private Map<String, Object> attributes; private File newCertFile; private File newKeyFile; private char[] newPassword; private int expDays; private int keyStrength; private X509Certificate signerCert; private Key signerKey; public CertCreateFields(Map<String, Object> attributes, File newCertFile, File newKeyFile, char[] newPassword, int expDays, int keyStrength, X509Certificate signerCert, Key signerKey) { this.attributes = attributes; this.newCertFile = newCertFile; this.newKeyFile = newKeyFile; this.newPassword = newPassword; this.expDays = expDays; this.keyStrength = keyStrength; this.signerCert = signerCert; this.signerKey = signerKey; } public Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } public File getNewCertFile() { return newCertFile; } public File getNewKeyFile() { return newKeyFile; } public char[] getNewPassword() { return newPassword; } public int getExpDays() { return expDays; } public int getKeyStrength() { return keyStrength; } public X509Certificate getSignerCert() { return signerCert; } public Key getSignerKey() { return signerKey; } public void setAttributes(Map<String, Object> attributes) { this.attributes = attributes; } public void setNewCertFile(File newCertFile) { this.newCertFile = newCertFile; } public void setNewKeyFile(File newKeyFile) { this.newKeyFile = newKeyFile; } public void setNewPassword(char[] newPassword) { this.newPassword = newPassword; } public void setExpDays(int expDays) { this.expDays = expDays; } public void setKeyStrength(int keyStrength) { this.keyStrength = keyStrength; } public void setSignerCert(X509Certificate signerCert) { this.signerCert = signerCert; } public void setSignerKey(Key signerKey) { this.signerKey = signerKey; } } ///CLOVER:ON
30.224
151
0.772102
05991453217eca53f34e20f1825a507a499a7254
712
package stone; public class Token { public static final Token EOF = new Token(-1); public static final String EOL = "\\n"; private int lineNumber; public static class TokenTypeMismatchException extends RuntimeException { public TokenTypeMismatchException(String string) { super(string); } } public Token(int lineNo) { this.lineNumber = lineNo; } public int getLineNumber() { return lineNumber; } public boolean isIdentifer() { return false; } public boolean isNumber() { return false; } public boolean isString() { return false; } public int getNumber() { throw new TokenTypeMismatchException("not number token"); } public String getText() { return ""; } }
14.833333
74
0.699438
51cc737cf046da5710cb384d2785ae3fa9677ead
1,800
/** * Copyright 2011 Perforce Software Inc., All Rights Reserved. */ package com.perforce.p4java.env; /** * Provides system information about the Java runtime environment */ public class SystemInfo { public static boolean isWindows() { return (getOsName().toLowerCase().startsWith("windows")); } public static boolean isMac() { return (getOsName().toLowerCase().startsWith("mac") || getOsName() .toLowerCase().startsWith("darwin")); } public static boolean isLinux() { return (getOsName().toLowerCase().startsWith("linux")); } public static boolean isUnix() { // Linux if (isLinux()) { return true; } // Solaris or SUN OS if (getOsName().toLowerCase().startsWith("solaris") || getOsName().toLowerCase().startsWith("sunos")) { return true; } // Mac OS X if (getOsName().toLowerCase().indexOf("mac os x") != -1) { return true; } // FreeBSD, NetBSD or OpenBSD if (getOsName().toLowerCase().startsWith("freebsd") || getOsName().toLowerCase().startsWith("netbsd") || getOsName().toLowerCase().startsWith("openbsd")) { return true; } // AIX if (getOsName().toLowerCase().startsWith("aix")) { return true; } // HP-UX if (getOsName().toLowerCase().startsWith("hp-ux")) { return true; } // IRIX if (getOsName().toLowerCase().startsWith("irix")) { return true; } return false; } public static String getOsName() { return System.getProperty("os.name"); } public static String getOsVersion() { return System.getProperty("os.version"); } public static String getOsArch() { return System.getProperty("os.arch"); } public static String getFileSeparator() { return System.getProperty("file.separator"); } public static String getUserHome() { return System.getProperty("user.home"); } }
22.5
68
0.663889
75fbf739e2f404b42571a506072b02ff490fb941
39,927
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassCodeVisitorSupport; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.VariableScope; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.BitwiseNegationExpression; import org.codehaus.groovy.ast.expr.ClosureExpression; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.ConstructorCallExpression; import org.codehaus.groovy.ast.expr.DeclarationExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.PostfixExpression; import org.codehaus.groovy.ast.expr.PrefixExpression; import org.codehaus.groovy.ast.expr.StaticMethodCallExpression; import org.codehaus.groovy.ast.expr.TupleExpression; import org.codehaus.groovy.ast.expr.UnaryMinusExpression; import org.codehaus.groovy.ast.expr.UnaryPlusExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.BlockStatement; import org.codehaus.groovy.ast.stmt.DoWhileStatement; import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.stmt.IfStatement; import org.codehaus.groovy.ast.stmt.ReturnStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.stmt.WhileStatement; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.BytecodeInterface8; import org.codehaus.groovy.syntax.Types; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static org.codehaus.groovy.ast.ClassHelper.BigDecimal_TYPE; import static org.codehaus.groovy.ast.ClassHelper.GROOVY_INTERCEPTABLE_TYPE; import static org.codehaus.groovy.ast.ClassHelper.OBJECT_TYPE; import static org.codehaus.groovy.ast.ClassHelper.boolean_TYPE; import static org.codehaus.groovy.ast.ClassHelper.double_TYPE; import static org.codehaus.groovy.ast.ClassHelper.int_TYPE; import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveType; import static org.codehaus.groovy.ast.ClassHelper.long_TYPE; import static org.codehaus.groovy.ast.tools.ParameterUtils.parametersEqual; import static org.codehaus.groovy.ast.tools.WideningCategories.isBigDecCategory; import static org.codehaus.groovy.ast.tools.WideningCategories.isDoubleCategory; import static org.codehaus.groovy.ast.tools.WideningCategories.isFloatingCategory; import static org.codehaus.groovy.ast.tools.WideningCategories.isIntCategory; import static org.codehaus.groovy.ast.tools.WideningCategories.isLongCategory; import static org.codehaus.groovy.classgen.asm.BinaryExpressionMultiTypeDispatcher.typeMap; import static org.codehaus.groovy.classgen.asm.BinaryExpressionMultiTypeDispatcher.typeMapKeyNames; import static org.objectweb.asm.Opcodes.ACC_FINAL; import static org.objectweb.asm.Opcodes.GETSTATIC; import static org.objectweb.asm.Opcodes.GOTO; import static org.objectweb.asm.Opcodes.IFEQ; import static org.objectweb.asm.Opcodes.IFNE; import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; public class OptimizingStatementWriter extends StatementWriter { // values correspond to BinaryExpressionMultiTypeDispatcher.typeMapKeyNames private static final MethodCaller[] guards = { null, MethodCaller.newStatic(BytecodeInterface8.class, "isOrigInt"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigL"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigD"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigC"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigB"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigS"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigF"), MethodCaller.newStatic(BytecodeInterface8.class, "isOrigZ"), }; private static final MethodCaller disabledStandardMetaClass = MethodCaller.newStatic(BytecodeInterface8.class, "disabledStandardMetaClass"); private final WriterController controller; private boolean fastPathBlocked; public OptimizingStatementWriter(final WriterController controller) { super(controller); this.controller = controller; } private FastPathData writeGuards(final StatementMeta meta, final Statement statement) { if (fastPathBlocked || controller.isFastPath() || meta == null || !meta.optimize) return null; controller.getAcg().onLineNumber(statement, null); MethodVisitor mv = controller.getMethodVisitor(); FastPathData fastPathData = new FastPathData(); Label slowPath = new Label(); for (int i = 0, n = guards.length; i < n; i += 1) { if (meta.involvedTypes[i]) { guards[i].call(mv); mv.visitJumpInsn(IFEQ, slowPath); } } // meta class check with boolean holder String owner = BytecodeHelper.getClassInternalName(controller.getClassNode()); MethodNode mn = controller.getMethodNode(); if (mn != null) { mv.visitFieldInsn(GETSTATIC, owner, Verifier.STATIC_METACLASS_BOOL, "Z"); mv.visitJumpInsn(IFNE, slowPath); } // standard metaclass check disabledStandardMetaClass.call(mv); mv.visitJumpInsn(IFNE, slowPath); // other guards here mv.visitJumpInsn(GOTO, fastPathData.pathStart); mv.visitLabel(slowPath); return fastPathData; } private void writeFastPathPrelude(final FastPathData meta) { MethodVisitor mv = controller.getMethodVisitor(); mv.visitJumpInsn(GOTO, meta.afterPath); mv.visitLabel(meta.pathStart); controller.switchToFastPath(); } private void writeFastPathEpilogue(final FastPathData meta) { MethodVisitor mv = controller.getMethodVisitor(); mv.visitLabel(meta.afterPath); controller.switchToSlowPath(); } @Override public void writeBlockStatement(final BlockStatement statement) { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); FastPathData fastPathData = writeGuards(meta, statement); if (fastPathData == null) { // normal mode with different paths // important is to not to have a fastpathblock here, // otherwise the per expression statement improvement // is impossible super.writeBlockStatement(statement); } else { // fast/slow path generation boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeBlockStatement(statement); fastPathBlocked = oldFastPathBlock; writeFastPathPrelude(fastPathData); super.writeBlockStatement(statement); writeFastPathEpilogue(fastPathData); } } @Override public void writeDoWhileLoop(final DoWhileStatement statement) { if (controller.isFastPath()) { super.writeDoWhileLoop(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeDoWhileLoop(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeDoWhileLoop(statement); writeFastPathEpilogue(fastPathData); } } @Override protected void writeIteratorHasNext(final MethodVisitor mv) { if (controller.isFastPath()) { mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "hasNext", "()Z", true); } else { super.writeIteratorHasNext(mv); } } @Override protected void writeIteratorNext(final MethodVisitor mv) { if (controller.isFastPath()) { mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "next", "()Ljava/lang/Object;", true); } else { super.writeIteratorNext(mv); } } @Override protected void writeForInLoop(final ForStatement statement) { if (controller.isFastPath()) { super.writeForInLoop(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeForInLoop(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeForInLoop(statement); writeFastPathEpilogue(fastPathData); } } @Override protected void writeForLoopWithClosureList(final ForStatement statement) { if (controller.isFastPath()) { super.writeForLoopWithClosureList(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeForLoopWithClosureList(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeForLoopWithClosureList(statement); writeFastPathEpilogue(fastPathData); } } @Override public void writeWhileLoop(final WhileStatement statement) { if (controller.isFastPath()) { super.writeWhileLoop(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeWhileLoop(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeWhileLoop(statement); writeFastPathEpilogue(fastPathData); } } @Override public void writeIfElse(final IfStatement statement) { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); FastPathData fastPathData = writeGuards(meta, statement); if (fastPathData == null) { super.writeIfElse(statement); } else { boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeIfElse(statement); fastPathBlocked = oldFastPathBlock; writeFastPathPrelude(fastPathData); super.writeIfElse(statement); writeFastPathEpilogue(fastPathData); } } @Override public void writeReturn(final ReturnStatement statement) { if (controller.isFastPath()) { super.writeReturn(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); if (isNewPathFork(meta) && writeDeclarationExtraction(statement)) { if (meta.declaredVariableExpression != null) { // declaration was replaced by assignment so we need to define the variable controller.getCompileStack().defineVariable(meta.declaredVariableExpression, false); } FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeReturn(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeReturn(statement); writeFastPathEpilogue(fastPathData); } else { super.writeReturn(statement); } } } @Override public void writeExpressionStatement(final ExpressionStatement statement) { if (controller.isFastPath()) { super.writeExpressionStatement(statement); } else { StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); // we have to have handle DelcarationExpressions special, since their // entry should be outside the optimization path, we have to do that of // course only if we are actually going to do two different paths, // otherwise it is not needed // // there are several cases to be considered now. // (1) no fast path possible, so just do super // (2) fast path possible, and at path split point (meaning not in // fast path and not in slow path). Here we have to extract the // Declaration and replace by an assignment // (3) fast path possible and in slow or fastPath. Nothing to do here. // // the only case we need to handle is then (2). if (isNewPathFork(meta) && writeDeclarationExtraction(statement)) { if (meta.declaredVariableExpression != null) { // declaration was replaced by assignment so we need to define the variable controller.getCompileStack().defineVariable(meta.declaredVariableExpression, false); } FastPathData fastPathData = writeGuards(meta, statement); boolean oldFastPathBlock = fastPathBlocked; fastPathBlocked = true; super.writeExpressionStatement(statement); fastPathBlocked = oldFastPathBlock; if (fastPathData == null) return; writeFastPathPrelude(fastPathData); super.writeExpressionStatement(statement); writeFastPathEpilogue(fastPathData); } else { super.writeExpressionStatement(statement); } } } private boolean writeDeclarationExtraction(final Statement statement) { Expression ex = null; if (statement instanceof ReturnStatement) { ReturnStatement rs = (ReturnStatement) statement; ex = rs.getExpression(); } else if (statement instanceof ExpressionStatement) { ExpressionStatement es = (ExpressionStatement) statement; ex = es.getExpression(); } else { throw new GroovyBugError("unknown statement type :" + statement.getClass()); } if (!(ex instanceof DeclarationExpression)) return true; DeclarationExpression declaration = (DeclarationExpression) ex; ex = declaration.getLeftExpression(); if (ex instanceof TupleExpression) return false; // stash declared variable in case we do subsequent visits after we // change to assignment only StatementMeta meta = statement.getNodeMetaData(StatementMeta.class); if (meta != null) { meta.declaredVariableExpression = declaration.getVariableExpression(); } // change statement to do assignment only BinaryExpression assignment = new BinaryExpression( declaration.getLeftExpression(), declaration.getOperation(), declaration.getRightExpression()); assignment.setSourcePosition(declaration); assignment.copyNodeMetaData(declaration); // replace statement code if (statement instanceof ReturnStatement) { ReturnStatement rs = (ReturnStatement) statement; rs.setExpression(assignment); } else if (statement instanceof ExpressionStatement) { ExpressionStatement es = (ExpressionStatement) statement; es.setExpression(assignment); } else { throw new GroovyBugError("unknown statement type :" + statement.getClass()); } return true; } private boolean isNewPathFork(final StatementMeta meta) { // meta.optimize -> can do fast path if (meta == null || !meta.optimize) return false; // fastPathBlocked -> slow path if (fastPathBlocked) return false; // controller.isFastPath() -> fastPath return !controller.isFastPath(); } public static void setNodeMeta(final TypeChooser chooser, final ClassNode classNode) { if (classNode.getNodeMetaData(ClassNodeSkip.class) != null) return; new OptVisitor(chooser).visitClass(classNode); } private static StatementMeta addMeta(final ASTNode node) { StatementMeta meta = node.getNodeMetaData(StatementMeta.class, x -> new StatementMeta()); meta.optimize = true; return meta; } private static StatementMeta addMeta(final ASTNode node, final OptimizeFlagsCollector opt) { StatementMeta meta = addMeta(node); meta.chainInvolvedTypes(opt); return meta; } //-------------------------------------------------------------------------- public static class ClassNodeSkip { } private static class FastPathData { private Label pathStart = new Label(); private Label afterPath = new Label(); } public static class StatementMeta { private boolean optimize; protected ClassNode type; protected MethodNode target; protected VariableExpression declaredVariableExpression; protected boolean[] involvedTypes = new boolean[typeMapKeyNames.length]; public void chainInvolvedTypes(final OptimizeFlagsCollector opt) { for (int i = 0, n = typeMapKeyNames.length; i < n; i += 1) { if (opt.current.involvedTypes[i]) { this.involvedTypes[i] = true; } } } @Override public String toString() { StringBuilder ret = new StringBuilder(); ret.append("optimize=").append(optimize); ret.append(" target=").append(target); ret.append(" type=").append(type); ret.append(" involvedTypes="); for (int i = 0, n = typeMapKeyNames.length; i < n; i += 1) { if (involvedTypes[i]) { ret.append(' ').append(typeMapKeyNames[i]); } } return ret.toString(); } } private static class OptimizeFlagsCollector { private static class OptimizeFlagsEntry { private boolean canOptimize; private boolean shouldOptimize; private boolean[] involvedTypes = new boolean[typeMapKeyNames.length]; } private OptimizeFlagsEntry current = new OptimizeFlagsEntry(); private final Deque<OptimizeFlagsEntry> previous = new LinkedList<>(); public void push() { previous.push(current); current = new OptimizeFlagsEntry(); } public void pop(final boolean propagateFlags) { OptimizeFlagsEntry old = current; current = previous.pop(); if (propagateFlags) { chainCanOptimize(old.canOptimize); chainShouldOptimize(old.shouldOptimize); for (int i = 0, n = typeMapKeyNames.length; i < n; i += 1) { current.involvedTypes[i] |= old.involvedTypes[i]; } } } @Override public String toString() { StringBuilder ret = new StringBuilder(); if (current.shouldOptimize) { ret.append("should optimize, can = " + current.canOptimize); } else if (current.canOptimize) { ret.append("can optimize"); } else { ret.append("don't optimize"); } ret.append(" involvedTypes ="); for (int i = 0, n = typeMapKeyNames.length; i < n; i += 1) { if (current.involvedTypes[i]) { ret.append(' ').append(typeMapKeyNames[i]); } } return ret.toString(); } /** * @return true iff we should Optimize - this is almost seen as must */ private boolean shouldOptimize() { return current.shouldOptimize; } /** * @return true iff we can optimize, but not have to */ private boolean canOptimize() { return current.canOptimize || current.shouldOptimize; } /** * set "should" to true, if not already */ public void chainShouldOptimize(final boolean opt) { current.shouldOptimize = shouldOptimize() || opt; } /** * set "can" to true, if not already */ public void chainCanOptimize(final boolean opt) { current.canOptimize = current.canOptimize || opt; } public void chainInvolvedType(final ClassNode type) { Integer res = typeMap.get(type); if (res == null) return; current.involvedTypes[res] = true; } public void reset() { current.canOptimize = false; current.shouldOptimize = false; current.involvedTypes = new boolean[typeMapKeyNames.length]; } } private static class OptVisitor extends ClassCodeVisitorSupport { private static final VariableScope nonStaticScope = new VariableScope(); private final OptimizeFlagsCollector opt = new OptimizeFlagsCollector(); private boolean optimizeMethodCall = true; private final TypeChooser typeChooser; private VariableScope scope; private ClassNode node; OptVisitor(final TypeChooser chooser) { this.typeChooser = chooser; } @Override protected SourceUnit getSourceUnit() { return null; } @Override public void visitClass(final ClassNode node) { this.optimizeMethodCall = !node.implementsInterface(GROOVY_INTERCEPTABLE_TYPE); this.node = node; this.scope = nonStaticScope; super.visitClass(node); this.scope = null; this.node = null; } @Override public void visitConstructor(final ConstructorNode node) { scope = node.getVariableScope(); super.visitConstructor(node); opt.reset(); } @Override public void visitMethod(final MethodNode node) { scope = node.getVariableScope(); super.visitMethod(node); opt.reset(); } // statements: @Override public void visitBlockStatement(final BlockStatement statement) { opt.push(); boolean optAll = true; for (Statement stmt : statement.getStatements()) { opt.push(); stmt.visit(this); optAll = optAll && opt.canOptimize(); opt.pop(true); } if (statement.isEmpty()) { opt.chainCanOptimize(true); opt.pop(true); } else { opt.chainShouldOptimize(optAll); if (optAll) { addMeta(statement, opt); } opt.pop(optAll); } } @Override public void visitExpressionStatement(final ExpressionStatement statement) { if (statement.getNodeMetaData(StatementMeta.class) != null) return; opt.push(); super.visitExpressionStatement(statement); if (opt.shouldOptimize()) { addMeta(statement, opt); } opt.pop(opt.shouldOptimize()); } @Override public void visitForLoop(final ForStatement statement) { opt.push(); super.visitForLoop(statement); if (opt.shouldOptimize()) { addMeta(statement, opt); } opt.pop(opt.shouldOptimize()); } @Override public void visitIfElse(final IfStatement statement) { opt.push(); super.visitIfElse(statement); if (opt.shouldOptimize()) { addMeta(statement, opt); } opt.pop(opt.shouldOptimize()); } @Override public void visitReturnStatement(final ReturnStatement statement) { opt.push(); super.visitReturnStatement(statement); if (opt.shouldOptimize()) { addMeta(statement,opt); } opt.pop(opt.shouldOptimize()); } // expressions: @Override public void visitBinaryExpression(final BinaryExpression expression) { if (expression.getNodeMetaData(StatementMeta.class) != null) return; super.visitBinaryExpression(expression); ClassNode leftType = typeChooser.resolveType(expression.getLeftExpression(), node); ClassNode rightType = typeChooser.resolveType(expression.getRightExpression(), node); ClassNode resultType = null; int operation = expression.getOperation().getType(); if (operation == Types.LEFT_SQUARE_BRACKET && leftType.isArray()) { opt.chainShouldOptimize(true); resultType = leftType.getComponentType(); } else { switch (operation) { case Types.COMPARE_EQUAL: case Types.COMPARE_LESS_THAN: case Types.COMPARE_LESS_THAN_EQUAL: case Types.COMPARE_GREATER_THAN: case Types.COMPARE_GREATER_THAN_EQUAL: case Types.COMPARE_NOT_EQUAL: if (isIntCategory(leftType) && isIntCategory(rightType)) { opt.chainShouldOptimize(true); } else if (isLongCategory(leftType) && isLongCategory(rightType)) { opt.chainShouldOptimize(true); } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) { opt.chainShouldOptimize(true); } else { opt.chainCanOptimize(true); } resultType = boolean_TYPE; break; case Types.LOGICAL_AND: case Types.LOGICAL_AND_EQUAL: case Types.LOGICAL_OR: case Types.LOGICAL_OR_EQUAL: if (boolean_TYPE.equals(leftType) && boolean_TYPE.equals(rightType)) { opt.chainShouldOptimize(true); } else { opt.chainCanOptimize(true); } expression.setType(boolean_TYPE); resultType = boolean_TYPE; break; case Types.DIVIDE: case Types.DIVIDE_EQUAL: if (isLongCategory(leftType) && isLongCategory(rightType)) { resultType = BigDecimal_TYPE; opt.chainShouldOptimize(true); } else if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) { // no optimization for BigDecimal yet //resultType = BigDecimal_TYPE; } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) { resultType = double_TYPE; opt.chainShouldOptimize(true); } break; case Types.POWER: case Types.POWER_EQUAL: // TODO: implement break; case Types.ASSIGN: resultType = optimizeDivWithIntOrLongTarget(expression.getRightExpression(), leftType); opt.chainCanOptimize(true); break; default: if (isIntCategory(leftType) && isIntCategory(rightType)) { resultType = int_TYPE; opt.chainShouldOptimize(true); } else if (isLongCategory(leftType) && isLongCategory(rightType)) { resultType = long_TYPE; opt.chainShouldOptimize(true); } else if (isBigDecCategory(leftType) && isBigDecCategory(rightType)) { // no optimization for BigDecimal yet //resultType = BigDecimal_TYPE; } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) { resultType = double_TYPE; opt.chainShouldOptimize(true); } } } if (resultType != null) { addMeta(expression).type = resultType; opt.chainInvolvedType(resultType); opt.chainInvolvedType(leftType); opt.chainInvolvedType(rightType); } } @Override public void visitBitwiseNegationExpression(final BitwiseNegationExpression expression) { // TODO: implement int operations for this super.visitBitwiseNegationExpression(expression); addMeta(expression).type = OBJECT_TYPE; } @Override public void visitClosureExpression(final ClosureExpression expression) { } @Override public void visitConstructorCallExpression(final ConstructorCallExpression expression) { if (expression.getNodeMetaData(StatementMeta.class) != null) return; super.visitConstructorCallExpression(expression); // we cannot set a target for the constructor call, since we cannot easily check the meta class of the other class //setMethodTarget(call, "<init>", call.getArguments(), false); } @Override public void visitDeclarationExpression(final DeclarationExpression expression) { Expression right = expression.getRightExpression(); right.visit(this); ClassNode leftType = typeChooser.resolveType(expression.getLeftExpression(), node); Expression rightExpression = expression.getRightExpression(); ClassNode rightType = optimizeDivWithIntOrLongTarget(rightExpression, leftType); if (rightType == null) rightType = typeChooser.resolveType(expression.getRightExpression(), node); if (isPrimitiveType(leftType) && isPrimitiveType(rightType)) { // if right is a constant, then we optimize only if it makes a block complete, so we set a maybe if (right instanceof ConstantExpression) { opt.chainCanOptimize(true); } else { opt.chainShouldOptimize(true); } addMeta(expression).type = Optional.ofNullable(typeChooser.resolveType(expression, node)).orElse(leftType); opt.chainInvolvedType(leftType); opt.chainInvolvedType(rightType); } } @Override public void visitMethodCallExpression(final MethodCallExpression expression) { if (expression.getNodeMetaData(StatementMeta.class) != null) return; super.visitMethodCallExpression(expression); if (AsmClassGenerator.isThisExpression(expression.getObjectExpression())) { setMethodTarget(expression, expression.getMethodAsString(), expression.getArguments(), true); } } @Override public void visitPostfixExpression(final PostfixExpression expression) { super.visitPostfixExpression(expression); addTypeInformation(expression.getExpression(), expression); } @Override public void visitPrefixExpression(final PrefixExpression expression) { super.visitPrefixExpression(expression); addTypeInformation(expression.getExpression(), expression); } @Override public void visitStaticMethodCallExpression(final StaticMethodCallExpression expression) { if (expression.getNodeMetaData(StatementMeta.class) != null) return; super.visitStaticMethodCallExpression(expression); setMethodTarget(expression, expression.getMethod(), expression.getArguments(), true); } @Override public void visitUnaryMinusExpression(final UnaryMinusExpression expression) { // TODO: implement int operations for this super.visitUnaryMinusExpression(expression); addMeta(expression).type = OBJECT_TYPE; } @Override public void visitUnaryPlusExpression(final UnaryPlusExpression expression) { // TODO: implement int operations for this super.visitUnaryPlusExpression(expression); addMeta(expression).type = OBJECT_TYPE; } // private void addTypeInformation(final Expression expression, final Expression orig) { ClassNode type = typeChooser.resolveType(expression, node); if (isPrimitiveType(type)) { addMeta(orig).type = type; opt.chainShouldOptimize(true); opt.chainInvolvedType(type); } } /** * Optimizes "Z = X/Y" with Z being int or long style. * * @returns null if the optimization cannot be applied, otherwise it will return the new target type */ private ClassNode optimizeDivWithIntOrLongTarget(final Expression rhs, final ClassNode assignmentTartgetType) { if (!(rhs instanceof BinaryExpression)) return null; BinaryExpression binExp = (BinaryExpression) rhs; int op = binExp.getOperation().getType(); if (op != Types.DIVIDE && op != Types.DIVIDE_EQUAL) return null; ClassNode originalResultType = typeChooser.resolveType(binExp, node); if (!originalResultType.equals(BigDecimal_TYPE) || !(isLongCategory(assignmentTartgetType) || isFloatingCategory(assignmentTartgetType))) { return null; } ClassNode leftType = typeChooser.resolveType(binExp.getLeftExpression(), node); if (!isLongCategory(leftType)) return null; ClassNode rightType = typeChooser.resolveType(binExp.getRightExpression(), node); if (!isLongCategory(rightType)) return null; ClassNode target; if (isIntCategory(leftType) && isIntCategory(rightType)) { target = int_TYPE; } else if (isLongCategory(leftType) && isLongCategory(rightType)) { target = long_TYPE; } else if (isDoubleCategory(leftType) && isDoubleCategory(rightType)) { target = double_TYPE; } else { return null; } addMeta(rhs).type = target; opt.chainInvolvedType(target); return target; } private void setMethodTarget(final Expression expression, final String name, final Expression callArgs, final boolean isMethod) { if (name == null) return; if (!optimizeMethodCall) return; if (AsmClassGenerator.containsSpreadExpression(callArgs)) return; // find method call target Parameter[] paraTypes = null; if (callArgs instanceof ArgumentListExpression) { ArgumentListExpression args = (ArgumentListExpression) callArgs; int size = args.getExpressions().size(); paraTypes = new Parameter[size]; int i = 0; for (Expression exp : args.getExpressions()) { ClassNode type = typeChooser.resolveType(exp, node); if (!validTypeForCall(type)) return; paraTypes[i] = new Parameter(type, ""); i += 1; } } else { ClassNode type = typeChooser.resolveType(callArgs, node); if (!validTypeForCall(type)) return; paraTypes = new Parameter[]{new Parameter(type, "")}; } MethodNode target; ClassNode type; if (isMethod) { target = node.getMethod(name, paraTypes); if (target == null) return; if (!target.getDeclaringClass().equals(node)) return; if (scope.isInStaticContext() && !target.isStatic()) return; type = target.getReturnType().redirect(); } else { type = expression.getType(); target = selectConstructor(type, paraTypes); if (target == null) return; } StatementMeta meta = addMeta(expression); meta.target = target; meta.type = type; opt.chainShouldOptimize(true); } private static MethodNode selectConstructor(final ClassNode node, final Parameter[] parameters) { List<ConstructorNode> ctors = node.getDeclaredConstructors(); MethodNode result = null; for (ConstructorNode ctor : ctors) { if (parametersEqual(ctor.getParameters(), parameters)) { result = ctor; break; } } return (result != null && result.isPublic() ? result : null); } private static boolean validTypeForCall(final ClassNode type) { // do call only for final classes and primitive types return isPrimitiveType(type) || (type.getModifiers() & ACC_FINAL) > 0; } } }
41.677453
144
0.61382
83ae3d9317a56ecc2e7c64aaee7f43972764265f
12,727
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package bo.app; import com.appboy.support.AppboyLogger; import com.appboy.support.StringUtils; import java.text.SimpleDateFormat; import java.util.*; // Referenced classes of package bo.app: // r public final class dl { public dl() { // 0 0:aload_0 // 1 1:invokespecial #52 <Method void Object()> // 2 4:return } public static long a() { return System.currentTimeMillis() / 1000L; // 0 0:invokestatic #58 <Method long System.currentTimeMillis()> // 1 3:ldc2w #59 <Long 1000L> // 2 6:ldiv // 3 7:lreturn } public static long a(Date date) { return date.getTime() / 1000L; // 0 0:aload_0 // 1 1:invokevirtual #66 <Method long Date.getTime()> // 2 4:ldc2w #59 <Long 1000L> // 3 7:ldiv // 4 8:lreturn } public static String a(Date date, r r1) { Object obj = ((Object) (r1)); // 0 0:aload_1 // 1 1:astore_2 if(!c.contains(((Object) (r1)))) //* 2 2:getstatic #48 <Field EnumSet c> //* 3 5:aload_1 //* 4 6:invokevirtual #71 <Method boolean EnumSet.contains(Object)> //* 5 9:ifne 65 { obj = ((Object) (a)); // 6 12:getstatic #21 <Field String a> // 7 15:astore_2 StringBuilder stringbuilder = new StringBuilder(); // 8 16:new #73 <Class StringBuilder> // 9 19:dup // 10 20:invokespecial #74 <Method void StringBuilder()> // 11 23:astore_3 stringbuilder.append("Unsupported date format: "); // 12 24:aload_3 // 13 25:ldc1 #76 <String "Unsupported date format: "> // 14 27:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 15 30:pop stringbuilder.append(((Object) (r1))); // 16 31:aload_3 // 17 32:aload_1 // 18 33:invokevirtual #83 <Method StringBuilder StringBuilder.append(Object)> // 19 36:pop stringbuilder.append(". Defaulting to "); // 20 37:aload_3 // 21 38:ldc1 #85 <String ". Defaulting to "> // 22 40:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 23 43:pop stringbuilder.append(((Object) (r.b))); // 24 44:aload_3 // 25 45:getstatic #38 <Field r r.b> // 26 48:invokevirtual #83 <Method StringBuilder StringBuilder.append(Object)> // 27 51:pop AppboyLogger.w(((String) (obj)), stringbuilder.toString()); // 28 52:aload_2 // 29 53:aload_3 // 30 54:invokevirtual #89 <Method String StringBuilder.toString()> // 31 57:invokestatic #93 <Method int AppboyLogger.w(String, String)> // 32 60:pop obj = ((Object) (r.b)); // 33 61:getstatic #38 <Field r r.b> // 34 64:astore_2 } r1 = ((r) (new SimpleDateFormat(((r) (obj)).a(), Locale.US))); // 35 65:new #95 <Class SimpleDateFormat> // 36 68:dup // 37 69:aload_2 // 38 70:invokevirtual #97 <Method String r.a()> // 39 73:getstatic #103 <Field Locale Locale.US> // 40 76:invokespecial #106 <Method void SimpleDateFormat(String, Locale)> // 41 79:astore_1 ((SimpleDateFormat) (r1)).setTimeZone(b); // 42 80:aload_1 // 43 81:getstatic #31 <Field TimeZone b> // 44 84:invokevirtual #110 <Method void SimpleDateFormat.setTimeZone(TimeZone)> return ((SimpleDateFormat) (r1)).format(date); // 45 87:aload_1 // 46 88:aload_0 // 47 89:invokevirtual #114 <Method String SimpleDateFormat.format(Date)> // 48 92:areturn } public static Date a(int i, int j, int k) { return a(i, j, k, 0, 0, 0); // 0 0:iload_0 // 1 1:iload_1 // 2 2:iload_2 // 3 3:iconst_0 // 4 4:iconst_0 // 5 5:iconst_0 // 6 6:invokestatic #118 <Method Date a(int, int, int, int, int, int)> // 7 9:areturn } public static Date a(int i, int j, int k, int l, int i1, int j1) { GregorianCalendar gregoriancalendar = new GregorianCalendar(i, j, k, l, i1, j1); // 0 0:new #120 <Class GregorianCalendar> // 1 3:dup // 2 4:iload_0 // 3 5:iload_1 // 4 6:iload_2 // 5 7:iload_3 // 6 8:iload 4 // 7 10:iload 5 // 8 12:invokespecial #123 <Method void GregorianCalendar(int, int, int, int, int, int)> // 9 15:astore 6 ((Calendar) (gregoriancalendar)).setTimeZone(b); // 10 17:aload 6 // 11 19:getstatic #31 <Field TimeZone b> // 12 22:invokevirtual #126 <Method void Calendar.setTimeZone(TimeZone)> return ((Calendar) (gregoriancalendar)).getTime(); // 13 25:aload 6 // 14 27:invokevirtual #129 <Method Date Calendar.getTime()> // 15 30:areturn } public static Date a(long l) { return new Date(l * 1000L); // 0 0:new #63 <Class Date> // 1 3:dup // 2 4:lload_0 // 3 5:ldc2w #59 <Long 1000L> // 4 8:lmul // 5 9:invokespecial #133 <Method void Date(long)> // 6 12:areturn } public static Date a(String s, r r1) { if(StringUtils.isNullOrBlank(s)) //* 0 0:aload_0 //* 1 1:invokestatic #142 <Method boolean StringUtils.isNullOrBlank(String)> //* 2 4:ifeq 43 { r1 = ((r) (a)); // 3 7:getstatic #21 <Field String a> // 4 10:astore_1 StringBuilder stringbuilder = new StringBuilder(); // 5 11:new #73 <Class StringBuilder> // 6 14:dup // 7 15:invokespecial #74 <Method void StringBuilder()> // 8 18:astore_2 stringbuilder.append("Null or blank date string received: "); // 9 19:aload_2 // 10 20:ldc1 #144 <String "Null or blank date string received: "> // 11 22:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 12 25:pop stringbuilder.append(s); // 13 26:aload_2 // 14 27:aload_0 // 15 28:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 16 31:pop AppboyLogger.w(((String) (r1)), stringbuilder.toString()); // 17 32:aload_1 // 18 33:aload_2 // 19 34:invokevirtual #89 <Method String StringBuilder.toString()> // 20 37:invokestatic #93 <Method int AppboyLogger.w(String, String)> // 21 40:pop return null; // 22 41:aconst_null // 23 42:areturn } if(!c.contains(((Object) (r1)))) //* 24 43:getstatic #48 <Field EnumSet c> //* 25 46:aload_1 //* 26 47:invokevirtual #71 <Method boolean EnumSet.contains(Object)> //* 27 50:ifne 89 { s = a; // 28 53:getstatic #21 <Field String a> // 29 56:astore_0 StringBuilder stringbuilder1 = new StringBuilder(); // 30 57:new #73 <Class StringBuilder> // 31 60:dup // 32 61:invokespecial #74 <Method void StringBuilder()> // 33 64:astore_2 stringbuilder1.append("Unsupported date format. Returning null. Got date format: "); // 34 65:aload_2 // 35 66:ldc1 #146 <String "Unsupported date format. Returning null. Got date format: "> // 36 68:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 37 71:pop stringbuilder1.append(((Object) (r1))); // 38 72:aload_2 // 39 73:aload_1 // 40 74:invokevirtual #83 <Method StringBuilder StringBuilder.append(Object)> // 41 77:pop AppboyLogger.w(s, stringbuilder1.toString()); // 42 78:aload_0 // 43 79:aload_2 // 44 80:invokevirtual #89 <Method String StringBuilder.toString()> // 45 83:invokestatic #93 <Method int AppboyLogger.w(String, String)> // 46 86:pop return null; // 47 87:aconst_null // 48 88:areturn } r1 = ((r) (new SimpleDateFormat(r1.a(), Locale.US))); // 49 89:new #95 <Class SimpleDateFormat> // 50 92:dup // 51 93:aload_1 // 52 94:invokevirtual #97 <Method String r.a()> // 53 97:getstatic #103 <Field Locale Locale.US> // 54 100:invokespecial #106 <Method void SimpleDateFormat(String, Locale)> // 55 103:astore_1 ((SimpleDateFormat) (r1)).setTimeZone(b); // 56 104:aload_1 // 57 105:getstatic #31 <Field TimeZone b> // 58 108:invokevirtual #110 <Method void SimpleDateFormat.setTimeZone(TimeZone)> try { r1 = ((r) (((SimpleDateFormat) (r1)).parse(s))); // 59 111:aload_1 // 60 112:aload_0 // 61 113:invokevirtual #150 <Method Date SimpleDateFormat.parse(String)> // 62 116:astore_1 } //* 63 117:aload_1 //* 64 118:areturn // Misplaced declaration of an exception variable catch(r r1) //* 65 119:astore_1 { String s1 = a; // 66 120:getstatic #21 <Field String a> // 67 123:astore_2 StringBuilder stringbuilder2 = new StringBuilder(); // 68 124:new #73 <Class StringBuilder> // 69 127:dup // 70 128:invokespecial #74 <Method void StringBuilder()> // 71 131:astore_3 stringbuilder2.append("Exception parsing date "); // 72 132:aload_3 // 73 133:ldc1 #152 <String "Exception parsing date "> // 74 135:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 75 138:pop stringbuilder2.append(s); // 76 139:aload_3 // 77 140:aload_0 // 78 141:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 79 144:pop stringbuilder2.append(". Returning null"); // 80 145:aload_3 // 81 146:ldc1 #154 <String ". Returning null"> // 82 148:invokevirtual #80 <Method StringBuilder StringBuilder.append(String)> // 83 151:pop AppboyLogger.e(s1, stringbuilder2.toString(), ((Throwable) (r1))); // 84 152:aload_2 // 85 153:aload_3 // 86 154:invokevirtual #89 <Method String StringBuilder.toString()> // 87 157:aload_1 // 88 158:invokestatic #158 <Method int AppboyLogger.e(String, String, Throwable)> // 89 161:pop return null; // 90 162:aconst_null // 91 163:areturn } return ((Date) (r1)); } public static double b() { return (double)System.currentTimeMillis() / 1000D; // 0 0:invokestatic #58 <Method long System.currentTimeMillis()> // 1 3:l2d // 2 4:ldc2w #160 <Double 1000D> // 3 7:ddiv // 4 8:dreturn } public static long c() { return System.currentTimeMillis(); // 0 0:invokestatic #58 <Method long System.currentTimeMillis()> // 1 3:lreturn } private static final String a = AppboyLogger.getAppboyLogTag(bo/app/dl); private static final TimeZone b = TimeZone.getTimeZone("UTC"); private static final EnumSet c; static { // 0 0:ldc1 #2 <Class dl> // 1 2:invokestatic #19 <Method String AppboyLogger.getAppboyLogTag(Class)> // 2 5:putstatic #21 <Field String a> // 3 8:ldc1 #23 <String "UTC"> // 4 10:invokestatic #29 <Method TimeZone TimeZone.getTimeZone(String)> // 5 13:putstatic #31 <Field TimeZone b> c = EnumSet.of(((Enum) (r.a)), ((Enum) (r.b)), ((Enum) (r.c))); // 6 16:getstatic #36 <Field r r.a> // 7 19:getstatic #38 <Field r r.b> // 8 22:getstatic #40 <Field r r.c> // 9 25:invokestatic #46 <Method EnumSet EnumSet.of(Enum, Enum, Enum)> // 10 28:putstatic #48 <Field EnumSet c> //* 11 31:return } }
38.566667
104
0.538776
f00bdcea3c57cca617784ede1d926103f6749bd0
4,971
package io.reactivex.internal.operators.observable; import io.reactivex.ObservableSource; import io.reactivex.Observer; import io.reactivex.Scheduler; import io.reactivex.disposables.Disposable; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.observers.SerializedObserver; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public final class ObservableSampleTimed<T> extends AbstractObservableWithUpstream<T, T> { final boolean emitLast; final long period; final Scheduler scheduler; final TimeUnit unit; public ObservableSampleTimed(ObservableSource<T> observableSource, long j, TimeUnit timeUnit, Scheduler scheduler2, boolean z) { super(observableSource); this.period = j; this.unit = timeUnit; this.scheduler = scheduler2; this.emitLast = z; } public void subscribeActual(Observer<? super T> observer) { SerializedObserver serializedObserver = new SerializedObserver(observer); if (this.emitLast) { this.source.subscribe(new SampleTimedEmitLast(serializedObserver, this.period, this.unit, this.scheduler)); } else { this.source.subscribe(new SampleTimedNoLast(serializedObserver, this.period, this.unit, this.scheduler)); } } static abstract class SampleTimedObserver<T> extends AtomicReference<T> implements Observer<T>, Disposable, Runnable { private static final long serialVersionUID = -3517602651313910099L; final Observer<? super T> downstream; final long period; final Scheduler scheduler; final AtomicReference<Disposable> timer = new AtomicReference<>(); final TimeUnit unit; Disposable upstream; /* access modifiers changed from: package-private */ public abstract void complete(); SampleTimedObserver(Observer<? super T> observer, long j, TimeUnit timeUnit, Scheduler scheduler2) { this.downstream = observer; this.period = j; this.unit = timeUnit; this.scheduler = scheduler2; } public void onSubscribe(Disposable disposable) { if (DisposableHelper.validate(this.upstream, disposable)) { this.upstream = disposable; this.downstream.onSubscribe(this); Scheduler scheduler2 = this.scheduler; long j = this.period; DisposableHelper.replace(this.timer, scheduler2.schedulePeriodicallyDirect(this, j, j, this.unit)); } } public void onNext(T t) { lazySet(t); } public void onError(Throwable th) { cancelTimer(); this.downstream.onError(th); } public void onComplete() { cancelTimer(); complete(); } /* access modifiers changed from: package-private */ public void cancelTimer() { DisposableHelper.dispose(this.timer); } public void dispose() { cancelTimer(); this.upstream.dispose(); } public boolean isDisposed() { return this.upstream.isDisposed(); } /* access modifiers changed from: package-private */ public void emit() { Object andSet = getAndSet((Object) null); if (andSet != null) { this.downstream.onNext(andSet); } } } static final class SampleTimedNoLast<T> extends SampleTimedObserver<T> { private static final long serialVersionUID = -7139995637533111443L; SampleTimedNoLast(Observer<? super T> observer, long j, TimeUnit timeUnit, Scheduler scheduler) { super(observer, j, timeUnit, scheduler); } /* access modifiers changed from: package-private */ public void complete() { this.downstream.onComplete(); } public void run() { emit(); } } static final class SampleTimedEmitLast<T> extends SampleTimedObserver<T> { private static final long serialVersionUID = -7139995637533111443L; final AtomicInteger wip = new AtomicInteger(1); SampleTimedEmitLast(Observer<? super T> observer, long j, TimeUnit timeUnit, Scheduler scheduler) { super(observer, j, timeUnit, scheduler); } /* access modifiers changed from: package-private */ public void complete() { emit(); if (this.wip.decrementAndGet() == 0) { this.downstream.onComplete(); } } public void run() { if (this.wip.incrementAndGet() == 2) { emit(); if (this.wip.decrementAndGet() == 0) { this.downstream.onComplete(); } } } } }
34.282759
132
0.618588
d750a025a94b6922e6a87335cace881ac791258b
542
package com.chenjie.sboot.activemq; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * @Author chenjie * @Date 2018/10/16 18:05 * @Description: */ @SpringBootTest @RunWith(SpringRunner.class) public class ActiveMqApplicationTest { @Test public void contextLoads() { } }
23.565217
68
0.785978
899b5e9bc792ab3d06a9901c412137b0693d5b87
3,020
package esb; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class GenerarXML { public DOMSource GenerarXMLEnviar(String nroTarjeta, String fechaVencimiento, String digitoVerificador, String monto) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("confirmacion"); doc.appendChild(rootElement); Element nroTarjetaElement = doc.createElement("nroTarjeta"); nroTarjetaElement.appendChild(doc.createTextNode(nroTarjeta)); rootElement.appendChild(nroTarjetaElement); Element fechaVencimientoElement = doc.createElement("fechaVencimiento"); fechaVencimientoElement.appendChild(doc.createTextNode(fechaVencimiento)); rootElement.appendChild(fechaVencimientoElement); Element digitoVerificadorElement = doc.createElement("digitoVerificador"); digitoVerificadorElement.appendChild(doc.createTextNode(digitoVerificador)); rootElement.appendChild(digitoVerificadorElement); Element montoElement = doc.createElement("monto"); montoElement.appendChild(doc.createTextNode(monto)); rootElement.appendChild(montoElement); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); return source; } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } return null; } public DOMSource GenerarXMLAnular(String idConfirmacionPago) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("anulacion"); doc.appendChild(rootElement); Element idConfirmacionPagoElement = doc.createElement("idConfirmacionPago"); idConfirmacionPagoElement.appendChild(doc.createTextNode(idConfirmacionPago)); rootElement.appendChild(idConfirmacionPagoElement); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); return source; } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } return null; } }
33.932584
118
0.782119
3c9d44829ef680f73a94dc33cedce40abfffe8d8
335
package ru.otus.core.sessionmanager; import org.hibernate.Session; import ru.otus.hibernate.sessionmanager.DatabaseSessionHibernate; public interface SessionManager extends AutoCloseable { Session beginSession(); void commitSession(); void rollbackSession(); void close(); DatabaseSession getCurrentSession(); }
23.928571
65
0.776119
122d53907cc54e3d14908f5aff5be48db1e8af7f
1,784
package ru.bellintegrator.yahoo.jms; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import ru.bellintegrator.yahoo.YahooWeatherService; import javax.jms.JMSException; import javax.jms.Message; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CityNameListenerTest { @Mock private YahooWeatherService yahooWeatherService; @InjectMocks private CityNameListener cityNameListener; @Before public void checkInjections(){ Assert.assertNotNull(yahooWeatherService); Assert.assertNotNull(cityNameListener); } @Test public void whenReceiveMessageThenCallRequestWeather() throws JMSException { Message message = mock(Message.class); String location = "Ufa"; when(message.isBodyAssignableTo(String.class)).thenReturn(true); when(message.getBody(String.class)).thenReturn(location); cityNameListener.onMessage(message); verify(yahooWeatherService, atLeast(1)).requestWeather(location); } @Test public void whenReceiveWrongBodyMessageThenCatchException() throws JMSException { Message message = mock(Message.class); when(message.isBodyAssignableTo(String.class)).thenReturn(false); try { cityNameListener.onMessage(message); }catch (RuntimeException e){ assertEquals(e.getMessage(), "Incorrect message body type, must be String "); } } }
30.758621
89
0.73935
e75254c3dd5b61a7c0b087083ae9db6be8dda183
1,008
package com.lhsang.dashboard.model; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity(name="img_product") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Images { @Id int id; String src; @ManyToOne @JoinColumn(name="product_id") @JsonBackReference Product product; String title; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
16.52459
62
0.700397
396808d0ae02869d4c08b689f1962ad158d83376
2,559
package leppa.planarartifice.foci; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Set; import leppa.planarartifice.main.PlanarArtifice; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.casters.FocusEffect; import thaumcraft.api.casters.FocusEngine; import thaumcraft.api.casters.FocusNode; import thaumcraft.api.casters.IFocusElement; import thaumcraft.api.casters.NodeSetting; import thaumcraft.api.casters.Trajectory; public class FocusEffectColourized extends FocusEffect{ public static Field settings; public FocusEffectColourized(){ super(); try{ settings = FocusNode.class.getDeclaredField("settings"); settings.setAccessible(true); HashmapColourizerSettingsHack hash = new HashmapColourizerSettingsHack(); hash.putAll((HashMap)settings.get(this)); settings.set(this, hash); }catch(Exception e){ e.printStackTrace(); } } @Override public String getKey(){ return "planarartifice.FOCUSCOLOURED"; } @Override public String getResearch(){ return "PA_FOCUS_LIGHT"; } @Override public boolean execute(RayTraceResult var1, Trajectory var2, float var3, int var4){ PlanarArtifice.focusEffects.get(getSettingValue("focus")).setPackage(getPackage()); PlanarArtifice.focusEffects.get(getSettingValue("focus")).setParent(getParent()); PlanarArtifice.focusEffects.get(getSettingValue("focus")); return PlanarArtifice.focusEffects.get(getSettingValue("focus")).execute(var1, var2, var3, var4); } @Override public void renderParticleFX(World var1, double var2, double var4, double var6, double var8, double var10, double var12){ PlanarArtifice.focusEffects.get(getSettingValue("focus")).renderParticleFX(var1, var2, var4, var6, var8, var10, var12); } @Override public int getComplexity(){ return PlanarArtifice.focusEffects.get(getSettingValue("focus")).getComplexity(); } @Override public Aspect getAspect(){ return PlanarArtifice.focusEffects.get(getSettingValue("focus")).getAspect(); } @Override public NodeSetting[] createSettings(){ //return new NodeSetting[]{new NodeSettingBaseFocus().new NodeSettingFocusBase("focus", "focus.colourizer.focus"), new NodeSetting("customSettingOne", "focus.colourizer.invisible", new NodeSettingIgnore()), new NodeSetting("customSettingTwo", "focus.colourizer.invisible", new NodeSettingIgnore())}; return new NodeSetting[]{new NodeSettingBaseFocus().new NodeSettingFocusBase("focus", "focus.colourizer.focus")}; } }
35.054795
301
0.779601
d734cd03e73bb69f63f05a1a36a3714c53f6ead2
988
package com.example.controller; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.example.dao.MyLoggerFactory; import com.example.model.ERSUsers; import com.example.service.ERSUsersService; import com.example.service.ERSUsersServiceImpl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class ERSUsersController { public static ERSUsersService myServ = new ERSUsersServiceImpl(); final static Logger logger = Logger.getLogger(MyLoggerFactory.class); public static void allFinder(HttpServletRequest req, HttpServletResponse res) throws JsonProcessingException, IOException { List<ERSUsers> myUserList = myServ.getAllUsers(); res.getWriter().write(new ObjectMapper().writeValueAsString(myUserList)); logger.info("All reimbursements were found. Returning..."); } }
32.933333
78
0.818826
4259ef43679fc787b2a0960c84e8692b7497b9ad
2,220
package com.sd.lib.foot_panel.ext; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.widget.FrameLayout; /** * 高度为键盘高度的布局 */ public class FKeyboardHeightLayout extends FrameLayout { private Activity mActivity; public FKeyboardHeightLayout(Context context) { super(context); init(context); } public FKeyboardHeightLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { if (context instanceof Activity) { mActivity = (Activity) context; } else { throw new IllegalArgumentException("context must be instance of " + Activity.class.getName()); } } protected int getKeyboardHeight(FKeyboardListener listener) { return listener.getKeyboardHeight(); } /** * 键盘高度回调 */ private final FKeyboardListener.Callback mKeyboardCallback = new FKeyboardListener.Callback() { @Override public void onKeyboardHeightChanged(int height, FKeyboardListener listener) { final int viewHeight = getHeight(); Log.i(FKeyboardHeightLayout.class.getSimpleName(), "onKeyboardHeightChanged height:" + height + " viewHeight:" + viewHeight); if (viewHeight != height) { requestLayout(); } } }; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int keyboardHeight = getKeyboardHeight(FKeyboardListener.of(mActivity)); Log.i(FKeyboardHeightLayout.class.getSimpleName(), "onMeasure keyboardHeight:" + keyboardHeight); super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(keyboardHeight, MeasureSpec.EXACTLY)); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); FKeyboardListener.of(mActivity).addCallback(mKeyboardCallback); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); FKeyboardListener.of(mActivity).removeCallback(mKeyboardCallback); } }
31.267606
137
0.676577
0127b0c2ffb38575e7523fcbeafb29798518665a
1,293
package com.google.crypto.tink.hybrid; import com.google.crypto.tink.aead.AeadConfig; import com.google.crypto.tink.proto.RegistryConfig; import java.security.GeneralSecurityException; public final class HybridConfig { public static final String ECIES_AEAD_HKDF_PRIVATE_KEY_TYPE_URL = new EciesAeadHkdfPrivateKeyManager().getKeyType(); public static final String ECIES_AEAD_HKDF_PUBLIC_KEY_TYPE_URL = new EciesAeadHkdfPublicKeyManager().getKeyType(); @Deprecated public static final RegistryConfig LATEST = RegistryConfig.getDefaultInstance(); @Deprecated public static final RegistryConfig TINK_1_0_0 = RegistryConfig.getDefaultInstance(); @Deprecated public static final RegistryConfig TINK_1_1_0 = RegistryConfig.getDefaultInstance(); static { try { init(); } catch (GeneralSecurityException e) { throw new ExceptionInInitializerError(e); } } @Deprecated public static void init() throws GeneralSecurityException { register(); } public static void register() throws GeneralSecurityException { AeadConfig.register(); EciesAeadHkdfPrivateKeyManager.registerPair(true); HybridDecryptWrapper.register(); HybridEncryptWrapper.register(); } }
34.945946
120
0.737046
267149513a01956a5bbe764ee74061416e901294
1,070
/* COPYRIGHT (C) 2014 barreiro. All Rights Reserved. */ package net.projecteuler.barreiro.problem; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. * <p> * Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. * <p> * (Please note that the palindromic number, in either base, may not include leading zeros.) * * @author barreiro */ public class Problem036Test extends ProjectEulerAbstractTest { @Test public void test() { assertEquals( 872187, new Solver036().solve() ); } @Test public void minimal() { assertEquals( 1, new Solver036( 2 ).solve() ); } @Test public void small() { assertEquals( 25, new Solver036( 20 ).solve() ); } @Test public void example() { assertEquals( 1055, new Solver036( 586 ).solve() ); } @Test public void big() { assertEquals( 25846868, new Solver036( 10000000 ).solve() ); } }
23.26087
99
0.641121
98df6365847d6e5661f60741238c269b116f250e
951
package com.github.tinselspoon.intellij.kubernetes; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; import java.io.File; import java.net.URISyntaxException; import java.net.URL; /** * Static methods for tests. */ class TestUtil { /** * Gets the path to the given test data folder. * * @param directory the subdirectory within the test resources to search for. * @return the full absolute path to test data. */ @NotNull static String getTestDataPath(final String directory) { try { final URL url = ClassLoader.getSystemClassLoader().getResource(directory); TestCase.assertNotNull("Unable to determine test resources directory.", url); return new File(url.toURI()).getAbsolutePath(); } catch (final URISyntaxException e) { throw new AssertionError("Unable to determine test resources directory.", e); } } }
29.71875
89
0.680336
f562ef6a850b8b0a2944c37bdd4f653f90552256
1,564
package System.Entity; /** * The functions and Entity of Menu. * @author Jing Hu * @version 1.3 */ public class Entity_Menu { private String Dish_name; private float price; private boolean Available; /** * Entity class of menu. */ public Entity_Menu() { this.Dish_name=null; this.price=0; this.Available=true; } /** * Entity class of menu. * @param Dish_name * @param price * @param Available */ public Entity_Menu(String Dish_name, float price, boolean Available) { this.Dish_name=Dish_name; this.price=price; this.Available=true; } /** * Get name of dish. * @return Dish_name */ public String getDish_name() { return this.Dish_name; } /** * Set name of dish. * @param Dish_name */ public void setDish_name(String Dish_name) { this.Dish_name=Dish_name; } /** * Get price of dish. * @return price */ public float getPrice() { return price; } /** * Get price of dish. * @param Dish_name * @return price */ public float getPrice(String Dish_name) { return price; } /** * Set price of dish. * @param price */ public void setPrice(float price) { this.price=price; } /** * Get Available of dish. * @return Available */ public boolean getAvailable() { return Available; } /** * Get Available of dish. * @param Dish_name * @return available */ public boolean getAvailable(String Dish_name) { return Available; } /** * Set Available of dish. * @param Available */ public void setAvailable(boolean Available) { this.Available=Available; } }
17.377778
71
0.654731
599bc74f476bf2309f47c68c91fd96f60194e8f3
2,466
package com.github.chen0040.art.core; import java.util.ArrayList; import java.util.List; /** * Created by xschen on 23/8/15. */ public class ARTMAP extends FuzzyART { private List<String> labels; private double epsilon = 0.00001; public void setEpsilon(double epsilon) { this.epsilon = epsilon; } public ARTMAP(int inputCount) { super(inputCount, 0); labels = new ArrayList<>(); } public ARTMAP(){ super(); labels = new ArrayList<>(); } public String simulate(double[] x, String label, boolean can_create_new_node){ boolean new_node = can_create_new_node; int C = getNodeCount(); String winner = label; if(label != null && !labels.contains(label)){ addNode(x); labels.add(label); } else { if(label == null){ can_create_new_node = false; } if (can_create_new_node) { for (int j = 0; j < C; ++j) { double activation_value = choice_function(x, j); activation_values.set(j, activation_value); } for (int j = 0; j < C; ++j) { int J = template_with_max_activation_value(); if (J == -1) break; String labelJ = labels.get(J); if (!labelJ.equals(label)) { rho = match_function(x, J) + epsilon; } double match_value = match_function(x, J); if (match_value > rho) { update_node(x, J); new_node = false; break; } else { activation_values.set(J, 0.0); } } if (new_node) { addNode(x); labels.add(label); } } else { double max_match_value = 0; int J = -1; for (int j = 0; j < C; ++j) { double match_value = match_function(x, j); if (max_match_value < match_value) { max_match_value = match_value; J = j; } } winner = labels.get(J); } } return winner; } }
27.4
82
0.435118
46c2ff549c88849b762a37a128c097c895316baf
5,434
package com.senzing.api.model; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.senzing.api.model.impl.SzAttributeTypesResponseImpl; import java.util.*; /** * The response containing a list of attribute types. Typically this is the * list of all configured attribute types (excluding the "internal" ones). * */ @JsonDeserialize(using=SzAttributeTypesResponse.Factory.class) public interface SzAttributeTypesResponse extends SzResponseWithRawData { /** * Returns the {@link SzAttributeTypesResponseData} for this instance. * * @return The {@link SzAttributeTypesResponseData} for this instance. */ SzAttributeTypesResponseData getData(); /** * Sets the {@link SzAttributeTypesResponseData} for this instance. * * @param data The {@link SzAttributeTypesResponseData} for this instance. */ void setData(SzAttributeTypesResponseData data); /** * Convenience method to add the {@link SzAttributeType} to the contained * {@link SzAttributeTypesResponseData}. * * @param attributeType The {@link SzAttributeType} to add. */ void addAttributeType(SzAttributeType attributeType); /** * Sets the specified {@link List} of {@linkplain SzAttributeType attribute * types} using the specified {@link Collection} of {@link SzAttributeType} * instances. * * @param attributeTypes The {@link Collection} of {@link SzAttributeType} * instances. */ void setAttributeTypes(Collection<? extends SzAttributeType> attributeTypes); /** * A {@link ModelProvider} for instances of {@link SzAttributeTypesResponse}. */ interface Provider extends ModelProvider<SzAttributeTypesResponse> { /** * Creates an instance of {@link SzAttributeTypesResponse} with the * specified {@link SzMeta} and {@link SzLinks}. * * @param meta The response meta data. * * @param links The links for the response. */ SzAttributeTypesResponse create(SzMeta meta, SzLinks links); /** * Creates an instance of {@link SzAttributeTypesResponse} with the * specified {@link SzMeta}, {@link SzLinks} and {@link * SzAttributeTypesResponseData}. * * @param meta The response meta data. * * @param links The links for the response. * * @param data The data for the response. */ SzAttributeTypesResponse create(SzMeta meta, SzLinks links, SzAttributeTypesResponseData data); } /** * Provides a default {@link Provider} implementation for {@link * SzAttributeTypesResponse} that produces instances of * {@link SzAttributeTypesResponseImpl}. */ class DefaultProvider extends AbstractModelProvider<SzAttributeTypesResponse> implements Provider { /** * Default constructor. */ public DefaultProvider() { super(SzAttributeTypesResponse.class, SzAttributeTypesResponseImpl.class); } @Override public SzAttributeTypesResponse create(SzMeta meta, SzLinks links) { return new SzAttributeTypesResponseImpl(meta, links); } @Override public SzAttributeTypesResponse create(SzMeta meta, SzLinks links, SzAttributeTypesResponseData data) { return new SzAttributeTypesResponseImpl(meta, links, data); } } /** * Provides a {@link ModelFactory} implementation for * {@link SzAttributeTypesResponse}. */ class Factory extends ModelFactory<SzAttributeTypesResponse, Provider> { /** * Default constructor. This is public and can only be called after the * singleton master instance is created as it inherits the same state from * the master instance. */ public Factory() { super(SzAttributeTypesResponse.class); } /** * Constructs with the default provider. This constructor is private and * is used for the master singleton instance. * @param defaultProvider The default provider. */ private Factory(Provider defaultProvider) { super(defaultProvider); } /** * Creates an instance of {@link SzAttributeTypesResponse} with the * specified {@link SzMeta} and {@link SzLinks}. * * @param meta The response meta data. * * @param links The links for the response. */ public SzAttributeTypesResponse create(SzMeta meta, SzLinks links) { return this.getProvider().create(meta, links); } /** * Creates an instance of {@link SzAttributeTypesResponse} with the * specified {@link SzMeta}, {@link SzLinks} and {@link * SzAttributeTypesResponseData}. * * @param meta The response meta data. * * @param links The links for the response. * * @param data The data for the response. */ public SzAttributeTypesResponse create(SzMeta meta, SzLinks links, SzAttributeTypesResponseData data) { return this.getProvider().create(meta, links, data); } } /** * The {@link Factory} instance for this interface. */ Factory FACTORY = new Factory(new DefaultProvider()); }
32.153846
79
0.643541
f7a74aac35898ced455c81bb51be6c5dd0f6cc1c
1,602
/* * Copyright (C) 2015-2019 Lightbend Inc. <https://www.lightbend.com> */ package akka.stream.io; import akka.japi.Pair; import akka.stream.StreamTest; import akka.testkit.AkkaJUnitActorSystemResource; import akka.stream.javadsl.Sink; import akka.stream.javadsl.Source; import akka.stream.javadsl.StreamConverters; import akka.testkit.AkkaSpec; import akka.stream.testkit.Utils; import akka.util.ByteString; import org.junit.ClassRule; import org.junit.Test; import scala.concurrent.Future; import scala.concurrent.duration.FiniteDuration; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; public class InputStreamSinkTest extends StreamTest { public InputStreamSinkTest() { super(actorSystemResource); } @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("InputStreamSink", Utils.UnboundedMailboxConfig()); @Test public void mustReadEventViaInputStream() throws Exception { final FiniteDuration timeout = FiniteDuration.create(300, TimeUnit.MILLISECONDS); final Sink<ByteString, InputStream> sink = StreamConverters.asInputStream(timeout); final List<ByteString> list = Collections.singletonList(ByteString.fromString("a")); final InputStream stream = Source.from(list).runWith(sink, materializer); byte[] a = new byte[1]; stream.read(a); assertTrue(Arrays.equals("a".getBytes(), a)); } }
31.411765
120
0.755306
921fa432081ba1ba89a9d4c581d71424cccbb442
1,460
package org.firstinspires.ftc.teamcode.localization; import org.firstinspires.ftc.teamcode.util.MathUtil; import org.firstinspires.ftc.teamcode.util.Pose2d; import org.firstinspires.ftc.teamcode.util.Vector2d; public class PoseExponential { MathUtil m = new MathUtil(); Vector2d fieldPositionDelta = new Vector2d(); public PoseExponential() {} public Pose2d globalOdometryUpdate(Pose2d lastPose, Pose2d poseDeltas) { //get delta theta from robot pose deltas double dtheta = poseDeltas.getTheta(); //if dtheta is small enough, certain equations model it better double sinTerm = m.epsilonEquals(dtheta, 0) ? 1 - ((dtheta*dtheta) / 6.0) : Math.sin(dtheta) / dtheta; double cosTerm = m.epsilonEquals(dtheta, 0) ? dtheta / 2.0 : (1 - Math.cos(dtheta)) / dtheta; fieldPositionDelta = new Vector2d( sinTerm * poseDeltas.getX() - cosTerm * poseDeltas.getY(), cosTerm * poseDeltas.getX() + sinTerm * poseDeltas.getY() ); Pose2d fieldPoseDelta = new Pose2d(fieldPositionDelta.rotateBy(lastPose.getTheta()), poseDeltas.getTheta()); return new Pose2d( lastPose.getX() + fieldPoseDelta.getX(), lastPose.getY() + fieldPoseDelta.getY(), //make sure to angle wrap this number so it doesnt get above 2pi m.wrapToTau(lastPose.getTheta() + fieldPoseDelta.getTheta()) ); } }
39.459459
116
0.658904
225da7c6ca5990cb138bc4052150cb00963b3a8e
2,568
package io.upit.dal.jpa; import com.google.inject.Inject; import io.upit.dal.DAO; import io.upit.dal.models.Resource; import io.upit.utils.mapping.PojoInterfaceMapper; import javax.persistence.EntityManager; import java.io.Serializable; import java.util.Date; import java.util.List; public class EntityManagerDAO<DataObject extends Resource<ID>, JpaDataObject extends DataObject, ID extends Serializable> implements DAO<DataObject, ID> { private final Class<DataObject> dataClassType; private final Class<JpaDataObject> jpaClassType; protected final EntityManager entityManager; @Inject public EntityManagerDAO(Class<DataObject> dataClassType, Class<JpaDataObject> jpaClassType, EntityManager entityManager) { this.dataClassType = dataClassType; this.jpaClassType = jpaClassType; this.entityManager = entityManager; } public JpaDataObject autoBoxForJpa(DataObject obj) { if (null == obj) { return null; } else if (jpaClassType.isInstance(obj)) { return (JpaDataObject)obj; } // Map one instance to the other return PojoInterfaceMapper.mapSiblingClass(dataClassType, jpaClassType, obj); } public List<DataObject> autoBoxForJpa(List<DataObject> objs) { //TODO: This updates the list in place for performance reasons, this may not be what wew want since this is the DAO layer and not the service layer. for (int i = 0; i < objs.size(); i++) { objs.set(i, autoBoxForJpa(objs.get(i))); } return objs; } @Override public DataObject getById(ID id) { return entityManager.find(jpaClassType, id); } @Override public DataObject create(DataObject entity) { if (null == entity) { throw new NullPointerException("Entity may not be null"); } entity = autoBoxForJpa(entity); entity.setCreated(new Date()); entityManager.persist(entity); entityManager.flush(); return entity; } @Override public DataObject update(DataObject entity) { entity = autoBoxForJpa(entity); return entityManager.merge(entity); } @Override public DataObject delete(DataObject entity) { entity = autoBoxForJpa(entity); return deleteById(entity.getId()); } @Override public DataObject deleteById(ID id) { DataObject dataObject = getById(id); if (null != dataObject) { delete(dataObject); } return dataObject; } }
30.211765
156
0.665888
044e6c89e71cecc8c3330980a22eaa23a5b31f9b
9,462
package com.checkmarx.flow.service; import com.checkmarx.flow.config.IastProperties; import com.checkmarx.flow.dto.iast.manager.dto.ResultInfo; import com.checkmarx.flow.dto.iast.manager.dto.Scan; import com.checkmarx.flow.dto.iast.manager.dto.ScanVulnerabilities; import com.checkmarx.flow.dto.iast.manager.dto.description.VulnerabilityDescription; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.LocalDateTime; import java.util.List; @Slf4j @Service public class IastServiceRequests { private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); @Setter private int updateTokenSeconds; private final IastProperties iastProperties; private String authTokenHeader; private LocalDateTime authTokenHeaderDateGeneration; private String iastUrlRoot; private boolean sslEnabledOnIast; private SSLContext context; public IastServiceRequests(IastProperties iastProperties) { this.iastProperties = iastProperties; } @PostConstruct public void init() throws IOException, InterruptedException { if (iastProperties != null && iastProperties.getUpdateTokenSeconds() != null && iastProperties.getUrl() != null && iastProperties.getManagerPort() != null) { this.updateTokenSeconds = iastProperties.getUpdateTokenSeconds(); this.iastUrlRoot = iastProperties.getUrl() + ":" + iastProperties.getManagerPort() + "/iast/"; sslEnabledOnIast = iastUrlRoot.contains("https://"); loadCerToKeyStoreAndSslContext(); } } public ScanVulnerabilities apiScanVulnerabilities(Long scanId) throws IOException { return objectMapper.readValue(resultGetBodyOfDefaultConnectionToIast("scans/" + scanId + "/vulnerabilities"), ScanVulnerabilities.class); } public List<ResultInfo> apiScanResults(Long scanId, Long vulnerabilityId) throws IOException { return objectMapper.readValue( resultGetBodyOfDefaultConnectionToIast("scans/" + scanId + "/results?queryId=" + vulnerabilityId), new TypeReference<List<ResultInfo>>() { }); } public Scan apiScansScanTagFinish(String scanTag) throws IOException { return objectMapper .readValue(resultPutBodyOfDefaultConnectionToIast("scans/scan-tag/" + scanTag + "/finish"), Scan.class); } public VulnerabilityDescription apiVulnerabilitiesDescription(Long vulnerabilityId, String lang) throws IOException { return objectMapper .readValue(resultGetBodyOfDefaultConnectionToIast("vulnerabilities/" + vulnerabilityId + "/description?programmingLanguage=" + lang), VulnerabilityDescription.class); } /** * Update IAST authorization token if needed. */ private void checkAuthorization() { if (authTokenHeader == null || authTokenHeaderDateGeneration.plusSeconds(updateTokenSeconds).isBefore(LocalDateTime.now())) { authorization(); } } private String resultGetBodyOfDefaultConnectionToIast(String urlConnection) throws IOException { return resultBodyOfDefaultConnectionToIast(urlConnection, HttpMethod.GET); } private String resultPutBodyOfDefaultConnectionToIast(String urlConnection) throws IOException { return resultBodyOfDefaultConnectionToIast(urlConnection, HttpMethod.PUT); } private String resultBodyOfDefaultConnectionToIast(String urlConnection, HttpMethod requestMethod) throws IOException { log.trace("request to IAST manager. Url:" + urlConnection); URLConnection con = generateConnectionToIast(urlConnection, requestMethod); try (BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) { StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } return response.toString(); } catch (IOException e) { String msg = e.getMessage(); if (e.getMessage().contains("scans/scan-tag/") && e.getMessage().contains("/finish")) { msg = "Can't stop scan. " + msg; } if (e.getMessage().contains("/iast/scans/scan-tag/")) { msg = "Scan have to start and you must use a unique scan tag. " + "You may have used a non-unique scan tag. " + msg; } throw new IOException(msg, e); } } private URLConnection generateConnectionToIast(String urlConnection, HttpMethod requestMethod) throws IOException { checkAuthorization(); URL url = new URL(iastUrlRoot + urlConnection); URLConnection con = createUrlConnection(url, requestMethod); con.setRequestProperty("Authorization", "Bearer " + authTokenHeader); return con; } private void authorization() { try { URL url = new URL(iastUrlRoot + "login"); URLConnection con = createUrlConnection(url, HttpMethod.POST); JSONObject params = new JSONObject(); params.put("userName", iastProperties.getUsername()); params.put("password", iastProperties.getPassword()); String jsonInputString = params.toString(); try (OutputStream os = con.getOutputStream()) { byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } try (BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) { StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } authTokenHeader = response.substring(1, response.length() - 1); // remove first and last " authTokenHeaderDateGeneration = LocalDateTime.now(); } } catch (IOException e) { log.error("Can't authorize in IAST server", e); } } /** * Loads a self-signed SSL certificate if it was provided. * <p><b>Note:</b> The certificate is not validated in any way. */ private void loadCerToKeyStoreAndSslContext() { final String cerFilePath = iastProperties.getSslCertificateFilePath(); if (StringUtils.isEmpty(cerFilePath)) { return; } final String normalizedPath = FilenameUtils.separatorsToSystem(cerFilePath); try (FileInputStream fin = new FileInputStream(normalizedPath)) { CertificateFactory f = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) f.generateCertificate(fin); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); ks.setCertificateEntry("CxIAST-CxFlow", certificate); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, tmf.getTrustManagers(), null); context = sslContext; } catch (Exception e) { log.error("Couldn't load .cer file from: " + normalizedPath, e); } } private URLConnection createUrlConnection(URL url, HttpMethod requestMethod) throws IOException { if (sslEnabledOnIast) { final HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); if (context != null) { con.setSSLSocketFactory(context.getSocketFactory()); } setConnectionProperties(con, requestMethod); return con; } final HttpURLConnection con = (HttpURLConnection) url.openConnection(); setConnectionProperties(con, requestMethod); return con; } private void setConnectionProperties(HttpURLConnection con, HttpMethod requestMethod) throws ProtocolException { con.setRequestMethod(requestMethod.toString()); con.setRequestProperty("Content-Type", "application/json; utf-8"); con.setRequestProperty("Accept", "application/json"); con.setDoOutput(true); } }
43.805556
182
0.675544
35683ce5666a94c4667d329c4752a077ee55fe84
5,300
package org.firstinspires.ftc.teamcode.hardware; import com.qualcomm.robotcore.hardware.CRServo; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.DigitalChannel; import com.qualcomm.robotcore.hardware.HardwareMap; /** * Created by Reicher Robotics on 2/22/2018. */ public class RelicRobot { public HardwareMap hardwareMap; public double P = 0.5; public double I = 0.0; public double D = 0.9; public double PID_THRESH = 2.0; public double TICKS_PER_REV = 560; public double WHEEL_DIAMETER = 6.0; public double TICKS_PER_INCH = TICKS_PER_REV / WHEEL_DIAMETER / 3.14159; private String alignServoNames[] = new String[]{"alignExt"}; private String alignDigChNames[] = new String[]{"alignSide", "alignBack"}; private DigitalChannel.Mode alignDigChModes[] = new DigitalChannel.Mode[]{DigitalChannel.Mode.INPUT, DigitalChannel.Mode.INPUT}; private String driveMotorNames[] = new String[]{"lFDrive", "lRDrive", "rFDrive", "rRDrive"}; private DcMotorSimple.Direction driveMotorDirections[] = new DcMotorSimple.Direction[]{DcMotorSimple.Direction.REVERSE, DcMotorSimple.Direction.REVERSE, DcMotorSimple.Direction.FORWARD, DcMotorSimple.Direction.FORWARD}; private String conveyorMotorNames[] = new String[]{"lConveyor", "rConveyor"}; private DcMotorSimple.Direction conveyorMotorDirections[] = new DcMotorSimple.Direction[]{DcMotorSimple.Direction.FORWARD, DcMotorSimple.Direction.REVERSE}; private String platformServoNames[] = new String[]{"lPlat", "rPlat", "gripper"}; private String ramBarCRServoNames[] = new String[]{"ramBarRot"}; private CRServo.Direction ramBarCRServoDirections[] = new CRServo.Direction[]{CRServo.Direction.REVERSE}; private String ramBarAnInNames[] = new String[]{"ramBarAng"}; private String jewelDetectionColorSensorNames[] = new String[]{"jewDetColor"}; private String jewelRemoverServoNames[] = new String[]{"jewRemExt", "jewRemHit"}; private String phoneRotatorServoNames[] = new String[]{"phoneRot"}; private String relicExtMotorNames[] = new String[]{"relicExt"}; private DcMotorSimple.Direction relicExtMotorDirections[] = new DcMotorSimple.Direction[]{DcMotorSimple.Direction.REVERSE}; private String relicGrabServoNames[] = new String[]{"relicWrist", "relicClaw"}; private String imuNames[] = new String[]{"imu"}; private String rangeSensorNames[] = new String[]{"leftRS", "backRS", "rightRS"}; private String glyphDetectionSensorNames[] = new String[]{"firGlyphS", "secGlyphS"}; public AlignmentBar alignmentBar = null; public DriveMecanum driveMecanum = null; public GlyphConveyors glyphConveyors = null; public GlyphPlatform glyphPlatform = null; public GlyphRamBar glyphRamBar = null; public JewelDetection jewelDetection = null; public JewelRemover jewelRemover = null; public PhoneRotator phoneRotator = null; public RelicExtension relicExtension = null; public RelicGrabber relicGrabber = null; public IMU gyroIMU = null; public RangeLocator rangeLocator = null; public GlyphDetection glyphDetection = null; public RelicRobot(HardwareMap hwM){ hardwareMap = hwM; //alignmentBar = new AlignmentBar(hardwareMap, alignServoNames, alignDigChNames, alignDigChModes); driveMecanum = new DriveMecanum(hardwareMap, driveMotorNames, driveMotorDirections); glyphConveyors = new GlyphConveyors(hardwareMap, conveyorMotorNames, conveyorMotorDirections); glyphPlatform = new GlyphPlatform(hardwareMap, platformServoNames); glyphRamBar = new GlyphRamBar(hardwareMap, ramBarCRServoNames, ramBarCRServoDirections, ramBarAnInNames); jewelDetection = new JewelDetection(hardwareMap, jewelDetectionColorSensorNames); jewelRemover = new JewelRemover(hardwareMap, jewelRemoverServoNames); phoneRotator = new PhoneRotator(hardwareMap, phoneRotatorServoNames); relicExtension = new RelicExtension(hardwareMap, relicExtMotorNames, relicExtMotorDirections); relicGrabber = new RelicGrabber(hardwareMap, relicGrabServoNames); gyroIMU = new IMU(hardwareMap, imuNames[0]); rangeLocator = new RangeLocator(hardwareMap, rangeSensorNames); glyphDetection = new GlyphDetection(hardwareMap, glyphDetectionSensorNames); driveMecanum.setMotorBreak(DcMotor.ZeroPowerBehavior.BRAKE); } public void Init() { } public int convertInchToTicks(double inches){ return (int)(inches * TICKS_PER_INCH); } }
61.627907
234
0.654717
b4d911d7502356bf436acbd291085e14215b0c48
4,199
/* * Copyright 2013 Google 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.pixplicity.wizardpager.wizard.ui; import android.os.Bundle; import android.os.Handler; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.pixplicity.wizardpager.R; import com.pixplicity.wizardpager.wizard.model.MultipleFixedChoicePage; import com.pixplicity.wizardpager.wizard.model.Page; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class MultipleChoiceFragment extends WizardListFragment { public static MultipleChoiceFragment create(String key) { Bundle args = new Bundle(); args.putString(ARG_KEY, key); MultipleChoiceFragment fragment = new MultipleChoiceFragment(); fragment.setArguments(args); return fragment; } public MultipleChoiceFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MultipleFixedChoicePage fixedChoicePage = (MultipleFixedChoicePage) mPage; mChoices = new ArrayList<String>(); for (int i = 0; i < fixedChoicePage.getOptionCount(); i++) { mChoices.add(fixedChoicePage.getOptionAt(i)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = super.onCreateView(inflater, container, savedInstanceState); mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle()); // Pre-select currently selected items. new Handler().post(new Runnable() { @Override public void run() { MultipleFixedChoicePage fixedChoicePage = (MultipleFixedChoicePage) mPage; ArrayList<String> selectedItems = fixedChoicePage.getValues(); if (selectedItems == null || selectedItems.size() == 0) { return; } Set<String> selectedSet = new HashSet<String>(selectedItems); for (int i = 0; i < mChoices.size(); i++) { if (selectedSet.contains(mChoices.get(i))) { mListView.setItemChecked(i, true); } } } }); return rootView; } @Override public ArrayAdapter<String> getAdapter() { return new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, mChoices); } @Override public int getLayoutResId() { return R.layout.fragment_page_list; } @Override public void onListItemClick(AdapterView<?> l, View v, int position, long id) { SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions(); ArrayList<String> selections = new ArrayList<String>(); for (int i = 0; i < checkedPositions.size(); i++) { if (checkedPositions.valueAt(i)) { selections.add( mListView.getAdapter().getItem(checkedPositions.keyAt(i)).toString()); } } MultipleFixedChoicePage fixedChoicePage = (MultipleFixedChoicePage) mPage; fixedChoicePage.setValues(selections); mPage.notifyDataChanged(true); } }
33.325397
94
0.657776
05d0b4d49a19b8ad64a1e4e37efef2d8b96e80bd
142
package io.github.yutoeguma.app.web.auth.login; /** * @author yuto.eguma */ public class LoginCheckResult { public Boolean isLogin; }
14.2
47
0.711268
19dd36b7ecc6cc0a32145415a47b7d895c2e9d9a
1,052
package cn.huanzi.qch.baseadmin.common.pojo; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.thymeleaf.util.StringUtils; /** * 分页条件 */ @Data public class PageCondition { private int page;//当前页码 private int rows;//页面大小 private String sidx;//排序字段 private String sord;//排序方式 /** * 获取JPA的分页查询对象 */ @JsonIgnore public PageRequest getPageable() { //处理非法页码 if (page <= 0) { page = 1; } //处理非法页面大小 if (rows <= 0) { rows = 10; } //处理排序 if(!StringUtils.isEmpty(sidx) && !StringUtils.isEmpty(sord)){ Direction direction = "desc".equals(sord.toLowerCase()) ? Direction.DESC : Direction.ASC; return PageRequest.of(page - 1, rows, new Sort(direction, sidx)); } return PageRequest.of(page - 1, rows); } }
25.658537
101
0.621673
18c9a94fdd06b7da275cb66d3b9af6462b3aec5a
1,170
package ro.webdata.parser.xml.lido.core.leaf.gml; import ro.webdata.parser.xml.lido.core.attribute.XmlLang; import ro.webdata.parser.xml.lido.core.complex.gmlComplexType.GmlComplexType; /** * <link rel="stylesheet" type="text/css" href="../../../../javadoc.css"/> * <div class="lido"> * <div class="lido-title">Lido documentation:</div> * <div class="lido-doc"> * <b>Definition:</b> Georeferences of the place using the GML specification.<br/> * <b>How to record:</b> Repeat this element only for language variants.<br/> * <b>Notes:</b> For further documentation on GML refer to http://www.opengis.net/gml/<br/> * * <b>Attributes:</b> * <div class="lido-attr"> * <b>lang (xml:lang)</b><br/> * </div> * </div> * </div> * @author WebData * */ public class Gml extends GmlComplexType { private XmlLang lang; public Gml() {} public Gml(GmlComplexType gmlComplexType, XmlLang lang) { super( gmlComplexType.getPoint(), gmlComplexType.getLineString(), gmlComplexType.getPolygon() ); setLang(lang); } public XmlLang getLang() { return lang; } public void setLang(XmlLang lang) { this.lang = lang; } }
25.434783
94
0.662393
44146da0f7606d90910b17ba5a3c47322ce8b103
1,553
/* * 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 com.adriens.colisnc.api.service; import com.adriens.colisnc.api.model.StepsCounter; import com.adriens.github.colisnc.colisnc.ColisCrawler; import com.adriens.github.colisnc.colisnc.ColisDataRow; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; /** * * @author 3004SAL */ @Service public class ColisService { private final Logger log = LoggerFactory.getLogger(ColisService.class); //private ColisCrawler wrap; public List<ColisDataRow> getColisRows(String itemId) throws Exception { ArrayList<ColisDataRow> out; out = ColisCrawler.getColisRows(itemId); return out; } public ColisDataRow getLatestRow(String itemId) throws Exception { return ColisCrawler.getLatest(itemId); } public ColisDataRow getOldestRow(String itemId) throws Exception { return ColisCrawler.getOldest(itemId); } public StepsCounter getNbSteps(String itemId) throws Exception { return new StepsCounter(ColisCrawler.getColisRows(itemId).size()); } public ArrayList<ColisDataRow> getLatestStatusForColisList(List<String> itemsId) throws Exception { return ColisCrawler.getLatestStatusForColisList(itemsId); } }
31.693878
104
0.721185
0ba46080508e307213abb1c6f4553bbd34875617
591
package cc.mrbird.febs.heart.dao; import cc.mrbird.febs.heart.entity.HeartBShzl; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; /** * <p> * 术后资料 Mapper 接口 * </p> * * @author viki * @since 2021-05-25 */ public interface HeartBShzlMapper extends BaseMapper<HeartBShzl> { void updateHeartBShzl(HeartBShzl heartBShzl); @Delete("update heart_b_shzl set IS_DELETEMARK=0 where fileNo=#{fileNo}") void deleteByFileNo(@Param(value = "fileNo") String fileNo); }
28.142857
81
0.724196
ab840d17223d29ed00e6706dc00b0cb5e647976c
273
package umoo.wang.beanmanager.message.server.message; import lombok.AllArgsConstructor; import lombok.Data; /** * Created by yuanchen on 2019/01/23. */ @Data @AllArgsConstructor public class RegisterMessage { private String appName; private String environmentName; }
18.2
53
0.787546
c6437734b374cb07fddefd30b25c59c29f1fc3a5
3,831
package org.infinity.passport.service.impl; import lombok.extern.slf4j.Slf4j; import org.infinity.passport.domain.User; import org.infinity.passport.service.MailService; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.context.MessageSource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; import javax.annotation.Resource; import javax.mail.internet.MimeMessage; import java.nio.charset.StandardCharsets; import java.util.Locale; /** * Service for sending emails. */ @Service @Slf4j public class MailServiceImpl implements MailService { private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; @Resource private MailProperties mailProperties; @Resource private JavaMailSenderImpl javaMailSender; @Resource private MessageSource messageSource; @Resource private SpringTemplateEngine springTemplateEngine; /** * System default email address that sends the e-mails. */ @Async @Override public void sendEmail(String[] sendTo, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, sendTo, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); message.setTo(sendTo); message.setFrom(mailProperties.getUsername(), "InfinityTeam"); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", StringUtils.arrayToCommaDelimitedString(sendTo)); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}', exception is: {}", sendTo, e.getMessage()); } } @Async @Override public void sendEmailFromTemplate(User user, String templateName, String titleKey, String baseUrl) { Locale locale = Locale.SIMPLIFIED_CHINESE; Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, baseUrl); String content = springTemplateEngine.process(templateName, context); String subject = messageSource.getMessage(titleKey, null, locale); sendEmail(new String[]{user.getEmail()}, subject, content, false, true); } @Async @Override public void sendActivationEmail(User user, String baseUrl) { log.debug("Sending activation e-mail to '{}'", user.getEmail()); sendEmailFromTemplate(user, "email/activation-email", "emailActivationTitle", baseUrl); } @Async @Override public void sendCreationEmail(User user, String baseUrl) { log.debug("Sending creation e-mail to '{}'", user.getEmail()); sendEmailFromTemplate(user, "email/creation-email", "emailActivationTitle", baseUrl); } @Async @Override public void sendPasswordResetMail(User user, String baseUrl) { log.debug("Sending password reset e-mail to '{}'", user.getEmail()); sendEmailFromTemplate(user, "email/password-reset-email", "emailResetTitle", baseUrl); } }
40.326316
119
0.690681
f8388899ad1f92f33cefdfdb9920fd46ba4fcfc2
1,872
package projeto_1.user; import com.google.inject.Inject; import jakarta.annotation.Resource; import jakarta.jws.WebService; import jakarta.xml.ws.WebServiceContext; import projeto_1.exceptions.InternalServerErrorException; import projeto_1.auth.AuthModule; import projeto_1.auth.exceptions.UnauthorizedException; import projeto_1.user.beans.User; import projeto_1.user.exceptions.DuplicateUserException; import javax.inject.Singleton; @Singleton @WebService(endpointInterface = "projeto_1.user.UserService") public class UserServiceImpl implements UserService { private final AuthModule authModule; private final UserRepository repository; @Resource WebServiceContext ctx; @Inject public UserServiceImpl(UserRepository repository, AuthModule authModule) { this.repository = repository; this.authModule = authModule; } @Override public User createUser(String name, String email, String password) throws DuplicateUserException, InternalServerErrorException { User existingUser = this.repository.findByEmail(email); if (existingUser != null) { throw new DuplicateUserException(email); } return this.repository.createOne(new User(name, email, password)); } @Override public User replaceUser(String name, String email, String password) throws UnauthorizedException, DuplicateUserException, InternalServerErrorException { User me = this.authModule.getAuthenticatedUser(ctx.getMessageContext()); int myId = me.getId(); User emailUser = this.repository.findByEmail(email); if (emailUser != null && myId != emailUser.getId()) { throw new DuplicateUserException(email); } User newMe = new User(myId, name, email, password); return this.repository.replaceOne(newMe); } }
34.666667
96
0.730235
4efd1ff362ad08b20972c2f4e56961a403d6c60e
707
package com.baeldung.java14.newfeatues; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class MultilineUnitTest { @SuppressWarnings("preview") String multiline = """ A quick brown fox jumps over a lazy dog; \ the lazy dog howls loudly."""; @SuppressWarnings("preview") String anotherMultiline = """ A quick brown fox jumps over a lazy dog; the lazy dog howls loudly."""; @Test public void givenMultilineString_whenSlashUsed_thenNoNewLine() { assertFalse(multiline.contains("\n")); assertTrue(anotherMultiline.contains("\n")); } }
26.185185
68
0.659123
cd7272cd16337e970533e27320865ed0b24b7b99
1,438
package org.frekele.elasticsearch.mapping.annotations; import org.frekele.elasticsearch.mapping.annotations.values.BoolValue; import org.frekele.elasticsearch.mapping.annotations.values.FloatValue; import org.frekele.elasticsearch.mapping.enums.FieldType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A field of type token_count is really an integer field which accepts string values, analyzes them, then indexes the number of tokens in the string. * * @author frekele - Leandro Kersting de Freitas * @see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/token-count.html">Site Elasticsearch Reference Guide.</a> */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ElasticTokenCountField { FieldType type = FieldType.TOKEN_COUNT; String suffixName() default "tokenCount"; String analyzer() default ""; BoolValue enablePositionIncrements() default @BoolValue(ignore = true); @Deprecated FloatValue boost() default @FloatValue(ignore = true); BoolValue docValues() default @BoolValue(ignore = true); BoolValue index() default @BoolValue(ignore = true); BoolValue includeInAll() default @BoolValue(ignore = true); String nullValue() default ""; BoolValue store() default @BoolValue(ignore = true); }
32.681818
150
0.768428
3908667c94e7c5a49bee7112556056391113b6d6
2,605
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.server.tables; import static org.junit.Assert.assertEquals; import org.apache.accumulo.core.master.state.tables.TableState; import org.apache.accumulo.server.tables.TableManager.IllegalTableTransitionException; import org.junit.Test; public class IllegalTableTransitionExceptionTest { final TableState oldState = TableState.ONLINE; final TableState newState = TableState.OFFLINE; final String defaultMsg = "Error transitioning from " + oldState + " state to " + newState + " state"; @Test public void testIllegalTableTransitionExceptionMessage() { String userMessage = null; try { userMessage = "User suppled message - Exception from " + oldState + " state to " + newState + " state"; throw new TableManager.IllegalTableTransitionException(oldState, newState, userMessage); } catch (IllegalTableTransitionException e) { assertEquals(userMessage, e.getMessage()); } } @Test public void testIllegalTableTransitionExceptionDefaultMessage() { try { throw new TableManager.IllegalTableTransitionException(oldState, newState); } catch (IllegalTableTransitionException e) { assertEquals(defaultMsg, e.getMessage()); } } @Test public void testIllegalTableTransitionExceptionWithNull() { try { throw new TableManager.IllegalTableTransitionException(oldState, newState, null); } catch (IllegalTableTransitionException e) { assertEquals(defaultMsg, e.getMessage()); } } @Test public void testIllegalTableTransitionExceptionEmptyMessage() { try { throw new TableManager.IllegalTableTransitionException(oldState, newState, ""); } catch (IllegalTableTransitionException e) { assertEquals(defaultMsg, e.getMessage()); } } }
35.684932
99
0.741267
44cd4664e1358f10980a18f0a94657ca8bbc8280
1,986
package com.easyctrl.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.easyctrl.ldy.activity.R; import java.util.ArrayList; public class VirtualMLIstAdapter extends BaseAdapter { private static VirtualMLIstAdapter adapter; private ArrayList<String> beans; private LayoutInflater mInflater; public class ViewHolder { public TextView strType; } private VirtualMLIstAdapter(Context context, ArrayList<String> beans) { this.mInflater = LayoutInflater.from(context); this.beans = beans; } public static VirtualMLIstAdapter getAdapter(Context context, ArrayList<String> beans) { if (adapter == null) { adapter = new VirtualMLIstAdapter(context, beans); } return adapter; } public int getCount() { return this.beans == null ? 0 : this.beans.size(); } public Object getItem(int position) { return this.beans.get(position); } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; String type = (String) this.beans.get(position); if (convertView == null) { holder = new ViewHolder(); convertView = this.mInflater.inflate(R.layout.virtual_string_type_item, parent, false); holder.strType = (TextView) convertView.findViewById(R.id.strType); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.strType.setText(sprit(type)); return convertView; } private String sprit(String type) { int start = (Integer.valueOf(type).intValue() * 10) + 1; return String.valueOf(start) + " ~ " + String.valueOf(start + 9); } }
30.553846
99
0.659114
854088bba9f2cc9bfaa518858054fc96f68a74c3
44,346
/* * [New BSD License] Copyright (c) 2011-2012, Brackit Project Team <info@brackit.org> All rights * reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * Redistributions of source code must retain the * above copyright notice, this list of conditions and the following disclaimer. * Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the Brackit Project Team nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sirix.node; import java.util.Arrays; import org.sirix.exception.SirixException; import org.sirix.node.interfaces.SimpleDeweyID; /** * @author Michael Haustein * @author Christian Mathis * @author Sebastian Baechle */ public final class SirixDeweyID implements Comparable<SirixDeweyID>, SimpleDeweyID { private final static String divisionSeparator = "."; private final static int attributeRootDivisionValue = 1; private final static int recordValueRootDivisionValue = 0; // must be an even number! when a new DeweyID is calculated, and there is a // choice, DISTANCE_TO_SIBLING/2 nodes fits between the existing node, and // the new node. For example: id1=1.7, id2=NULL; new ID will be // 1.7+DISTANCE_TO_SIBLING private static int distanceToSibling = 16; private final static int namespaceRootDivisionValue = 0; private final int[] divisionValues; private final int level; // possible bitlength for one division // private final static byte[] divisionLengthArray = // {3,4,6,8,12,16,20,24,31}; private final static byte[] divisionLengthArray = { 7, 14, 21, 28, 31 }; private final static boolean[][] bitStringAsBoolean = { { false }, { true, false }, { true, true, false }, { true, true, true, false }, { true, true, true, true } }; // the maximum divisionvalue for the corresponding length // private final static int[] maxDivisionValue = // {8,24,88,344,4440,69976,1118552,17895768, 2147483647}; private final static int[] maxDivisionValue = new int[divisionLengthArray.length]; // the complete bitlength which is needed to store a value // private final static byte[] completeDivisionLengthArray = // {5,7,9,12,16,21,25,29,36}; private final static int[] completeDivisionLengthArray = new int[divisionLengthArray.length]; // the first DeweyID, for the corresponding position in // binaryTreeSearchArray // private final static int[] binaryTreeSuffixInit={ // 0,0,0,0,1,0,0,0,0,0,0,9,25,0,0,0,0,0,0,0,0,0,4441,69977,1118553,17895769,0,89,345}; private final static int[] binaryTreeSuffixInit; // the length, for the Prefix; the position is calculated by the formuala // 2*i+2 for a 1, and 2*i+1 for a 0 // private final static byte[] binaryTreeSearchArray={ // 0,0,0,0,3,0,0,0,0,0,0,4,6,0,0,0,0,0,0,0,0,0,16,20,24,31,0,8,12,0,0,0,0,0,0,0,0 // }; private final static byte[] binaryTreeSearchArray; static { // calculates the maxDivisionValues for (int i = 0; i < divisionLengthArray.length; i++) { maxDivisionValue[i] = 1 << divisionLengthArray[i]; /* for 0-reasons the 000 cannot be used * Because Division-Value 0 is allowed */ if (i == 0) maxDivisionValue[i] -= 1; if (i != 0) { if (maxDivisionValue[i] < 0) { // if maxDivisionValue is negative, the Integer.MAX_VALUE // can be stored with these bits maxDivisionValue[i] = Integer.MAX_VALUE; } else { maxDivisionValue[i] += maxDivisionValue[i - 1]; } } } if (maxDivisionValue[divisionLengthArray.length - 1] != Integer.MAX_VALUE) { throw new SirixException( "DeweyID: It is not possible to handle all positive Integer values with the given divisionLengthArray!"); } // check if bitStringAsBoolean has as many rows as divisionLengthArray if (bitStringAsBoolean.length != divisionLengthArray.length) { throw new SirixException( "DeweyID: bitStringAsBoolean and divisionLengthArray must have equal rows!"); } // now initialize the binaryTreeSuffixInit(this is the first Division // for the corresponding row) int maxBitStringLength = 0; for (int i = 0; i < bitStringAsBoolean.length; i++) { if (bitStringAsBoolean[i].length > maxBitStringLength) { maxBitStringLength = bitStringAsBoolean[i].length; } } // calculate the max index which can appear int index = 0; for (int i = 0; i < maxBitStringLength; i++) { index = (2 * index) + 2; } // init the binarySearchTrees binaryTreeSuffixInit = new int[index + 1]; binaryTreeSearchArray = new byte[index + 1]; for (int i = 0; i < bitStringAsBoolean.length; i++) { index = 0; for (int j = 0; j < bitStringAsBoolean[i].length; j++) { if (bitStringAsBoolean[i][j] == true) { index = (2 * index) + 2; } else { index = (2 * index) + 1; } if (binaryTreeSuffixInit[index] != 0) { throw new SirixException("DeweyID: The bitStringAsBoolean is not prefixfree!"); } } if (i == 0) { // the first row begin with 1 // binaryTreeSuffixInit[index] = 1; // but we have to begin at 000 for 0-reasons binaryTreeSuffixInit[index] = 0; // because the 0-value is allowed binaryTreeSuffixInit[index] -= 1; } else { // all other rows begin after the max value of the row before binaryTreeSuffixInit[index] = maxDivisionValue[i - 1] + 1; } binaryTreeSearchArray[index] = divisionLengthArray[i]; } for (int i = 0; i < bitStringAsBoolean.length; i++) { completeDivisionLengthArray[i] = bitStringAsBoolean[i].length + divisionLengthArray[i]; } } private final int[] parseDivisionValues(String divisionPart) { if (divisionPart.charAt(divisionPart.length() - 1) != '.') divisionPart += '.'; String[] divisions = divisionPart.split("\\."); int[] divisionValues = new int[divisions.length]; int i = 0; for (String division : divisions) { try { divisionValues[i] = Integer.parseInt(division); i++; } catch (NumberFormatException e) { throw new SirixException("Division " + i + " has an invalid value: " + division, e); } } return divisionValues; } private int calcLevel(int[] divisionValues) { int level = 0; for (int i = 0; i < divisionValues.length; i++) { if (divisionValues[i] % 2 == 1) level++; } return level; } public SirixDeweyID(byte[] deweyIDbytes) { int division = 1; int currentLevel = 1; int[] tempDivision = new int[10]; int tempDivisionLength = 0; // the first division "1" is implicit there and not encoded in // deweyIDbytes tempDivision[tempDivisionLength++] = 1; // first scan deweyID bytes to get length int binaryTreeSearchIndex = 0; int helpFindingBit; boolean prefixBit = true; int suffixlength = 0; int suffix = 0; // parse complete byte-Array for (int bitIndex = 0; bitIndex < (8 * deweyIDbytes.length); bitIndex++) { switch (bitIndex % 8) { case 0: helpFindingBit = 128; break; case 1: helpFindingBit = 64; break; case 2: helpFindingBit = 32; break; case 3: helpFindingBit = 16; break; case 4: helpFindingBit = 8; break; case 5: helpFindingBit = 4; break; case 6: helpFindingBit = 2; break; default: helpFindingBit = 1; break; } if (prefixBit) { // still parsing the prefix if ((deweyIDbytes[bitIndex / 8] & helpFindingBit) == helpFindingBit) { // bit is set // binaryTreeSearchIndex = (((2 * binaryTreeSearchIndex) + 2)); binaryTreeSearchIndex = (((binaryTreeSearchIndex << 1) + 2)); } else { // bit is not set // binaryTreeSearchIndex = (((2 * binaryTreeSearchIndex) + 1)); binaryTreeSearchIndex = (((binaryTreeSearchIndex << 1) + 1)); } if ((binaryTreeSearchArray.length > binaryTreeSearchIndex) && (binaryTreeSearchArray[binaryTreeSearchIndex] != 0)) { // division found; prefixBit = false; // memorize we found the complete prefix suffixlength = binaryTreeSearchArray[binaryTreeSearchIndex]; // initialize suffix suffix = binaryTreeSuffixInit[binaryTreeSearchIndex]; } } else { // prefix already found, so we are calculating the suffix if ((deweyIDbytes[bitIndex / 8] & helpFindingBit) == helpFindingBit) { // bit is set suffix += 1 << suffixlength - 1; } suffixlength--; if (suffixlength == 0) { // -1 is not a valid Divisionvalue if (suffix != -1) { division++; if (tempDivisionLength == tempDivision.length) { int[] newTempDivision = new int[tempDivisionLength + 5]; System.arraycopy(tempDivision, 0, newTempDivision, 0, tempDivisionLength); tempDivision = newTempDivision; } tempDivision[tempDivisionLength++] = suffix; if (suffix % 2 == 1) currentLevel++; } prefixBit = true; binaryTreeSearchIndex = 0; } } } this.level = currentLevel; this.divisionValues = new int[division]; System.arraycopy(tempDivision, 0, divisionValues, 0, division); } public SirixDeweyID(byte[] deweyIDbytes, int offset, int length) { int division = 1; int currentLevel = 1; int[] tempDivision = new int[10]; int tempDivisionLength = 0; // the first division "1" is implicit there and not encoded in // deweyIDbytes tempDivision[tempDivisionLength++] = 1; // first scan deweyID bytes to get length int binaryTreeSearchIndex = 0; int helpFindingBit; boolean prefixBit = true; int suffixlength = 0; int suffix = 0; // parse complete byte-Array int end = 8 * length; for (int bitIndex = 0; bitIndex < end; bitIndex++) { switch (bitIndex % 8) { case 0: helpFindingBit = 128; break; case 1: helpFindingBit = 64; break; case 2: helpFindingBit = 32; break; case 3: helpFindingBit = 16; break; case 4: helpFindingBit = 8; break; case 5: helpFindingBit = 4; break; case 6: helpFindingBit = 2; break; default: helpFindingBit = 1; break; } if (prefixBit) { // still parsing the prefix if ((deweyIDbytes[offset + bitIndex / 8] & helpFindingBit) == helpFindingBit) { // bit is set binaryTreeSearchIndex = (((2 * binaryTreeSearchIndex) + 2)); } else { // bit is not set binaryTreeSearchIndex = (((2 * binaryTreeSearchIndex) + 1)); } if ((binaryTreeSearchArray.length > binaryTreeSearchIndex) && (binaryTreeSearchArray[binaryTreeSearchIndex] != 0)) { // division found; prefixBit = false; // memorize we found the complete prefix suffixlength = binaryTreeSearchArray[binaryTreeSearchIndex]; // initialize suffix suffix = binaryTreeSuffixInit[binaryTreeSearchIndex]; } } else { // prefix already found, so we are calculating the suffix if ((deweyIDbytes[offset + bitIndex / 8] & helpFindingBit) == helpFindingBit) { // bit is set suffix += 1 << suffixlength - 1; } suffixlength--; if (suffixlength == 0) { // -1 is not a valid Divisionvalue if (suffix != -1) { division++; if (tempDivisionLength == tempDivision.length) { int[] newTempDivision = new int[tempDivisionLength + 5]; System.arraycopy(tempDivision, 0, newTempDivision, 0, tempDivisionLength); tempDivision = newTempDivision; } tempDivision[tempDivisionLength++] = suffix; if (suffix % 2 == 1) currentLevel++; } prefixBit = true; binaryTreeSearchIndex = 0; } } } this.level = currentLevel; this.divisionValues = new int[division]; System.arraycopy(tempDivision, 0, divisionValues, 0, division); } public SirixDeweyID(int[] divisionValues) { this.divisionValues = Arrays.copyOf(divisionValues, divisionValues.length); this.level = calcLevel(this.divisionValues); } public SirixDeweyID(int[] divisionValues, int level) { this.divisionValues = Arrays.copyOf(divisionValues, divisionValues.length); this.level = level; } public SirixDeweyID(int length, int[] divisionValues) { this.divisionValues = Arrays.copyOf(divisionValues, length); this.level = calcLevel(this.divisionValues); } public SirixDeweyID(int length, int[] divisionValues, int level) { this.divisionValues = Arrays.copyOf(divisionValues, length); this.level = level; } public SirixDeweyID(SirixDeweyID deweyID, int extraDivisionValue) { this.divisionValues = new int[deweyID.divisionValues.length + 1]; if (extraDivisionValue == recordValueRootDivisionValue) { this.level = deweyID.level; } else { this.level = deweyID.level + 1; } System.arraycopy(deweyID.divisionValues, 0, divisionValues, 0, deweyID.divisionValues.length); divisionValues[divisionValues.length - 1] = extraDivisionValue; } public SirixDeweyID(String deweyID) { this.divisionValues = parseDivisionValues(deweyID); this.level = calcLevel(divisionValues); } public int getLevel() { return level - 1; } public int getNumberOfDivisions() { return divisionValues.length; } public int[] getDivisionValues() { return divisionValues; } public int getDivisionValue(int division) { if (division >= divisionValues.length) { throw new SirixException("Invalid division: " + division); } return divisionValues[division]; } /** * Calculates the number of bits, that are needed to store the choosen * division-value */ private int getDivisionBits(int division) { if (divisionValues[division] <= maxDivisionValue[0]) return completeDivisionLengthArray[0]; else if (divisionValues[division] <= maxDivisionValue[1]) return completeDivisionLengthArray[1]; else if (divisionValues[division] <= maxDivisionValue[2]) return completeDivisionLengthArray[2]; else if (divisionValues[division] <= maxDivisionValue[3]) return completeDivisionLengthArray[3]; else if (divisionValues[division] <= maxDivisionValue[4]) return completeDivisionLengthArray[4]; else if (divisionValues[division] <= maxDivisionValue[5]) return completeDivisionLengthArray[5]; else if (divisionValues[division] <= maxDivisionValue[6]) return completeDivisionLengthArray[6]; else if (divisionValues[division] <= maxDivisionValue[7]) return completeDivisionLengthArray[7]; else return completeDivisionLengthArray[8]; } /** * sets the bits in the byteArray for the given division, which has to write * its bits at position bitIndex * returns the bitIndex where the next Division can start */ private final int setDivisionBitArray(int[] divisionValues, byte[] byteArray, int division, int bitIndex) { int divisionSize = getDivisionBits(division); int prefixLength; int suffix; boolean[] prefix; prefixLength = divisionLengthArray[divisionLengthArray.length - 1]; prefix = bitStringAsBoolean[divisionLengthArray.length - 1]; suffix = divisionValues[division] - maxDivisionValue[divisionLengthArray.length - 2] - 1; for (int i = 0; i < divisionLengthArray.length - 2; i++) { if (divisionValues[division] <= maxDivisionValue[i]) { prefixLength = divisionLengthArray[i]; prefix = bitStringAsBoolean[i]; if (i != 0) { suffix = divisionValues[division] - maxDivisionValue[i - 1] - 1; } else { suffix = divisionValues[division] + 1; } break; } } // set the prefixbits for (int i = 0; i < prefix.length; i++) { if (prefix[i] == true) { byteArray[bitIndex / 8] |= (int) Math.pow(2, 7 - (bitIndex % 8)); } bitIndex++; } // calculate the rest of the bits for (int i = 1; i <= divisionSize - prefix.length; i++) { int k = 1; k = k << divisionSize - prefix.length - i; if (suffix >= k) { suffix -= k; byteArray[bitIndex / 8] |= (int) Math.pow(2, 7 - (bitIndex % 8)); } bitIndex++; } return bitIndex; } public byte[] toBytes() { return toBytes(divisionValues); } public byte[] toAttributeRootBytes() { int[] attRootDivisions = Arrays.copyOf(divisionValues, divisionValues.length + 1); attRootDivisions[attRootDivisions.length - 1] = 1; return toBytes(attRootDivisions); } private byte[] toBytes(int[] divisionValues) { // calculate needed bits for deweyID int numberOfDivisionBits = 0; // starting at second division, because the first "1" can be optimized for (int i = 1; i < divisionValues.length; i++) { if (divisionValues[i] <= maxDivisionValue[0]) numberOfDivisionBits += completeDivisionLengthArray[0]; else if (divisionValues[i] <= maxDivisionValue[1]) numberOfDivisionBits += completeDivisionLengthArray[1]; else if (divisionValues[i] <= maxDivisionValue[2]) numberOfDivisionBits += completeDivisionLengthArray[2]; else if (divisionValues[i] <= maxDivisionValue[3]) numberOfDivisionBits += completeDivisionLengthArray[3]; else if (divisionValues[i] <= maxDivisionValue[4]) numberOfDivisionBits += completeDivisionLengthArray[4]; else if (divisionValues[i] <= maxDivisionValue[5]) numberOfDivisionBits += completeDivisionLengthArray[5]; else if (divisionValues[i] <= maxDivisionValue[6]) numberOfDivisionBits += completeDivisionLengthArray[6]; else if (divisionValues[i] <= maxDivisionValue[7]) numberOfDivisionBits += completeDivisionLengthArray[7]; else numberOfDivisionBits += completeDivisionLengthArray[8]; } byte[] deweyIDbytes; if (numberOfDivisionBits % 8 == 0) { deweyIDbytes = new byte[(numberOfDivisionBits / 8)]; } else { deweyIDbytes = new byte[(numberOfDivisionBits / 8) + 1]; } int bitIndex = 0; for (int i = 1; i < this.divisionValues.length; i++) { bitIndex = setDivisionBitArray(divisionValues, deweyIDbytes, i, bitIndex); } return deweyIDbytes; } @Override public String toString() { StringBuilder out = new StringBuilder(); for (int i = 0; i < divisionValues.length; i++) { if (i != 0) { out.append(SirixDeweyID.divisionSeparator); } out.append(divisionValues[i]); } return out.toString(); } @Override public int compareTo(SirixDeweyID deweyID) { if (this == deweyID) { return 0; } int[] myD = this.divisionValues; int[] oD = deweyID.divisionValues; int myLen = myD.length; int oLen = oD.length; int len = ((myLen <= oLen) ? myLen : oLen); int pos = -1; while (++pos < len) { if (myD[pos] != oD[pos]) { return myD[pos] - oD[pos]; } } return (myLen == oLen) ? 0 : (myLen < oLen) ? -1 : 1; } @Override public boolean equals(Object object) { return ((object instanceof SirixDeweyID) && (compareTo((SirixDeweyID) object) == 0)); } public static int compare(byte[] deweyID1, byte[] deweyID2) { int length1 = deweyID1.length; int length2 = deweyID2.length; int length = ((length1 <= length2) ? length1 : length2); int pos = -1; while (++pos < length) { int v2 = deweyID2[pos] & 255; int v1 = deweyID1[pos] & 255; if (v1 != v2) { return v1 - v2; } } return length1 - length2; } public static int compareAsPrefix(byte[] deweyID1, byte[] deweyID2) { int length1 = deweyID1.length; int length2 = deweyID2.length; int length = ((length1 <= length2) ? length1 : length2); int pos = -1; while (++pos < length) { int v2 = deweyID2[pos] & 255; int v1 = deweyID1[pos] & 255; if (v1 != v2) { return v1 - v2; } } return (length1 <= length2) ? 0 : 1; } public boolean isSelfOf(SirixDeweyID deweyID) { return compareTo(deweyID) == 0; } public boolean isAttributeOf(SirixDeweyID deweyID) { int[] myD = divisionValues; int[] oD = deweyID.divisionValues; int myLen = myD.length; int oLen = oD.length; if (oLen != myLen - 2) { return false; } int len = oLen; int pos = -1; while (++pos < len) { if (myD[pos] != oD[pos]) { return false; } } return ((myD[myLen - 2] == 1) && (myD[myLen - 1] % 2 != 0)); } public boolean isAncestorOf(SirixDeweyID deweyID) { int[] myD = divisionValues; int[] oD = deweyID.divisionValues; int myLen = myD.length; int oLen = oD.length; if (myLen >= oLen) { return false; } int len = myLen; int pos = -1; while (++pos < len) { if (myD[pos] != oD[pos]) { return false; } } return true; } public boolean isAncestorOrSelfOf(SirixDeweyID deweyID) { int[] myD = divisionValues; int[] oD = deweyID.divisionValues; int myLen = myD.length; int oLen = oD.length; if (myLen > oLen) { return false; } int len = myLen; int pos = -1; while (++pos < len) { if (myD[pos] != oD[pos]) { return false; } } return true; } public boolean isParentOf(SirixDeweyID deweyID) { int[] myD = divisionValues; int[] oD = deweyID.divisionValues; int myLen = myD.length; int oLen = oD.length; if ((myLen - oLen != -1) && ((myLen != oLen - 2) || (oD[oLen - 2] != 1))) { return false; } int len = myLen; int pos = -1; while (++pos < len) { if (myD[pos] != oD[pos]) { return false; } } return true; } public boolean isPrecedingSiblingOf(SirixDeweyID deweyID) { if (!isSiblingOf(deweyID)) { return false; } int myLen = divisionValues.length; int oLen = deweyID.divisionValues.length; int checkPos = Math.min(myLen - 1, oLen - 1); return ((divisionValues[checkPos] < deweyID.divisionValues[checkPos])); } public boolean isPrecedingOf(SirixDeweyID deweyID) { return ((compareTo(deweyID) < 0) && (!isAncestorOf(deweyID))); } public boolean isSiblingOf(SirixDeweyID deweyID) { if ((level == 0 || deweyID.level == 0) || (level != deweyID.level)) { return false; } final int[] myD = divisionValues; final int[] oD = deweyID.divisionValues; int myP = 0; int oP = 0; while ((myP < myD.length - 1) && (oP < oD.length - 1)) { if (myD[myP] == oD[oP]) { myP++; oP++; } else if (((myD[myP] % 2 == 0)) || (oD[oP] % 2 == 0)) { while (myD[myP] % 2 == 0) myP++; while (oD[oP] % 2 == 0) oP++; int rLenDiff = (myD.length - myP) - (oD.length - oP); return (rLenDiff == 0); } else { return false; } } return ((myD[myP] != 1) && (oD[oP] != 1) && (myD[myP] != oD[oP])); } public boolean isFollowingSiblingOf(SirixDeweyID deweyID) { if (!isSiblingOf(deweyID)) { return false; } int myLen = divisionValues.length; int oLen = deweyID.divisionValues.length; int checkPos = Math.min(myLen - 1, oLen - 1); return ((divisionValues[checkPos] > deweyID.divisionValues[checkPos])); } public boolean isFollowingOf(SirixDeweyID deweyID) { return (compareTo(deweyID) > 0) && (!isAncestorOf(deweyID)) && (!deweyID.isAncestorOf(this)); } public boolean isChildOf(SirixDeweyID deweyID) { return deweyID.isParentOf(this); } public boolean isDescendantOf(SirixDeweyID deweyID) { return deweyID.isAncestorOf(this); } public boolean isDescendantOrSelfOf(SirixDeweyID deweyID) { return deweyID.isAncestorOrSelfOf(this); } public boolean isAttribute() { return ((level > 1) && (divisionValues.length > 2) && (divisionValues[divisionValues.length - 2] == SirixDeweyID.attributeRootDivisionValue)); } public boolean isRecordValue() { return ((level > 1) && (divisionValues.length > 1) && (divisionValues[divisionValues.length - 1] == SirixDeweyID.recordValueRootDivisionValue)); } public boolean isAttributeRoot() { return ((level > 1) && (divisionValues.length > 1) && (divisionValues[divisionValues.length - 1] == SirixDeweyID.attributeRootDivisionValue)); } // ancestor or self semantics public SirixDeweyID getAncestor(int level) { if (this.level == level) { return this; } if (this.level < level) { return null; } int currDivision = 0; for (int i = 0; i < level; i++) { while (divisionValues[currDivision] % 2 == 0) currDivision++; currDivision++; } SirixDeweyID newID = new SirixDeweyID(Arrays.copyOf(divisionValues, currDivision), level); return newID; } /** * Like {@link #getAncestor(int)} but it checks in addition whether the ancestor has the given * DeweyID as prefix (or whether the ancestor is itself a prefix of the given DeweyID). If the * prefix condition is not satisfied, null is returned. * * @param level * @param requiredPrefix * @return */ public SirixDeweyID getAncestor(int level, SirixDeweyID requiredPrefix) { if (this.level < level) { return null; } int currDivision = 0; for (int i = 0; i < level; i++) { while (this.divisionValues[currDivision] % 2 == 0) { if (currDivision < requiredPrefix.divisionValues.length && this.divisionValues[currDivision] != requiredPrefix.divisionValues[currDivision]) { return null; } currDivision++; } if (currDivision < requiredPrefix.divisionValues.length && this.divisionValues[currDivision] != requiredPrefix.divisionValues[currDivision]) { return null; } currDivision++; } if (this.level == level) { return this; } else { return new SirixDeweyID(Arrays.copyOf(divisionValues, currDivision), level); } } public SirixDeweyID[] getAncestors() { if (level == 0) { return null; } SirixDeweyID id = this; SirixDeweyID[] ancestors = new SirixDeweyID[level]; for (int i = level; i > 0; i--) { ancestors[i - 1] = id.getParent(); id = id.getParent(); } return ancestors; } public SirixDeweyID[] getAncestors(SirixDeweyID lca) { if (!lca.isAncestorOf(this)) { return null; } SirixDeweyID id = this; SirixDeweyID[] ancestors = new SirixDeweyID[this.level - lca.getLevel() - 1]; for (int i = ancestors.length; i > 0; i--) { ancestors[i - 1] = id.getParent(); id = id.getParent(); } return ancestors; } public boolean isLCA(SirixDeweyID id) { return (getLCA(id).compareTo(id) == 0); } public SirixDeweyID getLCA(SirixDeweyID id) { int common_length = 0; int length = Math.min(divisionValues.length, id.divisionValues.length); for (int i = 0; i < length; i++) { if (id.divisionValues[i] == divisionValues[i]) common_length++; else break; } while (divisionValues[common_length - 1] % 2 == 0) common_length--; return new SirixDeweyID(Arrays.copyOf(divisionValues, common_length)); } public int calcLCALevel(SirixDeweyID id) { int lcaLevel = 0; int a = divisionValues.length; int b = id.divisionValues.length; int maxPos = ((a <= b) ? a : b); for (int i = 0; i < maxPos; i++) { if (id.divisionValues[i] == divisionValues[i]) { if (divisionValues[i] % 2 != 0) { lcaLevel++; } } else { break; } } return lcaLevel; } public SirixDeweyID getParent() { if (level == 0) { return null; } int i = divisionValues.length - 2; while ((i >= 0) && (divisionValues[i] % 2 == 0)) i--; SirixDeweyID parent = new SirixDeweyID(Arrays.copyOf(divisionValues, i + 1), level - 1); return parent; } @Override public int hashCode() { return Arrays.hashCode(divisionValues); } public static SirixDeweyID newBetween(SirixDeweyID deweyID1, SirixDeweyID deweyID2) { // newBetween always returns ID of new node in same level! if ((deweyID1 == null) && (deweyID2 != null)) { // return previous sibling ID of deweyID2 if deweyID2 is first child int i = deweyID2.divisionValues.length - 2; // start at penultimate // position while ((i >= 0) && (deweyID2.divisionValues[i] % 2 == 0)) i--; // scan to front while even divisions are located i++; // skip the 2s while (deweyID2.divisionValues[i] == 2 || deweyID2.divisionValues[i] == recordValueRootDivisionValue) i++; int divisions; int[] divisionValues; if ((deweyID2.divisionValues[i] % 2 == 1) && (deweyID2.divisionValues[i] > 3)) { // odd Division > 3, last division / 2 divisions = deweyID2.getNumberOfDivisions(); divisionValues = new int[divisions]; for (int j = 0; j < divisions - 1; j++) { divisionValues[j] = deweyID2.divisionValues[j]; } divisionValues[divisions - 1] = deweyID2.divisionValues[divisions - 1] / 2; // make sure last division is odd if (divisionValues[divisions - 1] % 2 == 0) divisionValues[divisions - 1]++; } else if (deweyID2.divisionValues[i] == 3) { // x.3 gets x.2.distanceToSibling+1 divisions = deweyID2.getNumberOfDivisions() + 1; divisionValues = new int[divisions]; for (int j = 0; j < divisions - 1; j++) { divisionValues[j] = deweyID2.divisionValues[j]; } divisionValues[i] = 2; divisionValues[i + 1] = distanceToSibling + 1; } else { // even division > 2 // current division /2 divisions = i + 1; divisionValues = new int[divisions]; for (int j = 0; j < divisions - 1; j++) { divisionValues[j] = deweyID2.divisionValues[j]; } divisionValues[i] = deweyID2.divisionValues[i] / 2; // make sure last division is odd if (divisionValues[i] % 2 == 0) divisionValues[i]++; } SirixDeweyID newID = new SirixDeweyID(Arrays.copyOf(divisionValues, divisions), deweyID2.level); return newID; } else if ((deweyID1 != null) && (deweyID2 == null)) { int[] tmp = Arrays.copyOf(deweyID1.divisionValues, deweyID1.divisionValues.length); tmp[tmp.length - 1] += distanceToSibling; SirixDeweyID newID = new SirixDeweyID(tmp, deweyID1.level); return newID; } else // two IDs given { if (deweyID1.compareTo(deweyID2) >= 0) throw new SirixException("DeweyID [newBetween]: deweyID1 is greater or equal to deweyID2"); if (deweyID1.getParent().compareTo(deweyID2.getParent()) != 0) throw new SirixException("DeweyID [newBetween]: deweyID1 and deweyID2 are no siblings"); // return new deweyID between deweyID1 and deweyID2 // first scan to first different divisions int i = 0; while (deweyID1.divisionValues[i] == deweyID2.divisionValues[i]) i++; int divisions; int[] divisionValues; if (deweyID2.divisionValues[i] - deweyID1.divisionValues[i] > 2) { // ready, because odd division fits // between the two given IDs divisions = i + 1; divisionValues = new int[divisions]; for (int j = 0; j < divisions - 1; j++) { divisionValues[j] = deweyID1.divisionValues[j]; } divisionValues[divisions - 1] = deweyID1.divisionValues[divisions - 1] + (deweyID2.divisionValues[divisions - 1] - deweyID1.divisionValues[divisions - 1]) / 2; // take care that division is odd if ((divisionValues[divisions - 1] % 2) == 0) divisionValues[divisions - 1] -= 1; } else if (deweyID2.divisionValues[i] - deweyID1.divisionValues[i] == 2) { // only one division number fits between // perhaps an odd division fits in if (deweyID2.divisionValues[i] % 2 == 0) { // odd division fits in divisions = i + 1; divisionValues = new int[divisions]; for (int j = 0; j < divisions - 1; j++) { divisionValues[j] = deweyID1.divisionValues[j]; } divisionValues[divisions - 1] = deweyID1.divisionValues[divisions - 1] + 1; } else { // only even division fits in divisions = i + 2; divisionValues = new int[divisions]; for (int j = 0; j < divisions - 1; j++) { divisionValues[j] = deweyID1.divisionValues[j]; } divisionValues[divisions - 2] += 1; divisionValues[divisions - 1] = distanceToSibling + 1; } } else { // one deweyID is parsed to the end but still no new deweyID // between found // and no DeweyID fits between the two divisions(these cases are // handled with above // two possibilities if (deweyID1.divisionValues[i] % 2 == 1) { // deweyID1 complete i++; // overparse the 2 while (deweyID2.divisionValues[i] == 2) i++; if (deweyID2.divisionValues[i] == 3) { // last division is 3 // add 2.distanceToSibling+1 divisions = i + 2; divisionValues = new int[divisions]; for (int j = 0; j < divisions - 2; j++) { divisionValues[j] = deweyID2.divisionValues[j]; } divisionValues[divisions - 2] = 2; divisionValues[divisions - 1] = distanceToSibling + 1; } else { // division >3 divisions = i + 1; divisionValues = new int[divisions]; for (int j = 0; j < divisions; j++) { divisionValues[j] = deweyID2.divisionValues[j]; } divisionValues[divisions - 1] /= 2; // make sure division is odd if (divisionValues[divisions - 1] % 2 == 0) divisionValues[divisions - 1] += 1; } } else { // deweyID2 complete i++; divisions = i + 1; divisionValues = new int[divisions]; for (int j = 0; j < divisions; j++) { divisionValues[j] = deweyID1.divisionValues[j]; } if (deweyID1.divisionValues[i] % 2 == 1) { // odd // last division + distanceToSibling divisionValues[divisions - 1] += distanceToSibling; } else { // even divisionValues[divisions - 1] += distanceToSibling - 1; // lastdivision + (distanceToSibling - 1); } } } SirixDeweyID newID = new SirixDeweyID(divisionValues, deweyID1.level); return newID; } } public final static SirixDeweyID newRootID() { return new SirixDeweyID(new int[] { 1 }, 1); } public final SirixDeweyID getNewChildID() { return (level > 0) ? new SirixDeweyID(this, SirixDeweyID.distanceToSibling + 1) : new SirixDeweyID(this, 1); } public final SirixDeweyID getNewChildID(int division) { return new SirixDeweyID(this, division); } public final SirixDeweyID getNewAttributeID() { int[] childDivisions = Arrays.copyOf(divisionValues, divisionValues.length + 2); childDivisions[divisionValues.length] = SirixDeweyID.attributeRootDivisionValue; childDivisions[divisionValues.length + 1] = SirixDeweyID.distanceToSibling + 1; SirixDeweyID newID = new SirixDeweyID(childDivisions, level + 1); return newID; } public final SirixDeweyID getNewNamespaceID() { int[] childDivisions = Arrays.copyOf(divisionValues, divisionValues.length + 2); childDivisions[divisionValues.length] = SirixDeweyID.namespaceRootDivisionValue; childDivisions[divisionValues.length + 1] = SirixDeweyID.distanceToSibling + 1; SirixDeweyID newID = new SirixDeweyID(childDivisions, level + 1); return newID; } public final SirixDeweyID getNewRecordID() { int[] childDivisions = Arrays.copyOf(divisionValues, divisionValues.length + 2); childDivisions[divisionValues.length] = SirixDeweyID.recordValueRootDivisionValue; childDivisions[divisionValues.length + 1] = SirixDeweyID.distanceToSibling + 1; SirixDeweyID newID = new SirixDeweyID(childDivisions, level + 1); return newID; } public final SirixDeweyID getRecordValueRootID() { return new SirixDeweyID(this, SirixDeweyID.recordValueRootDivisionValue); } public final SirixDeweyID getAttributeRootID() { return new SirixDeweyID(this, SirixDeweyID.attributeRootDivisionValue); } public static String getDivisionLengths() { StringBuffer output = new StringBuffer(); for (int i = 0; i < divisionLengthArray.length; i++) { output.append(divisionLengthArray[i] + " "); } return new String(output); } public static String getPrefixes() { StringBuffer output = new StringBuffer(); for (int i = 0; i < bitStringAsBoolean.length; i++) { for (int j = 0; j < bitStringAsBoolean[i].length; j++) { output.append(bitStringAsBoolean[i][j] + " "); } output.append(";"); } return new String(output); } public StringBuffer list() { StringBuffer output = new StringBuffer(); output.append("" + this.toString()); output.append("\t"); // calculate needed bits for deweyID byte[] byteArray = this.toBytes(); for (int i = 0; i < byteArray.length; i++) { output.append(byteArray[i] + "\t"); } output.append(""); int helpFindingBit; for (int bitIndex = 0; bitIndex < (8 * byteArray.length); bitIndex++) { switch (bitIndex % 8) { case 0: helpFindingBit = 128; break; case 1: helpFindingBit = 64; break; case 2: helpFindingBit = 32; break; case 3: helpFindingBit = 16; break; case 4: helpFindingBit = 8; break; case 5: helpFindingBit = 4; break; case 6: helpFindingBit = 2; break; default: helpFindingBit = 1; break; } if ((byteArray[bitIndex / 8] & helpFindingBit) == helpFindingBit) { // bit is set } else { } } return output; } public boolean equals(SirixDeweyID other) { return compareTo(other) == 0; } public boolean isRoot() { return level == 1; } public boolean isDocument() { return level == 0; } /** * Checks whether this DeweyID is a prefix of the other. * * @param other the other DeweyID * @return true if this DeweyID is a prefix of the other DeweyID */ public boolean isPrefixOf(SirixDeweyID other) { if (other.divisionValues.length < this.divisionValues.length) { return false; } for (int i = 0; i < this.divisionValues.length; i++) { if (this.divisionValues[i] != other.divisionValues[i]) { return false; } } return true; } /** * Like {@link #compareTo(SirixDeweyID)} but without checking the collection ID. Only the * divisions are considered. * * @param deweyID the other DeweyID * @return -1 if this DeweyID is less than the other, 0 if they are equal, and 1 if this DeweyID * is greater than the other */ public int compareReduced(SirixDeweyID deweyID) { if (this == deweyID) { return 0; } int[] myD = this.divisionValues; int[] oD = deweyID.divisionValues; int myLen = myD.length; int oLen = oD.length; int len = ((myLen <= oLen) ? myLen : oLen); int pos = -1; while (++pos < len) { if (myD[pos] != oD[pos]) { return myD[pos] - oD[pos]; } } return (myLen == oLen) ? 0 : (myLen < oLen) ? -1 : 1; } /** * Compares this DeweyID's parent with the given DeweyID (except for the collection ID). * * @param other the other DeweyID * @return a negative number if the parent is less than the other DeweyID, 0 if they are equal, * and a positive number if the parent is greater than the other DeweyID */ public int compareParentTo(SirixDeweyID other) { int parentLength = this.divisionValues.length - 1; while (this.divisionValues[parentLength - 1] % 2 == 0) { parentLength--; } int upperBound = Math.min(parentLength, other.divisionValues.length); for (int i = 0; i < upperBound; i++) { if (this.divisionValues[i] != other.divisionValues[i]) { return (this.divisionValues[i] < other.divisionValues[i]) ? -1 : 1; } } return Integer.signum(parentLength - other.divisionValues.length); } /** * Checks whether this DeweyID is either a prefix or greater than the other DeweyID. * * @param other the other DeweyID * @return true if this DeweyID is a prefix or greater than the other DeweyID */ public boolean isPrefixOrGreater(SirixDeweyID other) { int upperBound = (this.divisionValues.length <= other.divisionValues.length) ? this.divisionValues.length : other.divisionValues.length; for (int i = 0; i < upperBound; i++) { if (this.divisionValues[i] != other.divisionValues[i]) { return (this.divisionValues[i] > other.divisionValues[i]); } } return true; } /** * Checks whether this DeweyID appended by the extraDivision is either a prefix or greater than * the other DeweyID. * * @param other the other DeweyID * @return true if this DeweyID appended by the extraDivision is a prefix or greater than the * other DeweyID */ public boolean isPrefixOrGreater(int extraDivision, SirixDeweyID other) { boolean isShorter = (this.divisionValues.length < other.divisionValues.length); int upperBound = (isShorter ? this.divisionValues.length : other.divisionValues.length); for (int i = 0; i < upperBound; i++) { if (this.divisionValues[i] != other.divisionValues[i]) { return (this.divisionValues[i] > other.divisionValues[i]); } } // check extra division if (isShorter) { if (extraDivision != other.divisionValues[upperBound]) { return (extraDivision > other.divisionValues[upperBound]); } } // at this point, one DeweyID is a prefix of the other one -> this // DeweyID is either a prefix of the other, or greater return true; } }
31.743737
117
0.618816
494488a9b89f6f4ed139dbe3a0fbaf816f801f4d
2,047
package com.brageast.blog.util; import com.brageast.blog.util.entity.Combination; import org.springframework.lang.Nullable; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @Author chenmo * 这是一些对实体操作的类 * 自己创建点语法糖qwq * 没有什么实际意义,仅此娱乐 */ public abstract class EntityUtil { public static <T> T getEntity(T t){ isNull(t, "空指针异常"); return t; } public static <T> T getEntity(T t, String message){ isNull(t, message); return t; } /** * Assert.isNull() 不算null会报错 我只想是null 才报错 * @param object * @param message */ public static void isNull(@Nullable Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } // 配合Combination食用更佳 public static <E,T> Combination<E,T> getEntity(E e, T t){ Combination<E,T> cob = new Combination<>(); cob.setEType(e); cob.setTType(t); return cob; } public static <E,T> Set<Combination<E,T>> getEntity(E[] e, T[] t){ if(e.length != t.length) return null; Set<Combination<E,T>> sc = new HashSet<>(); for(int i = 0; i < e.length; i++){ sc.add(getEntity(e[i], t[i])); } return sc; } // 向Python 那样输出 // 将+号连接符试图换成逗号qwq public static String toString(Object... objs){ StringBuilder sb = new StringBuilder(); Arrays.asList(objs).forEach(sb::append); return sb.toString(); } public static void println(Object... objs) { log(System.out::println, objs); } public static void print(Object... objs) { log(System.out::print, objs); } /** * 用法 : EntityUtil.log(log::info,"demo", "sda", 1, new date()); * 是不是方便了很多qwq, 这该死的语法糖 * @param log * @param objs */ public static void log(Ilog log, Object... objs) { log.init(toString(objs)); } @FunctionalInterface public interface Ilog { void init(String str); } }
25.271605
72
0.581339
1e657839fb0afe84ac283d75266df1123a373d62
825
package br.com.samuelweb.nfe.exception; /** * Exceção a ser lançada na ocorrência de falhas provenientes da Nota Fiscal Eletronica. * * @author Samuel Oliveira - samuk.exe@hotmail.com - www.samuelweb.com.br */ public class NfeException extends Exception { private static final long serialVersionUID = -5054900660251852366L; String message; /** * Construtor da classe. * * @param e */ public NfeException(Throwable e) { super(e); } /** * Construtor da classe. * * @param message */ public NfeException(String message) { this((Throwable) null); this.message = message; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } }
16.836735
88
0.670303
d3d4cc6892950623874815c94f87f9006d05b07a
15,247
/* */ package org.apache.batik.anim.dom; /* */ /* */ import java.util.ArrayList; /* */ import java.util.Iterator; /* */ import org.apache.batik.anim.values.AnimatableNumberListValue; /* */ import org.apache.batik.anim.values.AnimatableValue; /* */ import org.apache.batik.dom.svg.AbstractSVGList; /* */ import org.apache.batik.dom.svg.AbstractSVGNumberList; /* */ import org.apache.batik.dom.svg.ListBuilder; /* */ import org.apache.batik.dom.svg.ListHandler; /* */ import org.apache.batik.dom.svg.LiveAttributeException; /* */ import org.apache.batik.dom.svg.SVGItem; /* */ import org.apache.batik.dom.svg.SVGNumberItem; /* */ import org.apache.batik.parser.ParseException; /* */ import org.w3c.dom.Attr; /* */ import org.w3c.dom.DOMException; /* */ import org.w3c.dom.Element; /* */ import org.w3c.dom.svg.SVGAnimatedNumberList; /* */ import org.w3c.dom.svg.SVGException; /* */ import org.w3c.dom.svg.SVGNumber; /* */ import org.w3c.dom.svg.SVGNumberList; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class SVGOMAnimatedNumberList /* */ extends AbstractSVGAnimatedValue /* */ implements SVGAnimatedNumberList /* */ { /* */ protected BaseSVGNumberList baseVal; /* */ protected AnimSVGNumberList animVal; /* */ protected boolean changing; /* */ protected String defaultValue; /* */ protected boolean emptyAllowed; /* */ /* */ public SVGOMAnimatedNumberList(AbstractElement elt, String ns, String ln, String defaultValue, boolean emptyAllowed) { /* 91 */ super(elt, ns, ln); /* 92 */ this.defaultValue = defaultValue; /* 93 */ this.emptyAllowed = emptyAllowed; /* */ } /* */ /* */ /* */ /* */ /* */ public SVGNumberList getBaseVal() { /* 100 */ if (this.baseVal == null) { /* 101 */ this.baseVal = new BaseSVGNumberList(); /* */ } /* 103 */ return (SVGNumberList)this.baseVal; /* */ } /* */ /* */ /* */ /* */ /* */ public SVGNumberList getAnimVal() { /* 110 */ if (this.animVal == null) { /* 111 */ this.animVal = new AnimSVGNumberList(); /* */ } /* 113 */ return (SVGNumberList)this.animVal; /* */ } /* */ /* */ /* */ /* */ /* */ public void check() { /* 120 */ if (!this.hasAnimVal) { /* 121 */ if (this.baseVal == null) { /* 122 */ this.baseVal = new BaseSVGNumberList(); /* */ } /* 124 */ this.baseVal.revalidate(); /* 125 */ if (this.baseVal.missing) { /* 126 */ throw new LiveAttributeException(this.element, this.localName, (short)0, null); /* */ } /* */ /* */ /* 130 */ if (this.baseVal.malformed) { /* 131 */ throw new LiveAttributeException(this.element, this.localName, (short)1, this.baseVal.getValueAsString()); /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public AnimatableValue getUnderlyingValue(AnimationTarget target) { /* 143 */ SVGNumberList nl = getBaseVal(); /* 144 */ int n = nl.getNumberOfItems(); /* 145 */ float[] numbers = new float[n]; /* 146 */ for (int i = 0; i < n; i++) { /* 147 */ numbers[i] = nl.getItem(n).getValue(); /* */ } /* 149 */ return (AnimatableValue)new AnimatableNumberListValue(target, numbers); /* */ } /* */ /* */ /* */ /* */ /* */ protected void updateAnimatedValue(AnimatableValue val) { /* 156 */ if (val == null) { /* 157 */ this.hasAnimVal = false; /* */ } else { /* 159 */ this.hasAnimVal = true; /* 160 */ AnimatableNumberListValue animNumList = (AnimatableNumberListValue)val; /* */ /* 162 */ if (this.animVal == null) { /* 163 */ this.animVal = new AnimSVGNumberList(); /* */ } /* 165 */ this.animVal.setAnimatedValue(animNumList.getNumbers()); /* */ } /* 167 */ fireAnimatedAttributeListeners(); /* */ } /* */ /* */ /* */ /* */ /* */ public void attrAdded(Attr node, String newv) { /* 174 */ if (!this.changing && this.baseVal != null) { /* 175 */ this.baseVal.invalidate(); /* */ } /* 177 */ fireBaseAttributeListeners(); /* 178 */ if (!this.hasAnimVal) { /* 179 */ fireAnimatedAttributeListeners(); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ public void attrModified(Attr node, String oldv, String newv) { /* 187 */ if (!this.changing && this.baseVal != null) { /* 188 */ this.baseVal.invalidate(); /* */ } /* 190 */ fireBaseAttributeListeners(); /* 191 */ if (!this.hasAnimVal) { /* 192 */ fireAnimatedAttributeListeners(); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ public void attrRemoved(Attr node, String oldv) { /* 200 */ if (!this.changing && this.baseVal != null) { /* 201 */ this.baseVal.invalidate(); /* */ } /* 203 */ fireBaseAttributeListeners(); /* 204 */ if (!this.hasAnimVal) { /* 205 */ fireAnimatedAttributeListeners(); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class BaseSVGNumberList /* */ extends AbstractSVGNumberList /* */ { /* */ protected boolean missing; /* */ /* */ /* */ /* */ /* */ protected boolean malformed; /* */ /* */ /* */ /* */ /* */ /* */ protected DOMException createDOMException(short type, String key, Object[] args) { /* 229 */ return SVGOMAnimatedNumberList.this.element.createDOMException(type, key, args); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected SVGException createSVGException(short type, String key, Object[] args) { /* 238 */ return ((SVGOMElement)SVGOMAnimatedNumberList.this.element).createSVGException(type, key, args); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ protected Element getElement() { /* 246 */ return (Element)SVGOMAnimatedNumberList.this.element; /* */ } /* */ /* */ /* */ /* */ /* */ protected String getValueAsString() { /* 253 */ Attr attr = SVGOMAnimatedNumberList.this.element.getAttributeNodeNS(SVGOMAnimatedNumberList.this.namespaceURI, SVGOMAnimatedNumberList.this.localName); /* 254 */ if (attr == null) { /* 255 */ return SVGOMAnimatedNumberList.this.defaultValue; /* */ } /* 257 */ return attr.getValue(); /* */ } /* */ /* */ /* */ /* */ /* */ protected void setAttributeValue(String value) { /* */ try { /* 265 */ SVGOMAnimatedNumberList.this.changing = true; /* 266 */ SVGOMAnimatedNumberList.this.element.setAttributeNS(SVGOMAnimatedNumberList.this.namespaceURI, SVGOMAnimatedNumberList.this.localName, value); /* */ } finally { /* 268 */ SVGOMAnimatedNumberList.this.changing = false; /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ protected void resetAttribute() { /* 276 */ super.resetAttribute(); /* 277 */ this.missing = false; /* 278 */ this.malformed = false; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected void resetAttribute(SVGItem item) { /* 287 */ super.resetAttribute(item); /* 288 */ this.missing = false; /* 289 */ this.malformed = false; /* */ } /* */ /* */ /* */ /* */ /* */ protected void revalidate() { /* 296 */ if (this.valid) { /* */ return; /* */ } /* */ /* 300 */ this.valid = true; /* 301 */ this.missing = false; /* 302 */ this.malformed = false; /* */ /* 304 */ String s = getValueAsString(); /* 305 */ boolean isEmpty = (s != null && s.length() == 0); /* 306 */ if (s == null || (isEmpty && !SVGOMAnimatedNumberList.this.emptyAllowed)) { /* 307 */ this.missing = true; /* */ return; /* */ } /* 310 */ if (isEmpty) { /* 311 */ this.itemList = new ArrayList(1); /* */ } else { /* */ try { /* 314 */ ListBuilder builder = new ListBuilder((AbstractSVGList)this); /* */ /* 316 */ doParse(s, (ListHandler)builder); /* */ /* 318 */ if (builder.getList() != null) { /* 319 */ clear(this.itemList); /* */ } /* 321 */ this.itemList = builder.getList(); /* 322 */ } catch (ParseException e) { /* 323 */ this.itemList = new ArrayList(1); /* 324 */ this.valid = true; /* 325 */ this.malformed = true; /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected class AnimSVGNumberList /* */ extends AbstractSVGNumberList /* */ { /* */ protected DOMException createDOMException(short type, String key, Object[] args) { /* 348 */ return SVGOMAnimatedNumberList.this.element.createDOMException(type, key, args); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected SVGException createSVGException(short type, String key, Object[] args) { /* 357 */ return ((SVGOMElement)SVGOMAnimatedNumberList.this.element).createSVGException(type, key, args); /* */ } /* */ /* */ /* */ /* */ /* */ protected Element getElement() { /* 364 */ return (Element)SVGOMAnimatedNumberList.this.element; /* */ } /* */ /* */ /* */ /* */ /* */ public int getNumberOfItems() { /* 371 */ if (SVGOMAnimatedNumberList.this.hasAnimVal) { /* 372 */ return super.getNumberOfItems(); /* */ } /* 374 */ return SVGOMAnimatedNumberList.this.getBaseVal().getNumberOfItems(); /* */ } /* */ /* */ /* */ /* */ /* */ public SVGNumber getItem(int index) throws DOMException { /* 381 */ if (SVGOMAnimatedNumberList.this.hasAnimVal) { /* 382 */ return super.getItem(index); /* */ } /* 384 */ return SVGOMAnimatedNumberList.this.getBaseVal().getItem(index); /* */ } /* */ /* */ /* */ /* */ /* */ protected String getValueAsString() { /* 391 */ if (this.itemList.size() == 0) { /* 392 */ return ""; /* */ } /* 394 */ StringBuffer sb = new StringBuffer(this.itemList.size() * 8); /* 395 */ Iterator<SVGItem> i = this.itemList.iterator(); /* 396 */ if (i.hasNext()) { /* 397 */ sb.append(((SVGItem)i.next()).getValueAsString()); /* */ } /* 399 */ while (i.hasNext()) { /* 400 */ sb.append(getItemSeparator()); /* 401 */ sb.append(((SVGItem)i.next()).getValueAsString()); /* */ } /* 403 */ return sb.toString(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ protected void setAttributeValue(String value) {} /* */ /* */ /* */ /* */ /* */ public void clear() throws DOMException { /* 416 */ throw SVGOMAnimatedNumberList.this.element.createDOMException((short)7, "readonly.number.list", null); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public SVGNumber initialize(SVGNumber newItem) throws DOMException, SVGException { /* 426 */ throw SVGOMAnimatedNumberList.this.element.createDOMException((short)7, "readonly.number.list", null); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public SVGNumber insertItemBefore(SVGNumber newItem, int index) throws DOMException, SVGException { /* 437 */ throw SVGOMAnimatedNumberList.this.element.createDOMException((short)7, "readonly.number.list", null); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public SVGNumber replaceItem(SVGNumber newItem, int index) throws DOMException, SVGException { /* 448 */ throw SVGOMAnimatedNumberList.this.element.createDOMException((short)7, "readonly.number.list", null); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public SVGNumber removeItem(int index) throws DOMException { /* 457 */ throw SVGOMAnimatedNumberList.this.element.createDOMException((short)7, "readonly.number.list", null); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public SVGNumber appendItem(SVGNumber newItem) throws DOMException { /* 466 */ throw SVGOMAnimatedNumberList.this.element.createDOMException((short)7, "readonly.number.list", null); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected void setAnimatedValue(float[] values) { /* 475 */ int size = this.itemList.size(); /* 476 */ int i = 0; /* 477 */ while (i < size && i < values.length) { /* 478 */ SVGNumberItem n = this.itemList.get(i); /* 479 */ n.setValue(values[i]); /* 480 */ i++; /* */ } /* 482 */ while (i < values.length) { /* 483 */ appendItemImpl(new SVGNumberItem(values[i])); /* 484 */ i++; /* */ } /* 486 */ while (size > values.length) { /* 487 */ removeItemImpl(--size); /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected void resetAttribute() {} /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected void resetAttribute(SVGItem item) {} /* */ /* */ /* */ /* */ /* */ /* */ protected void revalidate() { /* 510 */ this.valid = true; /* */ } /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/batik/anim/dom/SVGOMAnimatedNumberList.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
29.377649
167
0.455893
40fe11d8b51d91ee82cb61d0c81385e7d1966d4d
850
package org.acme.entities; import com.fasterxml.jackson.annotation.JsonBackReference; import io.quarkus.hibernate.orm.panache.PanacheEntity; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.List; @Data @Entity @Table(name = "users") public class UserEntity extends PanacheEntity { @NotNull @Column(nullable = false) private String name; @JsonBackReference(value = "userTasks") @OneToMany(mappedBy = "user") private List<TaskEntity> tasks; @Override public String toString() { return "UserEntity{" + "name='" + name + '\'' + ", tasks=" + tasks + ", id=" + id + '}'; } }
23.611111
58
0.658824
52a6f88f5fba91ceabb0c925f7107be8e1fd9537
9,981
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.infrastructure.jobs.service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.List; import org.apache.fineract.infrastructure.core.service.Page; import org.apache.fineract.infrastructure.core.service.PaginationHelper; import org.apache.fineract.infrastructure.core.service.RoutingDataSource; import org.apache.fineract.infrastructure.core.service.SearchParameters; import org.apache.fineract.infrastructure.jobs.data.JobDetailData; import org.apache.fineract.infrastructure.jobs.data.JobDetailHistoryData; import org.apache.fineract.infrastructure.jobs.exception.JobNotFoundException; import org.apache.fineract.infrastructure.jobs.exception.OperationNotAllowedException; import org.apache.fineract.infrastructure.security.utils.ColumnValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; @Service public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerReadService { private final JdbcTemplate jdbcTemplate; private final ColumnValidator columnValidator; private final PaginationHelper<JobDetailHistoryData> paginationHelper = new PaginationHelper<>(); @Autowired public SchedulerJobRunnerReadServiceImpl(final RoutingDataSource dataSource, final ColumnValidator columnValidator) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.columnValidator = columnValidator; } @Override public List<JobDetailData> findAllJobDeatils() { final JobDetailMapper detailMapper = new JobDetailMapper(); final String sql = detailMapper.schema(); final List<JobDetailData> JobDeatils = this.jdbcTemplate.query(sql, detailMapper, new Object[] {}); return JobDeatils; } @Override public JobDetailData retrieveOne(final Long jobId) { try { final JobDetailMapper detailMapper = new JobDetailMapper(); final String sql = detailMapper.schema() + " where job.id=?"; return this.jdbcTemplate.queryForObject(sql, detailMapper, new Object[] { jobId }); } catch (final EmptyResultDataAccessException e) { throw new JobNotFoundException(String.valueOf(jobId)); } } @Override public Page<JobDetailHistoryData> retrieveJobHistory(final Long jobId, final SearchParameters searchParameters) { if (!isJobExist(jobId)) { throw new JobNotFoundException(String.valueOf(jobId)); } final JobHistoryMapper jobHistoryMapper = new JobHistoryMapper(); final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(jobHistoryMapper.schema()); sqlBuilder.append(" where job.id=?"); if (searchParameters.isOrderByRequested()) { sqlBuilder.append(" order by ").append(searchParameters.getOrderBy()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy()); if (searchParameters.isSortOrderProvided()) { sqlBuilder.append(' ').append(searchParameters.getSortOrder()); this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder()); } } if (searchParameters.isLimited()) { sqlBuilder.append(" limit ").append(searchParameters.getLimit()); if (searchParameters.isOffset()) { sqlBuilder.append(" offset ").append(searchParameters.getOffset()); } } final String sqlCountRows = "SELECT FOUND_ROWS()"; return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] { jobId }, jobHistoryMapper); } @Override public boolean isUpdatesAllowed() { final String sql = "select job.display_name from job job where job.currently_running=true and job.updates_allowed=false"; final List<String> names = this.jdbcTemplate.queryForList(sql, String.class); if (names != null && names.size() > 0) { final String listVals = names.toString(); final String jobNames = listVals.substring(listVals.indexOf("[") + 1, listVals.indexOf("]")); throw new OperationNotAllowedException(jobNames); } return true; } private boolean isJobExist(final Long jobId) { boolean isJobPresent = false; try{ final String sql = "select count(*) from job job where job.id= ?"; final int count = this.jdbcTemplate.queryForObject(sql, Integer.class, new Object[] { jobId }); if (count == 1) { isJobPresent = true; } return isJobPresent; }catch(EmptyResultDataAccessException e){ return isJobPresent; } } private static final class JobDetailMapper implements RowMapper<JobDetailData> { private final StringBuilder sqlBuilder = new StringBuilder("select") .append(" job.id,job.display_name as displayName,job.next_run_time as nextRunTime,job.initializing_errorlog as initializingError,job.cron_expression as cronExpression,job.is_active as active,job.currently_running as currentlyRunning,") .append(" runHistory.version,runHistory.start_time as lastRunStartTime,runHistory.end_time as lastRunEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") .append(" from job job left join job_run_history runHistory ON job.id=runHistory.job_id and job.previous_run_start_time=runHistory.start_time "); public String schema() { return this.sqlBuilder.toString(); } @Override public JobDetailData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String displayName = rs.getString("displayName"); final Date nextRunTime = rs.getTimestamp("nextRunTime"); final String initializingError = rs.getString("initializingError"); final String cronExpression = rs.getString("cronExpression"); final boolean active = rs.getBoolean("active"); final boolean currentlyRunning = rs.getBoolean("currentlyRunning"); final Long version = rs.getLong("version"); final Date jobRunStartTime = rs.getTimestamp("lastRunStartTime"); final Date jobRunEndTime = rs.getTimestamp("lastRunEndTime"); final String status = rs.getString("status"); final String jobRunErrorMessage = rs.getString("jobRunErrorMessage"); final String triggerType = rs.getString("triggerType"); final String jobRunErrorLog = rs.getString("jobRunErrorLog"); JobDetailHistoryData lastRunHistory = null; if (version > 0) { lastRunHistory = new JobDetailHistoryData(version, jobRunStartTime, jobRunEndTime, status, jobRunErrorMessage, triggerType, jobRunErrorLog); } final JobDetailData jobDetail = new JobDetailData(id, displayName, nextRunTime, initializingError, cronExpression, active, currentlyRunning, lastRunHistory); return jobDetail; } } private static final class JobHistoryMapper implements RowMapper<JobDetailHistoryData> { private final StringBuilder sqlBuilder = new StringBuilder(200) .append(" runHistory.version,runHistory.start_time as runStartTime,runHistory.end_time as runEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") .append(" from job job join job_run_history runHistory ON job.id=runHistory.job_id"); public String schema() { return this.sqlBuilder.toString(); } @Override public JobDetailHistoryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long version = rs.getLong("version"); final Date jobRunStartTime = rs.getTimestamp("runStartTime"); final Date jobRunEndTime = rs.getTimestamp("runEndTime"); final String status = rs.getString("status"); final String jobRunErrorMessage = rs.getString("jobRunErrorMessage"); final String triggerType = rs.getString("triggerType"); final String jobRunErrorLog = rs.getString("jobRunErrorLog"); final JobDetailHistoryData jobDetailHistory = new JobDetailHistoryData(version, jobRunStartTime, jobRunEndTime, status, jobRunErrorMessage, triggerType, jobRunErrorLog); return jobDetailHistory; } } }
49.905
272
0.704539
e16d7df5d46d3f7dc46dec0746f77255d716587a
1,104
package it.univaq.disim.discovery.servicediscovery.dashboard.controller.impl; import it.univaq.disim.discovery.servicediscovery.dashboard.controller.DashboardController; import it.univaq.disim.discovery.servicediscovery.dashboard.model.ServiceInstancesResource; import it.univaq.disim.discovery.servicediscovery.dashboard.service.DashboardService; import it.univaq.disim.discovery.servicediscovery.registry.model.ServiceInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController; import java.util.List; import static org.springframework.http.ResponseEntity.ok; @RestController public class DashboardControllerImpl implements DashboardController { @Autowired private DashboardService dashboardService; @Override public ResponseEntity<ServiceInstancesResource> getInstance() { ServiceInstancesResource resource = new ServiceInstancesResource(); resource.setServiceInstances(dashboardService.getInstance()); return ok(resource); } }
39.428571
91
0.830616
24ce56aeb539b78a2609be2fea77cc57628d48b6
1,055
package com.jikezhiji.domain.command.converters; import org.springframework.data.mapping.model.SimpleTypeHolder; import java.net.URI; import java.net.URL; import java.nio.Buffer; import java.time.temporal.Temporal; import java.util.*; import java.util.regex.Pattern; /** * Created by Administrator on 2016/10/28. */ public class EnhancedSimpleTypeHolder extends SimpleTypeHolder{ private static Set<Class<?>> DEFAULT_SIMPLE_TYPES= new HashSet<>( Arrays.asList(Temporal.class,CharSequence.class,Number.class, Buffer.class, Pattern.class, UUID.class,URI.class,URL.class)); private static Set<Class<?>> getDefaultTypes(Class<?> ... classes) { Set<Class<?>> defaultTypes = new HashSet<>(DEFAULT_SIMPLE_TYPES); defaultTypes.addAll(Arrays.asList(classes)); return defaultTypes; } public EnhancedSimpleTypeHolder(Class<?> ... classes){ super(getDefaultTypes(classes), true); } public final static EnhancedSimpleTypeHolder holder = new EnhancedSimpleTypeHolder(); }
34.032258
89
0.721327
63bc49f7b717a42f028b1f58d89bb9a5cfc7abe9
8,507
package com.script.fairy; import android.util.Log; import com.script.opencvapi.LtLog; import com.script.opencvapi.AtFairy2; import com.script.opencvapi.AtFairyConfig; import com.script.opencvapi.utils.Utils; import com.script.framework.AtFairyImpl; import java.io.PrintWriter; import java.io.StringWriter; /** * Created by Administrator on 2018/6/19. */ public class CheckThread implements Runnable { private AtFairyImpl mFairy; private PublicFunction publicFunction; private int index = 0; private Object lockCheck = new Object(); private boolean mIsStoped = true; private long mTime = System.currentTimeMillis() / 1000, mTimex = 0; private long mTime1 = System.currentTimeMillis() / 1000, mTimex1 = 0; // result = publicFunction.localFindPic(392, 229, 885, 413, "IDreplace.png"); private PicTime picTime; public CheckThread(AtFairyImpl ypFairy) { mFairy = ypFairy; publicFunction = new PublicFunction(mFairy); picTime=new PicTime(392, 229, 885, 413, "IDreplace.png",0.8,mFairy); } @Override public void run() { MatTime matTime=new MatTime(mFairy); long sleep=0; boolean playerStopedStart=false; while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lockCheck) { while (this.mIsStoped ) { try { matTime.resetTime(); LtLog.i(publicFunction.getLineInfo() + "+++++++++++-+++-----------CheckTask.wait-->="); lockCheck.wait(); LtLog.i(publicFunction.getLineInfo() + "+++++++++++-+++-----------CheckTask.state-->="); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } if (index >= 50) { index = 0; } else { index = index + 1; } try { mCheckThread(); sleep=matTime.mMatTime(1174,137,70,471,0.9f); if(sleep>=600 && playerStopedStart==false){ LtLog.i(publicFunction.getLineInfo() + "+++++++++++------mFairy.playerStoped()+++++++++++-------=,sleep=" + sleep); mFairy.playerStoped(); matTime.resetTime(); playerStopedStart=true; } } catch (Exception e) { LtLog.i(e.toString()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw, true)); String str = sw.toString(); LtLog.i("============================error" + str); } } } private void mCheckThread() throws Exception { AtFairy2.OpencvResult result; boolean landStart = false; boolean resetGameStare = false; // result = publicFunction.localFindPic(392, 229, 885, 413, "IDreplace.png"); // if (result.sim >= 0.8) { // LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++++---------IDreplace=" + result); // mFairy.UpState(575); // Utils.sleep(60000); // } if(picTime.getPicTime()>=60){ LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++++---------IDreplace=" ); new TaskMain(mFairy).UpState(575); Utils.sleep(60000); picTime.resetTime(); } //登陆界面 landStart = Land(); if (landStart) { mTimex = System.currentTimeMillis() / 1000 - mTime; LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++++---------mTimex=" + mTimex); int outTiem; if(AtFairyConfig.getOption("task_id").isEmpty()){ //如果task_id 为空,在登陆界面5分钟后上报状态 outTiem=300; }else { //如果task_id 不为空,在登陆界面30分钟后上报状态 outTiem=1800; } if (mTimex >= outTiem) { new TaskMain(mFairy).UpState(577); Utils.sleep(60000); } } else { mTime = System.currentTimeMillis() / 1000; } resetGameStare=resetGame(); if(resetGameStare){ mTimex1 = System.currentTimeMillis() / 1000 - mTime1; LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++++---------mTimex1=" + mTimex1); if(mTimex1>=300){ new TaskMain(mFairy).UpState(581); Utils.sleep(60000); } }else { mTime1 = System.currentTimeMillis() / 1000; } } //防沉迷判断 private boolean resetGame() throws InterruptedException { AtFairy2.OpencvResult result; result = publicFunction.localFindPic(662, 629, 845, 711, "sleep.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------sleep=" + result); return true; } result = publicFunction.localFindPic(604,248,885,382, "err5.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++-------->err5=" + result); return true; } return false; } //登陆界面 private boolean Land() throws InterruptedException { AtFairy2.OpencvResult result; result = publicFunction.localFindPic(286, 744, 428, 976, "Land.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------Land=" + result); return true; } result = publicFunction.localFindPic(491, 614, 757, 691, "startUp1.png|startUp.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------startUp=" + result); return true; } result = publicFunction.localFindPic(189, 57, 442, 152, "notice.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------notice=" + result); return true; } result = publicFunction.localFindPic(207, 24, 520, 143, "agreement.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------agreement=" + result); return true; } result = publicFunction.localFindPic(528, 427, 661, 659, "login.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------login=" + result); return true; } result = publicFunction.localFindPic(1014, 587, 1147, 719, "login1.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------login=" + result); return true; } result = publicFunction.localFindPic(712, 462, 849, 666, "QQ.png" + "|" + "QQ1.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------QQ=" + result); return true; } result = publicFunction.localFindPic(257,376,448,479, "Land1.png"); if (result.sim >= 0.8) { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++++++++++--------------Land1=" + result); return true; } return false; } public void start() { LtLog.i(publicFunction.getLineInfo() + "+++++++++++-+++-----启动监控------CheckTask.restart-->mIsStoped=" + this.mIsStoped); this.mIsStoped = false; Utils.sleep(100); synchronized (lockCheck) { lockCheck.notify(); } } public void stop() { LtLog.i(publicFunction.getLineInfo() + "++++++++++++++----停止监控-------CheckTask.stop-->mIsStoped=" + this.mIsStoped); synchronized (lockCheck) { this.mIsStoped = true; lockCheck.notify(); } LtLog.i(publicFunction.getLineInfo() + "+++++++++++++++++++++++++CheckTask.stop-->mIsStoped=" + this.mIsStoped); } }
38.31982
135
0.492418
3859895fc21376b4f8b535058fee4fd317ae1410
639
public class H42 { public static void main (String[] args) { mainQ(Integer.parseInt(args[0]), Integer.parseInt(args[1])); } public static void mainQ(int flag, int u1){ assert(u1 > 0); int x = 1; int y = 1; int a = 0; if (flag != 0) a = 0; else a = 1; int i1 = 0; while (i1 < u1) { i1++; if (flag != 0) { a = x + y; x++; } else { a = x + y + 1; y++; } if (a % 2 == 1) y++; else x++; } // x==y if (flag != 0) a++; //%%%traces: int a, int y, int x //assert(a % 2 == 1); } }
15.585366
63
0.384977
5d4d4fc1eaac4f252a5a23751f34f5e5475b7362
3,461
package ast.node.conditional; import ast.exception.AstBaseException; import ast.exception.common.BadChildrenCountException; import ast.exception.semantic.TypeMismatchException; import ast.exception.semantic.UnknownSymbolException; import ast.node.BaseNode; import ast.node.constant.ConstantBooleanNode; import ast.node.operation.*; import org.antlr.runtime.tree.Tree; import symbolTable.SymbolTableProvider; import symbolTable.symbol.Symbol; import symbolTable.symbol.SymbolType; import utils.AstNodes; public class ConditionNode extends BaseNode { private BaseNode conditionNode; public ConditionNode(Tree child) throws AstBaseException { super(child); } /** * */ @Override protected void checkChildrenAmount() throws AstBaseException { int allowedChildrenAmount = 1; if (children.size() != allowedChildrenAmount) { throw new BadChildrenCountException(allowedChildrenAmount, children.size()); } } /** * */ @Override protected void exitNode() throws AstBaseException { } /** * */ @Override protected void extractChildren() throws AstBaseException { Tree condition = children.get(0); if (condition.toString().equalsIgnoreCase(AstNodes.CSTE_B)) { conditionNode = new ConstantBooleanNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.AND_NODE)) { conditionNode = new AndNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.OR_NODE)) { conditionNode = new OrNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.LEQ_NODE)) { conditionNode = new LeqNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.LT_NODE)) { conditionNode = new LtNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.GEQ_NODE)) { conditionNode = new GeqNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.GT_NODE)) { conditionNode = new GtNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.EQ_NODE)) { conditionNode = new EqNode(condition); } else if (condition.toString().equalsIgnoreCase(AstNodes.NEQ_NODE)) { conditionNode = new NeqNode(condition); } else { // provided node may be an IDF Symbol idf = SymbolTableProvider.getCurrent().getSymbol(condition.toString()); if (idf == null) { throw new UnknownSymbolException(condition.toString(), condition); } if (idf.getType() != SymbolType.BOOL) { throw new TypeMismatchException(SymbolType.BOOL.toString(), idf.getType().toString(), condition); } } } /** * */ @Override protected void extractIdfs() throws AstBaseException { } /** * @param prefix */ @Override public String generateCode(String prefix) throws AstBaseException { return conditionNode.generateCode(prefix); } /** * */ @Override protected void fillSymbolTable() throws AstBaseException { } /** * */ @Override protected void performSemanticControls() throws AstBaseException { } }
28.841667
113
0.639411
922f054b6448cc00a07530741afcf11066f79ad0
5,631
/* * 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 Controllers; import Controllers.exceptions.NonexistentEntityException; import entities.Etudiant; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import entities.Groupe; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author Oracle */ public class EtudiantJpaController implements Serializable { public EtudiantJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(Etudiant etudiant) { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Groupe groupe = etudiant.getGroupe(); if (groupe != null) { groupe = em.getReference(groupe.getClass(), groupe.getId()); etudiant.setGroupe(groupe); } em.persist(etudiant); if (groupe != null) { groupe.getEtudiantList().add(etudiant); groupe = em.merge(groupe); } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public void edit(Etudiant etudiant) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Etudiant persistentEtudiant = em.find(Etudiant.class, etudiant.getId()); Groupe groupeOld = persistentEtudiant.getGroupe(); Groupe groupeNew = etudiant.getGroupe(); if (groupeNew != null) { groupeNew = em.getReference(groupeNew.getClass(), groupeNew.getId()); etudiant.setGroupe(groupeNew); } etudiant = em.merge(etudiant); if (groupeOld != null && !groupeOld.equals(groupeNew)) { groupeOld.getEtudiantList().remove(etudiant); groupeOld = em.merge(groupeOld); } if (groupeNew != null && !groupeNew.equals(groupeOld)) { groupeNew.getEtudiantList().add(etudiant); groupeNew = em.merge(groupeNew); } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Integer id = etudiant.getId(); if (findEtudiant(id) == null) { throw new NonexistentEntityException("The etudiant with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Integer id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Etudiant etudiant; try { etudiant = em.getReference(Etudiant.class, id); etudiant.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The etudiant with id " + id + " no longer exists.", enfe); } Groupe groupe = etudiant.getGroupe(); if (groupe != null) { groupe.getEtudiantList().remove(etudiant); groupe = em.merge(groupe); } em.remove(etudiant); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Etudiant> findEtudiantEntities() { return findEtudiantEntities(true, -1, -1); } public List<Etudiant> findEtudiantEntities(int maxResults, int firstResult) { return findEtudiantEntities(false, maxResults, firstResult); } private List<Etudiant> findEtudiantEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Etudiant.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Etudiant findEtudiant(Integer id) { EntityManager em = getEntityManager(); try { return em.find(Etudiant.class, id); } finally { em.close(); } } public int getEtudiantCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Etudiant> rt = cq.from(Etudiant.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
33.123529
112
0.559936
baedcbff23037f2592d443aafa5795ef620f4dc4
3,755
package gov.cdc.usds.simplereport.logging; import gov.cdc.usds.simplereport.api.WebhookContextHolder; import gov.cdc.usds.simplereport.api.pxp.CurrentPatientContextHolder; import gov.cdc.usds.simplereport.db.model.Organization; import gov.cdc.usds.simplereport.db.model.PatientLink; import gov.cdc.usds.simplereport.service.AuditService; import gov.cdc.usds.simplereport.service.errors.RestAuditFailureException; import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; /** Wrapper around {@link AuditService} to catch exceptions and rethrow them */ @Service @Slf4j // NOT TRANSACTIONAL (must catch errors at transaction boundaries) @SuppressWarnings("checkstyle:IllegalCatch") public class RestAuditLogManager { private final AuditService _auditService; private final CurrentPatientContextHolder _contextHolder; private final WebhookContextHolder _webhookContextHolder; private static final int DEFAULT_SUCCESS = HttpStatus.OK.value(); public RestAuditLogManager( AuditService auditService, CurrentPatientContextHolder contextHolder, WebhookContextHolder webhookContextHolder) { this._auditService = auditService; this._contextHolder = contextHolder; this._webhookContextHolder = webhookContextHolder; } /** * To be called from a PostAuthorize annotation or otherwise at the end of request processing, but * before the response is actually handed back off to tomcat. Saves the audit log, or if it cannot * be saved throws an exception so that there is no response to the user about the action they * just attempted. * * @param request the {@link HttpServletRequest} that is being handled. * @param resultObject the object being returned by the controller method, presumably for Jackson * converting to a JSON response body. Not currently used, to the annoyance of Sonar. * @return true if the request should be allowed to complete, false otherwise (in this case, only * if we get to this but there is no patient link available, which indicates something wonky * happened.). */ public boolean logRestSuccess(HttpServletRequest request, Object resultObject) { PatientLink patientLink = _contextHolder.getPatientLink(); if (patientLink == null && !_contextHolder.isPatientSelfRegistrationRequest()) { log.error( "Somehow reached PXP success handler outside of registration & with no patient link"); return false; } try { String requestId = MDC.get(LoggingConstants.REQUEST_ID_MDC_KEY); Organization org = _contextHolder.getOrganization(); _auditService.logRestEvent(requestId, request, DEFAULT_SUCCESS, org, patientLink); } catch (Exception e) { throw new RestAuditFailureException(e); } return true; } public boolean logWebhookSuccess(HttpServletRequest request) { if (!_webhookContextHolder.isWebhook()) { log.error("Somehow reached success handler without webhook context being true"); return false; } try { String requestId = MDC.get(LoggingConstants.REQUEST_ID_MDC_KEY); _auditService.logWebhookRestEvent(requestId, request, DEFAULT_SUCCESS); } catch (Exception e) { throw new RestAuditFailureException(e); } return true; } public boolean logAnonymousRestSuccess(HttpServletRequest request, Object returnObject) { try { String requestId = MDC.get(LoggingConstants.REQUEST_ID_MDC_KEY); _auditService.logAnonymousRestEvent(requestId, request, DEFAULT_SUCCESS); } catch (Exception e) { throw new RestAuditFailureException(e); } return true; } }
41.263736
100
0.758455
4416215572f94a7b8908560b115126d9963a0385
1,060
package com.lsieun.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import sun.misc.BASE64Encoder; public class ImageTestUtil { /** <p>图片转化成base64字符串</p> * 处理流程:图片-->字节数组-->(Base64编码处理)字符串 * @param imgFile 图片路径(待处理的图片) 例如:String imgFile = "d://test.jpg"; * @return (Base64编码处理)字符串 */ public static String GetImageStr(String imgFile){ InputStream in = null; byte[] data = null; //读取图片字节数组 try{ in = new FileInputStream(imgFile); data = new byte[in.available()]; int count = in.read(data); System.out.println("read file bytes: " + count + "byte"); }catch (IOException e){ e.printStackTrace(); } finally{ IOUtils.closeQuietly(in); } //对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); if(data == null) return null; //返回Base64编码过的字符串 return encoder.encode(data); } }
27.894737
70
0.596226
c3686c92ee0825203f5264082fc896738ffe738c
2,950
package org.dstadler.jgit.api; /* Copyright 2013, 2014 Dominik Stadler Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.io.IOException; import org.dstadler.jgit.helper.CookbookHelper; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; /** * Snippet which shows how to check if commits are merged into a * given branch. * * See also http://stackoverflow.com/questions/26644919/how-to-determine-with-jgit-which-branches-have-been-merged-to-master */ public class CheckMergeStatusOfCommit { public static void main(String[] args) throws IOException { Repository repository = CookbookHelper.openJGitCookbookRepository(); RevWalk revWalk = new RevWalk( repository ); RevCommit masterHead = revWalk.parseCommit( repository.resolve( "refs/heads/master" )); // first a commit that was merged ObjectId id = repository.resolve("05d18a76875716fbdbd2c200091b40caa06c713d"); System.out.println("Had id: " + id); RevCommit otherHead = revWalk.parseCommit( id ); if( revWalk.isMergedInto( otherHead, masterHead ) ) { System.out.println("Commit " + otherHead + " is merged into master"); } else { System.out.println("Commit " + otherHead + " is NOT merged into master"); } // then a commit on a test-branch which is not merged id = repository.resolve("ae70dd60a7423eb07893d833600f096617f450d2"); System.out.println("Had id: " + id); otherHead = revWalk.parseCommit( id ); if( revWalk.isMergedInto( otherHead, masterHead ) ) { System.out.println("Commit " + otherHead + " is merged into master"); } else { System.out.println("Commit " + otherHead + " is NOT merged into master"); } // and finally master-HEAD itself id = repository.resolve("HEAD"); System.out.println("Had id: " + id); otherHead = revWalk.parseCommit( id ); if( revWalk.isMergedInto( otherHead, masterHead ) ) { System.out.println("Commit " + otherHead + " is merged into master"); } else { System.out.println("Commit " + otherHead + " is NOT merged into master"); } revWalk.dispose(); repository.close(); } }
36.419753
124
0.659661
b9f9b5d905c313e4de51bd289de9d67246d243cd
2,448
/* Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.apps.easyconnect.easyrp.client.basic.session; import com.google.apps.easyconnect.easyrp.client.basic.data.OauthTokenResponse; import org.json.JSONObject; /** * Generates and verifies the cookie values. Since the cookie is saved at client side, there would * be some way the check the value has not been changed by user. * @author guibinkong@google.com (Guibin Kong) */ public interface TokenGenerator { /** * Creates the cookie value for a logged-in email * @param email the logged-in email address * @return the cookie value created */ String generateSessionToken(String email); /** * Verifies the cookie value is valid. If valid, return the logged-in email address. * @param token the cookie value to be verified * @return the email address if valid, null otherwise */ String verifySessionToken(String token); /** * Creates the cookie value to save the IDP assertion. * @param data the assertion from IDP. * @return the cookie value created */ String generateIdpAssertionToken(JSONObject data); /** * Verifies the cookie value is valid. If valid, return the IDP assertion. * @param token the cookie value to be verified * @return the IDP assertion if valid, null otherwise */ JSONObject verifyIdpAssertionToken(String token); /** * Creates the cookie value to save the OAuth token. * @param data the OAuth token * @return the cookie value created */ String generateOauthToken(OauthTokenResponse data); /** * Verifies the cookie value is valid. If valid, return the OAuth token. * @param data the cookie value to be verified. * @return the OAuth token if valid, null otherwise */ OauthTokenResponse verifyOauthToken(String data); }
34.478873
99
0.707516
b2e74cca71cd969a84ec5bdb494dcd3bc7a2bab4
103
package zynaps.engine; public interface MaterialModifier { void changeColor(Material material); }
17.166667
40
0.786408
57312d924dbb626f5b26c9d7319215f2be4f92e4
8,305
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.android; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.graphics.Bitmap; import android.media.MediaMetadataRetriever; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.ContactsContract; import android.webkit.MimeTypeMap; import java.io.File; import java.io.IOException; import java.util.Random; import im.actor.android.images.ImageHelper; import im.actor.model.BaseMessenger; import im.actor.model.Configuration; import im.actor.model.MessengerEnvironment; import im.actor.model.entity.Peer; import im.actor.model.entity.content.FastThumb; import im.actor.model.network.NetworkState; public class AndroidBaseMessenger extends BaseMessenger { private Context context; private final Random random = new Random(); public AndroidBaseMessenger(Context context, Configuration configuration) { super(MessengerEnvironment.ANDROID, configuration); this.context = context; // Catch all phone book changes context.getContentResolver() .registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new ContentObserver(null) { @Override public void onChange(boolean selfChange) { onPhoneBookChanged(); } }); // Catch network change context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); NetworkState state; if (isConnected) { switch (activeNetwork.getType()) { case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_ETHERNET: state = NetworkState.WI_FI; break; case ConnectivityManager.TYPE_MOBILE: state = NetworkState.MOBILE; break; default: state = NetworkState.UNKNOWN; } } else { state = NetworkState.NO_CONNECTION; } onNetworkChanged(state); } }, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION)); } public Context getContext() { return context; } @Override public void changeGroupAvatar(int gid, String descriptor) { try { Bitmap bmp = ImageHelper.loadOptimizedHQ(descriptor); if (bmp == null) { return; } String resultFileName = getExternalTempFile("image", "jpg"); if (resultFileName == null) { return; } ImageHelper.save(bmp, resultFileName); super.changeGroupAvatar(gid, resultFileName); } catch (IOException e) { e.printStackTrace(); } } @Override public void changeMyAvatar(String descriptor) { try { Bitmap bmp = ImageHelper.loadOptimizedHQ(descriptor); if (bmp == null) { return; } String resultFileName = getExternalTempFile("image", "jpg"); if (resultFileName == null) { return; } ImageHelper.save(bmp, resultFileName); super.changeMyAvatar(resultFileName); } catch (IOException e) { e.printStackTrace(); } } public void sendDocument(Peer peer, String fullFilePath) { sendDocument(peer, fullFilePath, new File(fullFilePath).getName()); } public void sendDocument(Peer peer, String fullFilePath, String fileName) { int dot = fileName.indexOf('.'); String mimeType = null; if (dot >= 0) { String ext = fileName.substring(dot + 1); mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); } if (mimeType == null) { mimeType = "application/octet-stream"; } Bitmap fastThumb = ImageHelper.loadOptimizedHQ(fullFilePath); if (fastThumb != null) { fastThumb = ImageHelper.scaleFit(fastThumb, 90, 90); byte[] fastThumbData = ImageHelper.save(fastThumb); sendDocument(peer, fileName, mimeType, new FastThumb(fastThumb.getWidth(), fastThumb.getHeight(), fastThumbData), fullFilePath); } else { sendDocument(peer, fileName, mimeType, fullFilePath); } } public void sendPhoto(Peer peer, String fullFilePath) { sendPhoto(peer, fullFilePath, new File(fullFilePath).getName()); } public void sendPhoto(Peer peer, String fullFilePath, String fileName) { try { Bitmap bmp = ImageHelper.loadOptimizedHQ(fullFilePath); if (bmp == null) { return; } Bitmap fastThumb = ImageHelper.scaleFit(bmp, 90, 90); String resultFileName = getExternalTempFile("image", "jpg"); if (resultFileName == null) { return; } ImageHelper.save(bmp, resultFileName); byte[] fastThumbData = ImageHelper.save(fastThumb); sendPhoto(peer, fileName, bmp.getWidth(), bmp.getHeight(), new FastThumb(fastThumb.getWidth(), fastThumb.getHeight(), fastThumbData), resultFileName); } catch (Throwable t) { t.printStackTrace(); } } public void sendVideo(Peer peer, String fullFilePath) { sendVideo(peer, fullFilePath, new File(fullFilePath).getName()); } public void sendVideo(Peer peer, String fullFilePath, String fileName) { try { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(fullFilePath); int duration = (int) (Long.parseLong(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000L); Bitmap img = retriever.getFrameAtTime(0); int width = img.getWidth(); int height = img.getHeight(); Bitmap smallThumb = ImageHelper.scaleFit(img, 90, 90); byte[] smallThumbData = ImageHelper.save(smallThumb); FastThumb thumb = new FastThumb(smallThumb.getWidth(), smallThumb.getHeight(), smallThumbData); sendVideo(peer, fileName, width, height, duration, thumb, fullFilePath); } catch (Throwable e) { e.printStackTrace(); } } private String getExternalTempFile(String prefix, String postfix) { File externalFile = context.getExternalFilesDir(null); if (externalFile == null) { return null; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/tmp/"); dest.mkdirs(); File outputFile = new File(dest, prefix + "_" + random.nextLong() + "." + postfix); return outputFile.getAbsolutePath(); } private String getInternalTempFile(String prefix, String postfix) { File externalFile = context.getFilesDir(); if (externalFile == null) { return null; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/tmp/"); dest.mkdirs(); File outputFile = new File(dest, prefix + "_" + random.nextLong() + "." + postfix); return outputFile.getAbsolutePath(); } }
36.108696
131
0.594341
b44cb4b3f56fc5fd7d4aac285144b02c672bb7b8
1,575
package name.mjw.jquante.math.qm.integral; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import name.mjw.jquante.math.qm.basis.ContractedGaussian; import name.mjw.jquante.test.Fixtures; class HuzinagaTwoElectronTermTest { private final double delta = 0.000001; HuzinagaTwoElectronTerm e2 = new HuzinagaTwoElectronTerm(); static ContractedGaussian cgtoS0 = Fixtures.getCgtoS0(); static ContractedGaussian cgtoS1 = Fixtures.getCgtoS1(); static ContractedGaussian cgtoP0 = Fixtures.getCgtoP0(); static ContractedGaussian cgtoD0 = Fixtures.getCgtoD0(); static ContractedGaussian cgtoF0 = Fixtures.getCgtoF0(); @Test void ss00() { assertEquals(1.1283791633342477, e2.coulomb(cgtoS0, cgtoS0, cgtoS0, cgtoS0), delta); } @Test void ss01() { assertEquals(0.8427007900292194, e2.coulomb(cgtoS0, cgtoS0, cgtoS1, cgtoS1), delta); } @Test void sp00() { assertEquals(0.9403159699467084, e2.coulomb(cgtoS0, cgtoS0, cgtoP0, cgtoP0), delta); } @Test void sd00() { assertEquals(0.8086717345109515, e2.coulomb(cgtoS0, cgtoS0, cgtoD0, cgtoD0), delta); } @Test void sf00() { assertEquals(0.7132968291998493, e2.coulomb(cgtoS0, cgtoS0, cgtoF0, cgtoF0), delta); } @Test void pd00() { assertEquals(0.8583741496984647, e2.coulomb(cgtoP0, cgtoP0, cgtoD0, cgtoD0), delta); } @Test void dd00() { assertEquals(0.854418854766963, e2.coulomb(cgtoD0, cgtoD0, cgtoD0, cgtoD0), delta); } @Test void ff00() { assertEquals(0.8186960564969021, e2.coulomb(cgtoF0, cgtoF0, cgtoF0, cgtoF0), delta); } }
25.403226
86
0.746032
45ec0265f0271f9109368f8be44fc402a649249c
359
package org.bal.config; import org.bal.producer.Producer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; @Configuration @EnableJms public class ProducerConfiguration { @Bean public Producer sender() { return new Producer(); } }
22.4375
60
0.799443
84b8f608a1d2b7f6daa32c09d7df432df5c4e2f1
1,453
package com.nbu.annotationplus.controller; import com.nbu.annotationplus.dto.DtoCategory; import com.nbu.annotationplus.service.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/api") public class CategoryController { @Autowired private CategoryService categoryService; @GetMapping("/category") public List<DtoCategory> getAllCategories() { return categoryService.getAllCategories(); } @PostMapping("/category") public ResponseEntity<DtoCategory> createCategory(@Valid @RequestBody DtoCategory dtoCategory) { return categoryService.createCategory(dtoCategory); } @DeleteMapping("/category/{id}") public ResponseEntity<?> deleteCategoryById(@PathVariable(value = "id") Long id) { return categoryService.deleteCategoryById(id); } @PutMapping("/category/{id}") public DtoCategory updateCategoryById(@PathVariable(value = "id") Long id, @Valid @RequestBody DtoCategory dtoCategory) { return categoryService.updateCategoryById(id,dtoCategory); } @GetMapping("/category/{id}") public DtoCategory getCategoryById(@PathVariable(value = "id") Long id) { return categoryService.getCategoryById(id); } }
32.288889
100
0.732966
5974047bad814503d6bb898e7572fc5d373df4c4
780
package cn.programingmonkey.Exception.type; /** * Created by cai on 2017/3/30. */ public enum RESET_PWD_EXCEPTION_TYPE { RESET_PWD_EXCEPTION_MOBILE_UNRIGHTED(-901,"手机号未注册"), RESET_PWD_EXCEPTION_INVALID_VEIFYCODE(-902,"无效的验证码"), RESET_PWD_EXCEPTION_VERIFYCODE_EXPIRED(-903,"验证码已经失效,请重新获取"), RESET_PWD_EXCEPTION_PASSWORD_LEN_NOT_ENOUGH(-904,"密码长度不足"), RESET_PWD_EXCEPTION_INVALID_PASSWORD(-905,"无效的密码"), RESET_PWD_EXCEPTION_VERIFYCODE_SEND_TOO_OFTEN(-906,"验证码请求过于频繁,请一分钟后再试"); ; private int code; private String msg; RESET_PWD_EXCEPTION_TYPE(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } }
24.375
76
0.694872
24cc6f55f665c6a3fd1630ad8dc6d876d5b1298e
1,199
package org.ultramine.server.chunk; public enum ChunkBindState { /** * Чанк ничем не занят и может быть выгружен в любой момент. Стандартное * значение при асинхронной загрузке чанка. */ NONE, /** * Чанк занят игроком/игроками. Как только все игроки выйдут из радиуса * прогрузки, значение сменится на <code>NONE</code>. */ PLAYER, /** * Чанк был загружен синхронно, в обход менеджера загрузки чанков. По логике * ванильного майна это является утечкой памяти - чанк не будет выгружен из * памяти до тех пор, пока не будет помечен к отгрузке вручную (например, в * него зайдет и выйдет игрок). Но у нас чанк будет выгружен через некоторое * время. */ LEAK, /** * Чанк обнаружен в списке PersistentChunks, созданного форжей для всяких * чанклоадеров. Не будет выгружен до тех пор, пока не исчезнет из этого * списка. */ FORGE, /** * Чанку запрещено выгружаться или изменять состояние бинда. Чанк не будет * выгружен никогда. */ ETERNAL; public boolean canUnload() { return this == NONE; } public boolean canChangeState() { return this != ETERNAL && this != FORGE; } public boolean isLeak() { return this == LEAK || this == FORGE; } }
23.98
77
0.700584
caa5f50ef9a9e40ace5cc25d9bf0ac9fc413a243
116
package com.bbcron.myPackage; import static org.junit.jupiter.api.Assertions.*; class BBCronMyProjectMainTest { }
16.571429
49
0.801724
5703e14987128b2180d409bd842550f258583857
1,090
package com.dwarfeng.bitalarm.impl.service; import com.dwarfeng.bitalarm.stack.handler.AlarmHandler; import com.dwarfeng.bitalarm.stack.service.AlarmService; import com.dwarfeng.subgrade.sdk.exception.ServiceExceptionHelper; import com.dwarfeng.subgrade.stack.exception.ServiceException; import com.dwarfeng.subgrade.stack.exception.ServiceExceptionMapper; import com.dwarfeng.subgrade.stack.log.LogLevel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; @Service public class AlarmServiceImpl implements AlarmService { @Autowired private AlarmHandler alarmHandler; @Autowired private ServiceExceptionMapper sem; @Override public void processAlarm(long pointId, byte[] data, Date happenedDate) throws ServiceException { try { alarmHandler.processAlarm(pointId, data, happenedDate); } catch (Exception e) { throw ServiceExceptionHelper.logAndThrow("处理报警信息时发生异常", LogLevel.WARN, sem, e ); } } }
33.030303
100
0.751376
2cb3289380f7652cc1d3a39d5d5c5447092ac27a
2,238
/** * Copyright (C) 2012 JBoss 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 org.jboss.dashboard.ui.controller.requestChain; import org.jboss.dashboard.annotation.config.Config; import org.jboss.dashboard.ui.HTTPSettings; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @ApplicationScoped public class ResponseHeadersProcessor extends AbstractChainProcessor { @Inject @Config("false") private boolean useRefreshHeader; @Inject @Config("text/html") private String responseContentType; public boolean processRequest() throws Exception { HttpServletRequest request = getHttpRequest(); HttpServletResponse response = getHttpResponse(); if (responseContentType != null && !"".equals(responseContentType)) { response.setContentType(responseContentType); response.setHeader("Content-Type", responseContentType + "; charset=" + HTTPSettings.lookup().getEncoding()); } SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.US); response.setHeader("Expires", "Mon, 06 Jan 2003 21:29:02 GMT"); response.setHeader("Last-Modified", sdf.format(new Date()) + " GMT"); response.setHeader("Cache-Control", "no-cache, must-revalidate"); response.setHeader("Pragma", "no-cache"); if (useRefreshHeader) { response.setHeader("Refresh", java.lang.String.valueOf(request.getSession().getMaxInactiveInterval() + 61)); } return true; } }
39.964286
121
0.720286
0f916f779df321a7dfae4113a397e8be48fb2117
786
/* Faca a multiplicacao entre dois numeros usando somente soma. (Utilizar a estrutura de repeticao for) */ import java.util.Scanner; public class MultiplicaSomando { public static void main(String[] args) { Scanner leitorDoTeclado = new Scanner(System.in); int numeroUm, numeroDois, resultado=0; System.out.println("Programa para multiplicar dois numeros utilizando soma!"); System.out.print("Informe o primeiro numero: "); numeroUm = leitorDoTeclado.nextInt(); System.out.print("Informe o segundo numero: "); numeroDois = leitorDoTeclado.nextInt(); for(int i=1;i<=numeroUm;i++) { resultado=resultado+numeroDois; } System.out.println(numeroUm+" x "+numeroDois+" = "+resultado); } }
26.2
86
0.661578
14c3204ca18388366182839a2a0725905e9db45d
227
package net.geofflittle.congress4j.members.membercosponsoredbills; public enum CosponsorshipStatus { COSPONSORED, WITHDRAWN; @Override public String toString() { return name().toLowerCase(); } }
16.214286
66
0.696035
13bd87e2e8e879e411d6fcabe370211ab21d8ad5
465
package avonbo.snippets.java.ruleengine.eventbus.service; import avonbo.snippets.java.ruleengine.eventbus.domain.EventImpl; public class SimpleProcessingServiceImpl implements ProcessingService { Runnable command; public SimpleProcessingServiceImpl(Runnable command) { } @Override public void execute() { this.command.run(); } @Override public void setArguments(EventImpl messageEvent) { // not used } }
18.6
71
0.713978
3deae30391254cc4f7fc851c10dfab0344c9862a
2,266
package eu.w4.contrib.bpmnplus.module.filewatcher; public class WatcherConfig { private String _definitionsIdentifier; private String _definitionsVersion; private String _collaborationIdentifier; private String _processIdentifier; private String _signalIdentifier; private String _dataEntry; private String _dataType; private boolean _recursive; private boolean _pickingDirectories; private boolean _pickingFiles; public String getDefinitionsIdentifier() { return _definitionsIdentifier; } public void setDefinitionsIdentifier(String definitionsIdentifier) { _definitionsIdentifier = definitionsIdentifier; } public String getDefinitionsVersion() { return _definitionsVersion; } public void setDefinitionsVersion(String definitionsVersion) { _definitionsVersion = definitionsVersion; } public String getCollaborationIdentifier() { return _collaborationIdentifier; } public void setCollaborationIdentifier(String collaborationIdentifier) { _collaborationIdentifier = collaborationIdentifier; } public String getProcessIdentifier() { return _processIdentifier; } public void setProcessIdentifier(String processIdentifier) { _processIdentifier = processIdentifier; } public String getSignalIdentifier() { return _signalIdentifier; } public void setSignalIdentifier(String signalIdentifier) { _signalIdentifier = signalIdentifier; } public String getDataEntry() { return _dataEntry; } public void setDataEntry(String dataEntry) { _dataEntry = dataEntry; } public String getDataType() { return _dataType; } public void setDataType(String dataType) { _dataType = dataType; } public boolean isRecursive() { return _recursive; } public void setRecursive(boolean recursive) { _recursive = recursive; } public boolean isPickingDirectories() { return _pickingDirectories; } public void setPickingDirectories(boolean pickingDirectories) { _pickingDirectories = pickingDirectories; } public boolean isPickingFiles() { return _pickingFiles; } public void setPickingFiles(boolean pickingFiles) { _pickingFiles = pickingFiles; } }
17.984127
72
0.745808