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
a8ee988b7bdec28dc7bf0d509211503bcf85d6ea
1,072
public Map<String, String> dimNames = new HashMap<String, String>(); private void loadDiminutiveNames() { BufferedReader input = null; try { input = new BufferedReader(new FileReader(dimNamesFile)); String line = null; while ((line = input.readLine()) != null) { //System.out.println("line = " + line); StringTokenizer st = new StringTokenizer(line, ","); String key = st.nextToken(); List<String> values = new ArrayList<String>(); while (st.hasMoreElements()) { values.add(st.nextToken()); } dimNames.put(key, values); } } catch (IOException ex) { Logger.getLogger(ThisClass.class.getName()).log(Level.SEVERE, null, ex); } finally { try { input.close(); } catch (IOException ex) { Logger.getLogger(ThisClass.class.getName()).log(Level.SEVERE, null, ex); } } }
35.733333
88
0.504664
e9f324a21dee6d9e5c5efcd177d9505e08b28744
623
/* * Copyright (c) 2020. Yuanchen */ package book.precise_java; /** * @author shiyuanchen * @project LeetCode * @since 2020/11/24 */ public class Example39 { static class TLC { static int sf; int nf; void nm() { class NLC { int m(int p) { return sf + nf + p; } } } static class SMC { static int ssf = sf + TLC.sf; int snf = sf + TLC.sf; } class NMC { int nnf1 = sf + nf; int nnf2 = TLC.sf + TLC.this.nf; } } }
14.833333
44
0.41573
5b3971a3f4cc311cd4a52fc268fc44213f0f7715
4,468
package interview.twilio; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.OptionalDouble; import java.util.stream.Collectors; class Result { public static final String JSON_URL = "https://jsonmock.hackerrank.com/api/transactions/search?userId="; public static List<Integer> getUserTransaction(int uid, String txnType, String monthYear) { List<Integer> result = new ArrayList<>(); if (txnType != null && monthYear != null) { List<User> data = getJSONFromUrl(uid); filterData(result, txnType, monthYear, data); } if (result.isEmpty()) { result.add(-1); } return result; } private static void filterData(List<Integer> result, String txnType, String monthYear, List<User> userData) { List<User> filteredUserData = userData.stream() .filter(user -> filterDate(user.timestamp, monthYear)) .filter(user -> user.txnType.equalsIgnoreCase(txnType)).collect(Collectors.toList()); getAverageForMonthYear(txnType, filteredUserData, monthYear).ifPresent(averageAmount -> { filteredUserData .stream() .filter(user -> compareAmount(averageAmount, user)) .forEach(user -> result.add(user.id)); }); } private static boolean compareAmount(double averageAmount, User user) { double amount = convertDouble(user.amount); return Double.compare(amount, averageAmount) >= 0; } private static OptionalDouble getAverageForMonthYear(String txnType, List<User> userData, String monthYear) { return userData.stream() .filter(user -> user.txnType.equalsIgnoreCase(txnType)) .filter(user -> filterDate(user.timestamp, monthYear)) .mapToDouble(v -> convertDouble(v.amount)) .average(); } private static double convertDouble(String amount) { amount = amount.replaceAll("\\$", ""); amount = amount.replaceAll(",", ""); return Double.parseDouble(amount); } private static boolean filterDate(String timestamp, String monthYear) { try { DateFormat dateFormat = new SimpleDateFormat("MM-yyyy"); String convertedDate = dateFormat.format(new Date(Long.parseLong(timestamp))); return convertedDate.contains(monthYear); } catch (Exception e) { e.printStackTrace(); } return false; } public static List<User> getJSONFromUrl(int uid) { List<User> users = new ArrayList<>(); ApiResponse apiResponse; URL url = null; int totalPages = 0; int currentPage = 1; do { try { url = new URL(JSON_URL + uid + "&page=" + currentPage); } catch (MalformedURLException e) { e.printStackTrace(); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { apiResponse = new Gson().fromJson(reader, ApiResponse.class); totalPages = apiResponse.total_pages; currentPage++; users.addAll(apiResponse.data); } catch (Exception e) { e.printStackTrace(); } } while (currentPage < totalPages); return users; } } class ApiResponse { public int page; public int per_page; public int total; public int total_pages; public List<User> data; } class User { public int id; public int userId; public String userName; public String timestamp; public String txnType; public String amount; public Location LocationObject; public String ip; } class Location { public int id; public String address; public String city; public int zipCode; } public class RestApiParser { public static void main(String[] args) throws IOException { List<Integer> result = Result.getUserTransaction(4, "debit", "02-2019"); System.out.println(result.stream().map(String::valueOf).collect(Collectors.joining(","))); } }
31.244755
113
0.625783
9dfa6acef42c9093a0c376249ffc855f0a34b956
3,522
/* * The MIT License (MIT) * * Copyright (c) 2016 Goran Sarenkapa (JordanGS), and a number of other of contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.jenkinsci.plugins.zap; import java.text.MessageFormat; import hudson.model.BuildListener; /** * A support class to prevent used to create more user friendly console output. * * @author Goran Sarenkapa * @author Mostafa AbdelMoez * @author Tanguy de Lignières * @author Abdellah Azougarh * @author Thilina Madhusanka * @author Johann Ollivier-Lapeyre * @author Ludovic Roucoux * */ public class Utils { /* Global Constant: Used by Logger */ public static final String ZAP = "ZAP Jenkins Plugin"; /** * Write a empty line to the logger. * * @param listener * of type BuildListener: the display log listener during the Jenkins job execution. */ public static void lineBreak(BuildListener listener) { String message = ""; MessageFormat mf = new MessageFormat(message); listener.getLogger().println(mf.format(null)); } /** * Write a user specified message with injected values and specified indentation to the logger. * * @param listener * of type BuildListener: the display log listener during the Jenkins job execution. * @param indent * of type int: the indentation of the log message to be displayed. * @param message * of type String: the message to be displayed in the log. * @param args * of type String...: the values to be injected into the message */ public static void loggerMessage(BuildListener listener, int indent, String message, String... args) { MessageFormat mf = new MessageFormat(indent(message, indent)); listener.getLogger().println(mf.format(args)); } /** * Method which adds a specified amount of tabs to the message string. * * @param message * of type String: the message which will have tabs placed in front of it. * @param indent * of type int: the number of tabs to be placed in front of the message. * @return of type String: the original message with appended tabs to the front of it. */ public static String indent(String message, int indent) { String temp = ""; for (int i = 0; i < indent; i++) temp = temp + "\t"; return temp + message; } }
37.870968
106
0.678592
290c859b502a66fcbc2ff023dce9be9801f9d8df
8,864
package gocar.jeno.com.hencoder.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.view.View; import gocar.jeno.com.hencoder.R; /** * author : 宋佳 * time : 2017/07/14 * desc : * version: 1.0.0 */ public class MyView2 extends View { public MyView2(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public MyView2(Context context, AttributeSet attrs) { super(context, attrs); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //画 点 // drawPoint(canvas); //画多个 点儿 // drawPoints(canvas); // 画 椭圆 // drawOval(canvas); //画 线 // drawLine(canvas); // 画线 (多个坐标的) // drawLines(canvas); //画 椭圆 // drawRoundRect(canvas); //画 扇形 // drawArc(canvas); //画一些复杂的图形 一个小demo // drawPath(canvas); //用 path 简单的画一个圆 // drawPath1(canvas); //用 path 画线 主要是 lineTo(); rLine(); // drawPath2(canvas); // 用 path 画 贝塞尔曲线 // drawpath3(canvas); // 用 path 实现 moveTo(); // drawPaht4(canvas); // 实现 arcTo 的效果 意思是进行 画弧 // drawPath5(canvas); //close()的使用 意思是关闭从结束点 到起始点 // drawPath6(canvas); //以上是 path 的第一类的用法 只要是描述 路径的 //下面是 第二类的方法 辅助的设置或计算 //设置 bitmap drawBitmap(canvas); } private void drawBitmap(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setAntiAlias(true); paint.setStrokeWidth(10); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); canvas.drawBitmap(bitmap, 100, 100, paint); } private void drawPath6(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); Path path = new Path(); path.moveTo(100, 100); path.lineTo(200, 100); path.lineTo(150, 150); // path.close();//从当前位置 闭合这个图形 其实就是 path.lineTo(100,100); canvas.drawPath(path, paint); } /** * @param canvas arcTo addArc */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void drawPath5(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); /** * 这个方法和 Canvas.drawArc() 比起来,少了一个参数 useCenter,而多了一个参数 forceMoveTo 。 少了 useCenter , 是因为 arcTo() 只用来画弧形而不画扇形,所以不再需要 useCenter 参数; 而多出来的这个 forceMoveTo 参数的意思是, 绘制是要「抬一下笔移动过去」, 还是「直接拖着笔过去」,区别在于是否留下移动的痕迹。 其实 addArc 意思是 arcTo(xx, xx, xx, xx, xx, xx, true); 的简化版 将forceMoveTo 写死为 true 就是 跳过去然后画 */ Path path = new Path(); path.lineTo(100, 100); path.arcTo(100, 100, 300, 300, -90, 90, true); // 强制移动到弧形起点(无痕迹) canvas.drawPath(path, paint); } /** * 用 path 拼接的时候 moveTo 这个参数 * * @param canvas */ private void drawPaht4(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); Path path = new Path(); path.lineTo(100, 100); path.moveTo(200, 100); //此为移动到某个点上去 用 moveTo可以移动起始点 =此过程不会绘制图形,不过会移动点 path.lineTo(200, 0); // lineTo 都是想对于上个点来说的 canvas.drawPath(path, paint); } /** * 画线 用拜贝塞尔 * * @param canvas */ private void drawpath3(Canvas canvas) { } /** * 画线 一天线 * * @param canvas */ private void drawPath2(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); Path path = new Path(); path.lineTo(100, 100); path.rLineTo(100, 0); //r 是相对路径 意思是从上次的(100,100)为起点,相对来说画一条向右 100 的直线 path.quadTo(100, 100, 500, 500); canvas.drawPath(path, paint); } private void drawPath1(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); Path path = new Path(); path.addCircle(300, 300, 200, Path.Direction.CW); canvas.drawPath(path, paint); } /** * 这个是画复杂的图形 * Path 可以描述直线、二次曲线、三次曲线、圆、椭圆、弧形、矩形、圆角矩形。把这些图形结合起来,就可以描述出很多复杂的图形。 * * @param canvas */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void drawPath(Canvas canvas) { Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); paint.setColor(Color.RED); // 使用 path 对图形进行描述(这段描述代码不必看懂 Path path = new Path(); // 初始化 Path 对象 path.addArc(200, 200, 400, 400, -225, 225); path.arcTo(400, 200, 600, 400, -180, 225, false); path.lineTo(400, 542); canvas.drawPath(path, paint); // 绘制出 path 描述的图形(心形),大功告成 } /** * 画扇形 * * @param canvas */ private void drawArc(Canvas canvas) { Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.RED); paint.setAntiAlias(true); float x = (getWidth() - getHeight() / 2) / 2; float y = getHeight() / 4; RectF oval = new RectF(x, y, getWidth() - x, getHeight() - y); canvas.drawRect(oval, paint); Paint paint_over = new Paint(); paint_over.setStyle(Paint.Style.FILL); paint_over.setColor(Color.BLUE); canvas.drawArc(oval, -90, 90, true, paint_over);//其中的参数 : RectF oval 一个矩形 , float startAngle 开始的偏移量 正数代表顺时针 负数代表逆时针, float sweepAngle 画圈的大下, boolean useCenter 是否连接到圆心,@NonNull Paint paint } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void drawRoundRect(Canvas canvas) { Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.BLACK); paint.setAntiAlias(true); canvas.drawRoundRect(100, 100, 500, 300, 150, 50, paint); //参数的意思是: left top right bottom 的坐标 rx 是圆角的横向的左标 ry是圆角的纵向坐标 } /** * 画线 两个坐标就进行连接 * * @param canvas */ private void drawLines(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.BLACK); float[] points = {20, 20, 120, 20, 70, 20, 70, 120, 20, 120, 120, 120, 150, 20, 250, 20, 150, 20, 150, 120, 250, 20, 250, 120, 150, 120, 250, 120}; canvas.drawLines(points, paint); } /** * 画线 主要是两个点儿之间的线 * * @param canvas */ private void drawLine(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.parseColor("#00FA9A")); paint.setStrokeWidth(40); paint.setStyle(Paint.Style.FILL); canvas.drawLine(200, 200, 400, 400, paint); } /** * 画椭圆 * * @param canvas */ private void drawOval(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.parseColor("#FF7F24")); paint.setStyle(Paint.Style.FILL); //设置描边的画法 // canvas.drawOval(50, 50, 300, 200, paint); RectF rectF = new RectF(); rectF.set(50, 50, 300, 200); canvas.drawOval(rectF, paint); } /** * 画多个 点儿 再进行点儿的连接 * * @param canvas */ private void drawPoints(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.parseColor("#FF7F24")); paint.setStrokeWidth(20); paint.setStrokeCap(Paint.Cap.ROUND); float[] points = {0, 0, 50, 50, 50, 100, 100, 50, 100, 100, 150, 50, 150, 100}; // 绘制四个点:(50, 50) (50, 100) (100, 50) (100, 100) canvas.drawPoints(points, 2 /* 跳过两个数,即前两个 0 */, 8 /* 一共绘制 8 个数(4 个点)*/, paint); } /** * 画 点儿 * * @param canvas */ private void drawPoint(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.parseColor("#FF7F24")); paint.setStrokeWidth(200);//设置 点 的大小 //paint.setStrokeCap(Paint.Cap.ROUND); //圆形的 点 //圆头 //paint.setStrokeCap(Paint.Cap.BUTT); //平头 paint.setStrokeCap(Paint.Cap.SQUARE); //方头 canvas.drawPoint(250, 250, paint); } }
26.147493
198
0.57852
9959d2f7261c189ef25ae89a7cdfda32d1d05913
39,694
package org.thegalactic.rule; /* * ImplicationalSystem.java * * Copyright: 2010-2015 Karell Bertet, France * Copyright: 2015-2016 The Galactic Organization, France * * License: http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html CeCILL-B license * * This file is part of java-lattices. * You can redistribute it and/or modify it under the terms of the CeCILL-B license. */ import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import org.thegalactic.dgraph.ConcreteDGraph; import org.thegalactic.dgraph.Edge; import org.thegalactic.dgraph.Node; import org.thegalactic.io.Filer; import org.thegalactic.lattice.ClosureSystem; import org.thegalactic.lattice.io.ImplicationalSystemIOFactory; import org.thegalactic.util.ComparableSet; /** * This class gives a representation for an implicational system * (ImplicationalSystem), a set of rules. * * An ImplicationalSystem is composed of a TreeSet of comparable elements, and a * TreeSet of rules defined by class {@link Rule}. * * This class provides methods implementing classical transformation of an * implicational system : make proper, make minimum, make right maximal, make * left minimal, make unary, make canonical basis, make canonical direct basis * and reduction. * * An implicational system owns properties of a closure system, and thus extends * the abstract class {@link ClosureSystem} and implements methods * {@link #getSet} and {@link #closure}. * * Therefore, the closed set lattice of an ImplicationalSystem can be generated * by invoking method {@link #closedSetLattice} of a closure system. * * An implicational system can be instancied from and save to a text file in the * following format: - a list of elements separated by a space in the first line * ; - then, each rule on a line, written like [premise] -> [conclusion] where * elements are separated by a space. * * ~~~ * a b c d e * a b -> c d * c d -> e * ~~~ * * ![ImplicationalSystem](ImplicationalSystem.png) * * @uml ImplicationalSystem.png * !include resources/org/thegalactic/lattice/ImplicationalSystem.iuml * !include resources/org/thegalactic/lattice/ClosureSystem.iuml * * hide members * show ImplicationalSystem members * class ImplicationalSystem #LightCyan * title ImplicationalSystem UML graph */ public class ImplicationalSystem extends ClosureSystem { /* * --------------- FIELDS ----------------- */ /** * Generates a random ImplicationalSystem with a specified number of nodes * and rules. * * @param nbS the number of nodes of the generated ImplicationalSystem * @param nbR the number of rules of the generated ImplicationalSystem * * @return a random implicational system with a specified number of nodes * and rules. */ public static ImplicationalSystem random(int nbS, int nbR) { ImplicationalSystem sigma = new ImplicationalSystem(); // addition of elements for (int i = 0; i < nbS; i++) { sigma.addElement(Integer.valueOf(i)); } // addition of rules //for (int i = 0; i < nbR; i++) { One could get twice the same rule ... while (sigma.getRules().size() < nbR) { ComparableSet conclusion = new ComparableSet(); int choice = (int) Math.rint(nbS * Math.random()); int j = 1; for (Comparable c : sigma.getSet()) { if (j == choice) { conclusion.add(c); } j++; } ComparableSet premisse = new ComparableSet(); for (Comparable c : sigma.getSet()) { choice = (int) Math.rint(nbS * Math.random()); if (choice < nbS / 5) { premisse.add(c); } } //if (!premisse.isEmpty()) { sigma.addRule(new Rule(premisse, conclusion)); //} } return sigma; } /** * For the implicational rules of this component. */ private TreeSet<Rule> sigma; /** * For the elements space of this component. */ private TreeSet<Comparable> set; /* * --------------- CONSTRUCTORS ----------- */ /** * Constructs a new empty component. */ public ImplicationalSystem() { this.init(); } /** * Constructs this component from the specified set of rules `sigma`. * * @param sigma the set of rules. */ public ImplicationalSystem(Collection<Rule> sigma) { this.sigma = new TreeSet<Rule>(sigma); this.set = new TreeSet<Comparable>(); for (Rule rule : this.sigma) { set.addAll(rule.getPremise()); set.addAll(rule.getConclusion()); } } /** * Constructs this component as a copy of the specified ImplicationalSystem * `is`. * * Only structures (conataining reference of indexed elements) are copied. * * @param is the implicational system to be copied */ public ImplicationalSystem(ImplicationalSystem is) { this.sigma = new TreeSet<Rule>(is.getRules()); this.set = new TreeSet<Comparable>(is.getSet()); } /** * Constructs this component from the specified file. * * The file have to respect a certain format: * * An implicational system can be instancied from and save to a text file in * the following format: - A list of elements separated by a space in the * first line ; - then, each rule on a line, written like [premise] -> * [conclusion] where elements are separated by a space. * * ~~~ * a b c d e a b -> c d c d -> e * ~~~ * * Each element must be declared on the first line, otherwise, it is not * added in the rule Each rule must have a non empty concusion, otherwise, * it is not added in the component * * @param filename the name of the file * * @throws IOException When an IOException occurs */ public ImplicationalSystem(String filename) throws IOException { this.parse(filename); } /** * Initialise the implicational system. * * @return this for chaining */ public ImplicationalSystem init() { this.sigma = new TreeSet<Rule>(); this.set = new TreeSet<Comparable>(); return this; } /* * ------------- ACCESSORS METHODS ------------------ */ /** * Returns the set of rules. * * @return the set of rules of this component. */ public SortedSet<Rule> getRules() { return Collections.unmodifiableSortedSet((SortedSet<Rule>) this.sigma); } /** * Returns the set of indexed elements. * * @return the elements space of this component. */ public SortedSet<Comparable> getSet() { return Collections.unmodifiableSortedSet((SortedSet<Comparable>) this.set); } /** * Returns the number of elements in the set S of this component. * * @return the number of elements in the elements space of this component. */ public int sizeElements() { return this.set.size(); } /** * Returns the number of rules of this component. * * @return the number of rules of this component. */ public int sizeRules() { return this.sigma.size(); } /* * ------------- MODIFICATION METHODS ------------------ */ /** * Adds the specified element to the set `S` of this component. * * @param e the comparable to be added * * @return true if the element has been added to `S` */ public boolean addElement(Comparable e) { return set.add(e); } /** * Adds the specified element to the set `S` of this component. * * @param x the treeset of comparable to be added * * @return true if the element has been added to `S` */ public boolean addAllElements(TreeSet<Comparable> x) { boolean all = true; for (Comparable e : x) { if (!set.add(e)) { all = false; } } return all; } /** * Delete the specified element from the set `S` of this component and from * all the rule containing it. * * @param e the comparable to be added * * @return true if the element has been added to `S` */ public boolean deleteElement(Comparable e) { if (set.contains(e)) { set.remove(e); ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule : save.sigma) { Rule newR = new Rule(rule.getPremise(), rule.getConclusion()); newR.removeFromPremise(e); newR.removeFromConclusion(e); if (!rule.equals(newR)) { if (newR.getConclusion().size() != 0) { this.replaceRule(rule, newR); } else { this.removeRule(rule); } } } return true; } return false; } /** * Checks if the set S of this component contains the elements of the * specified rule. * * @param rule the rule to be checked * * @return true if `S` contains all the elements of the rule */ public boolean checkRuleElements(Rule rule) { for (Object e : rule.getPremise()) { if (!set.contains(e)) { return false; } } for (Object e : rule.getConclusion()) { if (!set.contains(e)) { return false; } } return true; } /** * Checks if this component already contains the specified rule. * * Rules are compared according to their premise and conclusion * * @param rule the rule to be tested * * @return true if `sigma` contains the rule */ public boolean containsRule(Rule rule) { return this.sigma.contains(rule); } /** * Adds the specified rule to this component. * * @param rule the rule to be added * * @return true the rule has been added to if `sigma` */ public boolean addRule(Rule rule) { if (!this.containsRule(rule) && this.checkRuleElements(rule)) { return this.sigma.add(rule); } return false; } /** * Removes the specified rule from the set of rules of this component. * * @param rule the rule to be removed * * @return true if the rule has been removed */ public boolean removeRule(Rule rule) { return this.sigma.remove(rule); } /** * Replaces the first specified rule by the second one. * * @param rule1 the rule to be replaced by `rule2` * @param rule2 the replacing rule * * @return true the rule has been replaced */ public boolean replaceRule(Rule rule1, Rule rule2) { return this.removeRule(rule1) && this.addRule(rule2); } /* * ----------- SAVING METHODS -------------------- */ /** * Returns a string representation of this component. * * The following format is used: * * An implicational system can be instancied from and save to a text file in * the following format: * - A list of elements separated by a space in the first line ; * - then, each rule on a line, written like [premise] -> [conclusion] where * elements are separated by a space. * * ~~~ * a b c d e * a b -> c * d c d -> e * ~~~ * * @return a string representation of this component. */ @Override public String toString() { StringBuilder s = new StringBuilder(); // first line : All elements of S separated by a space // a StringTokenizer is used to delete spaces in the // string description of each element of S for (Comparable e : this.set) { StringTokenizer st = new StringTokenizer(e.toString()); while (st.hasMoreTokens()) { s.append(st.nextToken()); } s.append(" "); } String newLine = System.getProperty("line.separator"); s.append(newLine); // next lines : a rule on each line, described by: // [elements of the premise separated by a space] -> [elements of the conclusion separated by a space] for (Rule rule : this.sigma) { s.append(rule.toString()).append(newLine); } return s.toString(); } /** * Save the description of this component in a file whose name is specified. * * @param filename the name of the file * * @throws IOException When an IOException occurs */ public void save(final String filename) throws IOException { Filer.getInstance().save(this, ImplicationalSystemIOFactory.getInstance(), filename); } /** * Parse the description of this component from a file whose name is * specified. * * @param filename the name of the file * * @return this for chaining * * @throws IOException When an IOException occurs */ public ImplicationalSystem parse(final String filename) throws IOException { this.init(); Filer.getInstance().parse(this, ImplicationalSystemIOFactory.getInstance(), filename); return this; } /* * ----------- PROPERTIES TEST METHODS -------------------- */ /** * Returns true if this component is a proper ImplicationalSystem. * * This test is perfomed in O(|Sigma||S|) by testing conclusion of each rule * * @return true if and only if this component is a proper implicational * system. */ public boolean isProper() { for (Rule rule : this.sigma) { for (Object c : rule.getConclusion()) { if (rule.getPremise().contains(c)) { return false; } } } return true; } /** * Returns true if this component is an unary ImplicationalSystem. * * This test is perfomed in O(|Sigma||S|) by testing conclusion of each rule * * @return true if this component is an unary ImplicationalSystem. */ public boolean isUnary() { for (Rule rule : this.sigma) { if (rule.getConclusion().size() > 1) { return false; } } return true; } /** * Returns true if this component is a compact ImplicationalSystem. * * This test is perfomed in O(|Sigma|^2|S|) by testing premises of each pair * of rules * * @return true if this component is a compact ImplicationalSystem. */ public boolean isCompact() { for (Rule rule1 : this.sigma) { for (Rule rule2 : this.sigma) { if (!rule1.equals(rule2) && rule1.getPremise().equals(rule2.getPremise())) { return false; } } } return true; } /** * Returns true if conclusion of rules of this component are closed. * * This test is perfomed in O(|Sigma||S|) by testing conclusion of each rule * * @return true if conclusion of rules of this component are closed. */ public boolean isRightMaximal() { for (Rule rule : this.sigma) { if (!rule.getConclusion().containsAll(this.closure(rule.getConclusion()))) { return false; } } return true; } /** * Returns true if this component is left minimal. * * This test is perfomed in O(|Sigma|^2|S|) by testing conclusions of each * pair of rules * * @return true if this component is left minimal. */ public boolean isLeftMinimal() { for (Rule rule1 : this.sigma) { for (Rule rule2 : this.sigma) { if (!rule1.equals(rule2) && rule1.getPremise().containsAll(rule2.getPremise()) && rule1.getConclusion().equals(rule2.getConclusion())) { return false; } } } return true; } /** * Returns true if this component is direct. * * This test is perfomed in O(|Sigma|^2|S|) by testing if closure of the * premisse of each conclusion can be obtained by only one iteration on the * set of rules. * * @return true if this component is direct. */ public boolean isDirect() { for (Rule rule1 : this.sigma) { TreeSet<Comparable> onePass = new TreeSet(rule1.getPremise()); for (Rule rule2 : this.sigma) { if (rule1.getPremise().containsAll(rule2.getPremise())) { onePass.addAll(rule2.getConclusion()); } } if (!onePass.equals(this.closure(rule1.getPremise()))) { return false; } } return true; } /** * Returns true if this component is minimum. * * This test is perfomed in O(|Sigma|^2|S|) by testing if closure of the * premisse of each conclusion can be obtained by only one iteration on the * set of rules. * * @return true if this component is minimum. */ public boolean isMinimum() { ImplicationalSystem tmp = new ImplicationalSystem(this); tmp.makeRightMaximal(); for (Rule rule : sigma) { ImplicationalSystem epsilon = new ImplicationalSystem(tmp); epsilon.removeRule(rule); TreeSet<Comparable> clThis = this.closure(rule.getPremise()); TreeSet<Comparable> clEpsilon = epsilon.closure(rule.getPremise()); if (clThis.equals(clEpsilon)) { return false; } } return true; } /** * Returns true if this component is equal to its canonical direct basis. * * The canonical direct basis is computed before to be compare with this * component. * * This test is performed in O(d|S|), where d corresponds to the number of * rules that have to be added by the direct treatment. This number is * exponential in the worst case. * * @return true if this component is equal to its canonical direct basis. */ public boolean isCanonicalDirectBasis() { ImplicationalSystem cdb = new ImplicationalSystem(this); cdb.makeCanonicalDirectBasis(); return this.isIncludedIn(cdb) && cdb.isIncludedIn(this); } /** * Returns true if this component is equal to its canonical basis. * * The canonical basis is computed before to be compare with this component. * * This treatment is performed in (|Sigma||S|cl) where O(cl) is the * computation of a closure. * * @return true if this component is equal to its canonical basis. */ public boolean isCanonicalBasis() { ImplicationalSystem cb = new ImplicationalSystem(this); cb.makeCanonicalBasis(); return this.isIncludedIn(cb) && cb.isIncludedIn(this); } /** * Compares by inclusion of the proper and unary form of this component with * the specified one. * * @param is another ImplicationalSystem * * @return true if really include in this componenet. */ public boolean isIncludedIn(ImplicationalSystem is) { ImplicationalSystem tmp = new ImplicationalSystem(this); tmp.makeProper(); tmp.makeUnary(); is.makeProper(); is.makeUnary(); for (Rule rule : tmp.sigma) { if (!is.containsRule(rule)) { return false; } } return true; } /* * ----------- PROPERTIES MODIFICATION METHODS -------------------- */ /** * Makes this component a proper ImplicationalSystem. * * Elements that are at once in the conclusion and in the premise are * deleted from the conclusion. When the obtained conclusion is an empty * set, the rule is deleted from this component * * This treatment is performed in O(|Sigma||S|). * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeProper() { ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule : save.sigma) { // deletes elements of conclusion which are in the premise Rule newR = new Rule(rule.getPremise(), rule.getConclusion()); for (Object e : rule.getConclusion()) { if (newR.getPremise().contains(e)) { newR.removeFromConclusion(e); } } // replace the rule by the new rule is it has been modified if (!rule.equals(newR)) { this.replaceRule(rule, newR); } // delete rule with an empty conclusion if (newR.getConclusion().isEmpty()) { this.removeRule(newR); } } return save.sizeRules() - this.sizeRules(); } /** * Makes this component an unary ImplicationalSystem. * * This treatment is performed in O(|Sigma||S|) * * A rule with a non singleton as conclusion is replaced with a sets of * rule, one rule for each element of the conclusion. * * This treatment is performed in O(|Sigma||S|). * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeUnary() { ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule : save.sigma) { if (rule.getConclusion().size() > 1) { this.removeRule(rule); TreeSet<Comparable> conclusion = rule.getConclusion(); TreeSet<Comparable> premise = rule.getPremise(); for (Comparable e : conclusion) { TreeSet<Comparable> newC = new TreeSet(); newC.add(e); Rule newRule = new Rule(premise, newC); this.addRule(newRule); } } } return save.sizeRules() - this.sizeRules(); } /** * Replaces rules of same premise by only one rule. * * This treatment is performed in O(|sigma|^2|S|) * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeCompact() { ImplicationalSystem save = new ImplicationalSystem(this); int before = this.sigma.size(); this.sigma = new TreeSet(); while (save.sigma.size() > 0) { Rule rule1 = save.sigma.first(); ComparableSet newConc = new ComparableSet(); Iterator<Rule> it2 = save.sigma.iterator(); while (it2.hasNext()) { Rule rule2 = it2.next(); if (!rule1.equals(rule2) && rule1.getPremise().equals(rule2.getPremise())) { newConc.addAll(rule2.getConclusion()); it2.remove(); } } if (newConc.size() > 0) { newConc.addAll(rule1.getConclusion()); Rule newR = new Rule(rule1.getPremise(), newConc); this.addRule(newR); } else { this.addRule(rule1); } save.removeRule(rule1); } return before - this.sigma.size(); } /** * Replaces association rules of same premise, same support and same * confidence by only one rule. * * This treatment is performed in O(|sigma|^2|S|) * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeCompactAssociation() { ImplicationalSystem save = new ImplicationalSystem(this); int before = this.sigma.size(); this.sigma = new TreeSet(); while (save.sigma.size() > 0) { AssociationRule rule1 = (AssociationRule) save.sigma.first(); ComparableSet newConc = new ComparableSet(); Iterator<Rule> it2 = save.sigma.iterator(); while (it2.hasNext()) { AssociationRule rule2 = (AssociationRule) it2.next(); if (!rule1.equals(rule2) && rule1.getPremise().equals(rule2.getPremise()) && rule1.getConfidence() == rule2.getConfidence() && rule1.getSupport() == rule2.getSupport()) { newConc.addAll(rule2.getConclusion()); it2.remove(); } } if (newConc.size() > 0) { newConc.addAll(rule1.getConclusion()); AssociationRule newR = new AssociationRule(rule1.getPremise(), newConc, rule1.getSupport(), rule1.getConfidence()); this.addRule(newR); } else { this.addRule(rule1); } save.removeRule(rule1); } return before - this.sigma.size(); } /** * Replaces conclusion of each rule with their closure without the premise. * * This treatment is performed in O(|sigma||S|cl), where O(cl) is the * computation of a closure. * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeRightMaximal() { int s = this.sizeRules(); this.makeCompact(); ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule : save.sigma) { Rule newR = new Rule(rule.getPremise(), this.closure(rule.getPremise())); if (!rule.equals(newR)) { this.replaceRule(rule, newR); } } return s - this.sizeRules(); } /** * Makes this component a left minimal and compact ImplicationalSystem. * * The unary form of this componant is first computed: if two rules have the * same unary conclusion, the rule with the inclusion-maximal premise is * deleted. * * Then, the left-minimal treatment is performed in O(|sigma|^2|S|)) * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeLeftMinimal() { this.makeUnary(); ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule1 : save.sigma) { for (Rule rule2 : save.sigma) { if (!rule1.equals(rule2) && rule2.getPremise().containsAll(rule1.getPremise()) && rule1.getConclusion().equals(rule2.getConclusion())) { this.sigma.remove(rule2); } } } this.makeCompact(); return save.sizeRules() - this.sizeRules(); } /** * Makes this component a compact and direct ImplicationalSystem. * * The unary and proper form of this componant is first computed. For two * given rules rule1 and rule2, if the conclusion of rule1 contains the * premise of rule1, then a new rule is addes, with rule1.premisse + * rule2.premisse - rule1.conclusion as premise, and rule2.conclusion as * conlusion. This treatment is performed in a recursive way until no new * rule is added. * * This treatment is performed in O(d|S|), where d corresponds to the number * of rules that have to be added by the direct treatment, that can be * exponential in the worst case. * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeDirect() { this.makeUnary(); this.makeProper(); int s = this.sizeRules(); boolean ok = true; while (ok) { ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule1 : save.sigma) { for (Rule rule2 : save.sigma) { if (!rule1.equals(rule2) && !rule1.getPremise().containsAll(rule2.getConclusion())) { ComparableSet c = new ComparableSet(rule2.getPremise()); c.removeAll(rule1.getConclusion()); c.addAll(rule1.getPremise()); if (!c.containsAll(rule2.getPremise())) { Rule newR = new Rule(c, rule2.getConclusion()); // new_rule.addAllToPremise (rule1.getPremise()); // new_rule.addAllToPremise (rule2.getPremise()); // new_rule.removeAllFromPremise(rule1.getConclusion()); // new_rule.addAllToConclusion(rule2.getConclusion() ); this.addRule(newR); } } } } if (this.sizeRules() == save.sizeRules()) { ok = false; } } this.makeCompact(); return s - this.sizeRules(); } /** * Makes this component a minimum and proper ImplicationalSystem. * * A rule is deleted when the closure of its premisse remains the same even * if this rule is suppressed. * * This treatment is performed in O(|sigma||S|cl) where O(cl) is the * computation of a closure. * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeMinimum() { this.makeRightMaximal(); ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule : save.sigma) { ImplicationalSystem epsilon = new ImplicationalSystem(this); epsilon.removeRule(rule); if (epsilon.closure(rule.getPremise()).equals(this.closure(rule.getPremise()))) { this.removeRule(rule); } } return save.sizeRules() - this.sizeRules(); } /** * Replace this component by its canonical direct basis. * * The proper, unary and left minimal form of this component is first * computed, before to apply the recursive directe treatment, then the left * minimal treatment. * * This treatment is performed in O(d), where d corresponds to the number of * rules that have to be added by the direct treatment. This number is * exponential in the worst case. * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeCanonicalDirectBasis() { int s = this.sizeRules(); this.makeProper(); this.makeLeftMinimal(); this.makeDirect(); this.makeLeftMinimal(); this.makeCompact(); return s - this.sizeRules(); } /** * Replace this component by the canonical basis. * * Conclusion of each rule is first replaced by its closure. Then, premise * of each rule r is replaced by its closure in ImplicationalSystem \ rule. * This treatment is performed in (|Sigma||S|cl) where O(cl) is the * computation of a closure. * * @return the difference between the number of rules of this component * before and after this treatment */ public int makeCanonicalBasis() { this.makeMinimum(); ImplicationalSystem save = new ImplicationalSystem(this); for (Rule rule : save.sigma) { ImplicationalSystem epsilon = new ImplicationalSystem(this); epsilon.removeRule(rule); Rule tmp = new Rule(epsilon.closure(rule.getPremise()), rule.getConclusion()); if (!rule.equals(tmp)) { this.replaceRule(rule, tmp); } } this.makeProper(); return save.sizeRules() - this.sizeRules(); } /* * --------------- METHODS BASED ON GRAPH ------------ */ /** * Returns the representative graph of this component. * * Nodes of the graph are attributes of this components. For each proper * rule X+b->a, there is an {X}-valuated edge from a to b. Notice that, for * a rule b->a, the edge from a to b is valuated by emptyset. and for the * two rules X+b->a and Y+b->a, the edge from a to b is valuated by {X,Y}. * * @return the representative graph of this component. */ public ConcreteDGraph representativeGraph() { ImplicationalSystem tmp = new ImplicationalSystem(this); tmp.makeUnary(); // nodes of the graph are elements not belonging to X ConcreteDGraph pred = new ConcreteDGraph(); TreeMap<Comparable, Node> nodeCreated = new TreeMap<Comparable, Node>(); for (Comparable x : tmp.getSet()) { Node node = new Node(x); pred.addNode(node); nodeCreated.put(x, node); } // an edge is added from b to a when there exists a rule X+a -> b or a -> b for (Rule rule : tmp.getRules()) { for (Object a : rule.getPremise()) { ComparableSet diff = new ComparableSet(rule.getPremise()); diff.remove(a); Node source = nodeCreated.get(rule.getConclusion().first()); Node target = nodeCreated.get(a); Edge ed; if (pred.containsEdge(source, target)) { ed = pred.getEdge(source, target); } else { ed = new Edge(source, target, new TreeSet<ComparableSet>()); pred.addEdge(ed); } ((TreeSet<ComparableSet>) ed.getContent()).add(diff); } } return pred; } /** * Returns the dependency graph of this component. * * Dependency graph of this component is the representative graph of the * canonical direct basis. Therefore, the canonical direct basis has to be * generated before to compute its representativ graph, and this treatment * is performed in O(d), as for the canonical direct basis generation, where * d corresponds to the number of rules that have to be added by the direct * treatment. This number is exponential in the worst case. * * @return the dependency graph of this component. */ public ConcreteDGraph dependencyGraph() { ImplicationalSystem bcd = new ImplicationalSystem(this); bcd.makeCanonicalDirectBasis(); bcd.makeUnary(); return bcd.representativeGraph(); } /** * Removes from this component reducible elements. * * Reducible elements are elements equivalent by closure to others elements. * They are computed by `getReducibleElements` of `ClosureSystem` in * O(O(|Sigma||S|^2) * * @return the set of reducibles removed elements, with their equivalent * elements */ public TreeMap<Comparable, TreeSet<Comparable>> reduction() { // compute the reducible elements TreeMap red = this.getReducibleElements(); // collect elements implied by nothing TreeSet<Comparable> truth = this.closure(new TreeSet<Comparable>()); // modify each rule for (Object x : red.keySet()) { TreeSet<Rule> rules = this.sigma; rules = (TreeSet<Rule>) rules.clone(); for (Rule rule : rules) { Rule rule2 = new Rule(); boolean modif = false; // replace the reducible element by its equivalent in the premise TreeSet premise = rule.getPremise(); premise = (TreeSet) premise.clone(); if (premise.contains(x)) { premise.remove(x); premise.addAll((TreeSet) red.get(x)); rule2.addAllToPremise(premise); modif = true; } else { rule2.addAllToPremise(premise); } // replace the reducible element by its equivalent in the conclusion TreeSet conclusion = rule.getConclusion(); conclusion = (TreeSet) conclusion.clone(); if (conclusion.contains(x)) { conclusion.remove(x); conclusion.addAll((TreeSet) red.get(x)); rule2.addAllToConclusion(conclusion); modif = true; } else { rule2.addAllToConclusion(conclusion); } // replace the rule if modified if (modif) { if (truth.containsAll(rule2.getConclusion())) { this.removeRule(rule); // Conclusions of this rule are always true, thus the rule is useless } else { this.replaceRule(rule, rule2); } } else if (truth.containsAll(rule.getConclusion())) { this.removeRule(rule); // Conclusions of this rule are always true, thus the rule is useless } } // remove the reducible elements from the elements set this.deleteElement((Comparable) x); } return red; } /** * Return true if this component is reduced. * * @return true if this component is reduced. */ public boolean isReduced() { // Copy this component not to modify it ImplicationalSystem tmp = new ImplicationalSystem(this); return tmp.reduction().isEmpty(); } /* * --------------- IMPLEMENTATION OF CLOSURESYSTEM ABSTRACT METHODS ------------ */ /** * Builds the closure of a set X of indexed elements. * * The closure is initialised with X. The closure is incremented with the * conclusion of each rule whose premise is included in it. Iterations over * the rules are performed until no new element has to be added in the * closure. * * For direct ImplicationalSystem, only one iteration is needed, and the * treatment is performed in O(|Sigma||S|). * * For non direct ImplicationalSystem, at most |S| iterations are needed, * and this tratment is performed in O(|Sigma||S|^2). * * @param x a TreeSet of indexed elements * * @return the closure of X for this component */ public TreeSet<Comparable> closure(TreeSet<Comparable> x) { TreeSet<Comparable> oldES = new TreeSet<Comparable>(); // all the attributes are in their own closure TreeSet<Comparable> newES = new TreeSet<Comparable>(x); do { oldES.addAll(newES); for (Rule rule : this.sigma) { if (newES.containsAll(rule.getPremise()) || rule.getPremise().isEmpty()) { newES.addAll(rule.getConclusion()); } } } while (!oldES.equals(newES)); return newES; } }
35.096375
131
0.574268
25f9d9dc4bdb2bb7b55307094bf50d7df9633d44
1,988
package net.mgsx.gltf.demo; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.ObjectMap.Entry; import net.mgsx.gltf.demo.data.ModelEntry; import net.mgsx.gltf.loaders.glb.GLBLoader; import net.mgsx.gltf.loaders.gltf.GLTFLoader; import net.mgsx.gltf.scene3d.scene.SceneAsset; public class GLTFTest extends ApplicationAdapter { private String samplesPath; public GLTFTest() { this("models"); } public GLTFTest(String samplesPath) { this.samplesPath = samplesPath; } @Override public void create() { FileHandle rootFolder = Gdx.files.internal(samplesPath); FileHandle file = rootFolder.child("model-index.json"); Array<ModelEntry> entries = new Json().fromJson(Array.class, ModelEntry.class, file); for(ModelEntry entry : entries){ for(Entry<String, String> variant : entry.variants){ FileHandle baseFolder = rootFolder.child(entry.name).child(variant.key); FileHandle glFile = baseFolder.child(variant.value); long ptime = System.currentTimeMillis(); SceneAsset sceneAsset; try{ if(glFile.extension().equals("gltf")){ sceneAsset = new GLTFLoader().load(glFile); }else if(glFile.extension().equals("glb")){ sceneAsset = new GLBLoader().load(glFile); }else{ throw new GdxRuntimeException("unknown file extension " + glFile.extension()); } long ctime = System.currentTimeMillis(); float dtime = (ctime - ptime) / 1000f; System.out.println(entry.name + " | " + variant.key + " | ok | " + dtime); sceneAsset.dispose(); }catch(GdxRuntimeException e){ System.err.println(entry.name + " | " + variant.key + " | error | " + e.getMessage()); } try { Thread.sleep(10); } catch (InterruptedException e) { } } } } }
29.235294
91
0.694668
d369d151cc06eb0a595a8d55bab4212a6bcea5ad
1,748
package com.example.dell.app; public class Demo { public static void main(String[] args) { try { byte[] arr = "天气预报".getBytes("GBK"); System.out.println(getJineiMa("天气预报")); }catch (Exception e){ e.printStackTrace(); } System.out.println("1234"); } public static String getJineiMa(String chineseName){ StringBuffer sb = new StringBuffer(); try { char[]ch = chineseName.toCharArray(); for (char c : ch){ if (isChinese(c)){ byte[]by = String.valueOf(c).getBytes("GBK"); for (byte b : by){ sb.append(Integer.toHexString(b & 0xff)); } System.out.println(sb); }else{ byte b = (byte) c; sb.append(Integer.toHexString(b & 0xff)); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString().toUpperCase().trim(); } private static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { return true; } return false; } }
37.191489
149
0.547483
f4c624a30347ba6401d6facca5eb6811e302c910
1,421
/* * Copyright 2017 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.commons.core.models; import java.util.Collection; import java.util.Map; import java.util.Set; /** * Interface that describes the basic common information of the variant model */ public interface IVariant { VariantType getType(); String getChromosome(); long getStart(); long getEnd(); int getLength(); String getReference(); String getAlternate(); Set<String> getIds(); default String getMainId() { return null; } /** @deprecated this field is temporary, use getIds or getMainId instead */ @Deprecated Set<String> getDbsnpIds(); Map<String, Set<String>> getHgvs(); Collection<? extends IVariantSourceEntry> getSourceEntries(); IVariantSourceEntry getSourceEntry(String fileId, String studyId); }
25.375
79
0.717101
1b7ff83a116bcf40b6510c231862c99f44a6fa4e
2,890
package com.airhacks.followme.dashboard; /* * #%L * igniter * %% * Copyright (C) 2013 - 2016 Adam Bien * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.airhacks.followme.dashboard.light.LightView; import com.airhacks.followme.north.NorthView; import java.net.URL; import java.time.LocalDate; import java.util.ResourceBundle; import javafx.beans.binding.Bindings; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.util.converter.NumberStringConverter; import javax.inject.Inject; /** * * @author adam-bien.com */ public class DashboardPresenter implements Initializable { @FXML Label message; @FXML Label a; @FXML TextField b; @FXML TextField c; @FXML Pane lightsBox; @Inject Tower tower; @Inject private String prefix; @Inject private String happyEnding; @Inject private LocalDate date; private String theVeryEnd; @FXML AnchorPane south; IntegerProperty bNumber = new SimpleIntegerProperty(); IntegerProperty cNumber = new SimpleIntegerProperty(); @Override public void initialize(URL url, ResourceBundle rb) { //fetched from dashboard.properties this.theVeryEnd = rb.getString("theEnd"); Bindings.bindBidirectional(b.textProperty(), bNumber, new NumberStringConverter()); Bindings.bindBidirectional(c.textProperty(), cNumber, new NumberStringConverter()); a.textProperty().bind(bNumber.add(cNumber).asString()); NorthView northView = new NorthView(); // south.getChildren().add(northView.getView()); northView.getViewAsync(south.getChildren()::add); } public void createLights() { for (int i = 0; i < 255; i++) { final int red = i; LightView view = new LightView((f) -> red); view.getViewAsync(lightsBox.getChildren()::add); } } public void launch() { message.setText("Date: " + date + " -> " + prefix + tower.readyToTakeoff() + happyEnding + theVeryEnd ); } }
26.272727
109
0.679585
b903f4ea4c7afbf18daeeed3a0dfb868a964d0bf
250
package com.redis.tpl; import lombok.Data; /** * @author liuweilong * @description * @date 2019/6/19 15:02 */ @Data public class HashObject { private String name; private String password; private Integer age; private Long id; }
14.705882
28
0.676
367930a820953df6d04bf5674f2995b0d6a6508d
30,953
package repository; import io.ebean.*; import models.*; import org.mindrot.jbcrypt.BCrypt; import play.db.ebean.EbeanConfig; import javax.inject.Inject; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.CompletionStage; import static java.lang.Integer.parseInt; import static java.util.concurrent.CompletableFuture.supplyAsync; /** * A profile repository that executes database operations in a different * execution context handles all interactions with the profile table . */ public class ProfileRepository { private final EbeanServer ebeanServer; private final DatabaseExecutionContext executionContext; private final ProfilePassportCountryRepository profilePassportCountryRepository; private final ProfileNationalityRepository profileNationalityRepository; private final ProfileTravellerTypeRepository profileTravellerTypeRepository; private final RolesRepository rolesRepository; @Inject public ProfileRepository(EbeanConfig ebeanConfig, DatabaseExecutionContext executionContext) { this.ebeanServer = Ebean.getServer(ebeanConfig.defaultServer()); this.executionContext = executionContext; this.profilePassportCountryRepository = new ProfilePassportCountryRepository(ebeanConfig, executionContext); this.profileNationalityRepository = new ProfileNationalityRepository(ebeanConfig, executionContext); this.profileTravellerTypeRepository = new ProfileTravellerTypeRepository(ebeanConfig, executionContext); this.rolesRepository = new RolesRepository(ebeanConfig, executionContext); } /** * Method for login to check if there is a traveller account under the supplied email * * @param email String of the logged in users email * @return boolean if profile exists or not */ public boolean checkProfileExists(String email) { String selectQuery = "Select * from profile WHERE email = ?"; SqlRow row = ebeanServer.createSqlQuery(selectQuery).setParameter(1, email).findOne(); return row != null; } /** * Method to validate if the given email and password match an account in the database * * @param email users email input * @param password users password input * @return */ public boolean validate(String email, String password) { String selectQuery = "SELECT * FROM profile WHERE email = ?"; List<SqlRow> rows = ebeanServer.createSqlQuery(selectQuery) .setParameter(1, email) .findList(); for (SqlRow row: rows) { if (BCrypt.checkpw(password, row.getString("password"))) { return true; } } return false; } /** * Method to get all profiles, their roles will also be filled. * * @return List of all profiles */ public List<Profile> getAll() { String selectQuery = "SELECT * FROM profile WHERE soft_delete = 0;"; List<SqlRow> rows = ebeanServer.createSqlQuery(selectQuery).findList(); List<Profile> allProfiles = new ArrayList<>(); for (SqlRow row : rows) { allProfiles.add(profileFromRow(row)); } return allProfiles; } /** * Ebeans method to get all profiles not filling linking tables * @return List of all profiles */ public List<Profile> getAllEbeans(){ return (new ArrayList<>(ebeanServer.find(Profile.class) .where() .eq("soft_delete", 0) .findList())); } /** * Method to get all profiles for the travellers page with pagination. Gets the first 9 initially and uses * an offset to load the next set of profiles to display with each new page. * * All profiles roles will also be filled. * * @return List of all profiles */ public List<Profile> getAllTravellersPaginate(Integer offset) { String selectQuery = "SELECT * " + "FROM profile " + "WHERE soft_delete = 0 " + "ORDER BY profile_id ASC " + "LIMIT 12 OFFSET ?"; List<SqlRow> rows = ebeanServer.createSqlQuery(selectQuery) .setParameter(1, offset) .findList(); List<Profile> allProfiles = new ArrayList<>(); for (SqlRow row : rows) { allProfiles.add(profileFromRow(row)); } return allProfiles; } /** * Method for getting a profile * * @param email String of the email to get * @return Profile class of the user */ public Profile getProfileById(String email) { Profile profile = ebeanServer.find(Profile.class).where().like("email", email).findOne(); profile.setNationalities(profileNationalityRepository.getList(profile.getProfileId()).get()); profile.setPassports(profilePassportCountryRepository.getList(profile.getProfileId()).get()); profile.setTravellerTypes(profileTravellerTypeRepository.getList(profile.getProfileId()).get()); profile.setRoles(rolesRepository.getProfileRoles(profile.getProfileId()).get()); return profile; } /** * Method for getting a profile that is not soft deleted * * @param userId String of the email to get * @return Profile class of the user */ public Profile getExistingProfileByProfileId(Integer userId) { Profile profile = ebeanServer.find(Profile.class) .where().eq("soft_delete", "0").and() .like("profile_id", userId.toString()).findOne(); profile.setNationalities(profileNationalityRepository.getList(profile.getProfileId()).get()); profile.setPassports(profilePassportCountryRepository.getList(profile.getProfileId()).get()); profile.setTravellerTypes(profileTravellerTypeRepository.getList(profile.getProfileId()).get()); profile.setRoles(rolesRepository.getProfileRoles(profile.getProfileId()).get()); return profile; } /** * Method for getting a profile * * @param userId String of the email to get * @return Profile class of the user */ public Profile getProfileByProfileId(Integer userId) { Profile profile = ebeanServer.find(Profile.class).setId(userId).findOne(); profile.setRoles(rolesRepository.getProfileRoles(userId).get()); return profile; } /** * Method for getting a page of profiles linked to an event from a given offset * @param userIdList List of profile ids to get profile subset * @param offset start index of page * @return list of profiles to be displayed in current page */ public Optional<List<Profile>> getAllProfileByIdListPage(List<Integer> userIdList, int offset) { if (userIdList.isEmpty()) { return Optional.empty(); } else { return Optional.of(ebeanServer.find(Profile.class).setMaxRows(5).setFirstRow(offset).where().idIn(userIdList).findList()); } } /** * Database access method to query the database for profiles that match the given search parameters * * @param travellerType Traveller type to search for * @param lowerAge Lower limit for age of profile * @param upperAge Upper limit for age of profile * @param gender Gender of profile * @param nationality nationality of profile * @return List of profiles that match query parameters */ public List<Profile> searchProfiles(String travellerType, Date lowerAge, Date upperAge, String gender, String nationality, int offset) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String queryString = "SELECT profile_traveller_type.profile FROM profile_traveller_type " + "JOIN profile_nationality ON profile_nationality.profile = profile_traveller_type.profile " + "JOIN nationality ON profile_nationality.nationality = nationality_id " + "JOIN traveller_type ON profile_traveller_type.traveller_type = traveller_type_id"; boolean whereAdded = false; if (!travellerType.equals("")) { queryString += " WHERE traveller_type_name = ?"; whereAdded = true; } if (!nationality.equals("")) { if (!whereAdded) { queryString += " WHERE nationality_name = ?"; } else { queryString += " AND nationality_name = ?"; } } queryString += " LIMIT 100"; SqlQuery query = ebeanServer.createSqlQuery(queryString); if (!travellerType.equals("")) { query.setParameter(1, travellerType); } if (!nationality.equals("")) { if (!whereAdded) { query.setParameter(1, nationality); } else { query.setParameter(2, nationality); } } List<SqlRow> foundRows = query.findList(); List<Integer> foundIds = new ArrayList<>(); List<Profile> foundProfiles = new ArrayList<>(); if (!foundRows.isEmpty()) { for (SqlRow row : foundRows) { foundIds.add(row.getInteger("profile")); } foundProfiles = ebeanServer.find(Profile.class).where() .idIn(foundIds) .contains("gender", gender) .gt("birth_date", dateFormat.format(upperAge)) .lt("birth_date", dateFormat.format(lowerAge)) .setMaxRows(12) .setFirstRow(offset) .findList(); for (Profile profile : foundProfiles) { Optional<Map<Integer, PassportCountry>> optionalIntegerPassportCountryMap = profilePassportCountryRepository.getList(profile.getProfileId()); optionalIntegerPassportCountryMap.ifPresent(profile::setPassports); Optional<Map<Integer, Nationality>> optionalNationalityMap = profileNationalityRepository.getList(profile.getProfileId()); optionalNationalityMap.ifPresent(profile::setNationalities); Optional<Map<Integer, TravellerType>> optionalTravellerTypeMap = profileTravellerTypeRepository.getList(profile.getProfileId()); optionalTravellerTypeMap.ifPresent(profile::setTravellerTypes); } } return foundProfiles; } /** * Method to get the size of the profile search result * Used for the max value in the travellers search pagination * * @param travellerType Traveller type to search for * @param lowerAge Lower limit for age of profile * @param upperAge Upper limit for age of profile * @param gender Gender of profile * @param nationality nationality of profile * @return int containing the size of the found profiles based on the search */ public int getNumSearchProfiles(String travellerType, Date lowerAge, Date upperAge, String gender, String nationality){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String queryString = "SELECT profile_traveller_type.profile FROM profile_traveller_type " + "JOIN profile_nationality ON profile_nationality.profile = profile_traveller_type.profile " + "JOIN nationality ON profile_nationality.nationality = nationality_id " + "JOIN traveller_type ON profile_traveller_type.traveller_type = traveller_type_id"; boolean whereAdded = false; if (!travellerType.equals("")) { queryString += " WHERE traveller_type_name = ?"; whereAdded = true; } if (!nationality.equals("")) { if (!whereAdded) { queryString += " WHERE nationality_name = ?"; } else { queryString += " AND nationality_name = ?"; } } SqlQuery query = ebeanServer.createSqlQuery(queryString); if (!travellerType.equals("")) { query.setParameter(1, travellerType); } if (!nationality.equals("")) { if (!whereAdded) { query.setParameter(1, nationality); } else { query.setParameter(2, nationality); } } List<SqlRow> foundRows = query.findList(); List<Integer> foundIds = new ArrayList<>(); int numProfiles = 0; if (!foundRows.isEmpty()) { for (SqlRow row : foundRows) { foundIds.add(row.getInteger("profile")); } numProfiles = ebeanServer.find(Profile.class).where() .idIn(foundIds) .contains("gender", gender) .gt("birth_date", dateFormat.format(upperAge)) .lt("birth_date", dateFormat.format(lowerAge)) .findCount(); } return numProfiles; } /** * Create a profile instance from data of an SQL Row result * * @param row The SQL query result as a row * @return A profile made based on data from row */ private Profile profileFromRow(SqlRow row) { Integer profileId = row.getInteger("profile_id"); Map<Integer, PassportCountry> passportCountries = new HashMap<>(); Map<Integer, Nationality> nationalities = new HashMap<>(); Map<Integer, TravellerType> travellerTypes = new HashMap<>(); List<String> roles = new ArrayList<>(); Optional<Map<Integer, PassportCountry>> optionalIntegerPassportCountryMap = profilePassportCountryRepository.getList(profileId); if (optionalIntegerPassportCountryMap.isPresent()) { passportCountries = optionalIntegerPassportCountryMap.get(); } Optional<Map<Integer, Nationality>> optionalNationalityMap = profileNationalityRepository.getList(profileId); if (optionalNationalityMap.isPresent()) { nationalities = optionalNationalityMap.get(); } Optional<Map<Integer, TravellerType>> optionalTravellerTypeMap = profileTravellerTypeRepository.getList(profileId); if (optionalTravellerTypeMap.isPresent()) { travellerTypes = optionalTravellerTypeMap.get(); } Optional<List<String>> optionalRoles = rolesRepository.getProfileRoles(profileId); if (optionalRoles.isPresent()) { roles = optionalRoles.get(); } return new Profile(profileId, row.getString("first_name"), row.getString("middle_name"), row.getString("last_name"), row.getString("email"), row.getDate("birth_date"), passportCountries, row.getString("gender"), row.getDate("time_created"), nationalities, travellerTypes, roles); } /** * This method finds a profile in the database using a given profile id * * @param profileId the id of the profile to find * @return CompletionStage holding an optional of the profile found */ public CompletionStage<Optional<Profile>> findById(int profileId) { return supplyAsync(() -> { Profile profile = ebeanServer.find(Profile.class).setId(profileId).findOne(); profile.setNationalities(profileNationalityRepository.getList(profile.getProfileId()).get()); profile.setPassports(profilePassportCountryRepository.getList(profile.getProfileId()).get()); profile.setTravellerTypes(profileTravellerTypeRepository.getList(profile.getProfileId()).get()); profile.setRoles(rolesRepository.getProfileRoles(profile.getProfileId()).get()); return Optional.of(profile); }); } /** * Finds one profile using its email as a query * * @param email the users email * @return a Profile object that matches the email */ public CompletionStage<Optional<Profile>> lookupEmail(String email) { return supplyAsync(() -> { String qry = "Select * from profile where email = ? and soft_delete = 0"; List<SqlRow> rowList = ebeanServer.createSqlQuery(qry).setParameter(1, email).findList(); Profile profile = null; if (!rowList.isEmpty() && !rowList.get(0).isEmpty()) { profile = profileFromRow(rowList.get(0)); } return Optional.ofNullable(profile); }, executionContext); } /** * Inserts a profile into the ebean database server * * @param profile Profile object to insert into the database * @return the image id */ public CompletionStage<Optional<Integer>> insert(Profile profile) { return supplyAsync(() -> { profile.setTimeCreated(new Date()); Transaction txn = ebeanServer.beginTransaction(); String qry = "INSERT INTO profile (first_name, middle_name, last_name, email, " + "password, birth_date, gender) " + "VALUES (?, ?, ?, ?, ?, ?, ?)"; Integer value = null; try { SqlUpdate query = Ebean.createSqlUpdate(qry); query.setParameter(1, profile.getFirstName()); query.setParameter(2, profile.getMiddleName()); query.setParameter(3, profile.getLastName()); query.setParameter(4, profile.getEmail()); query.setParameter(5, profile.getPassword()); query.setParameter(6, profile.getBirthDate()); query.setParameter(7, profile.getGender()); query.setGetGeneratedKeys(true); // Need to set the ID of the generated key query.execute(); txn.commit(); value = parseInt(query.getGeneratedKey().toString()); // Id of the newly created profile for (String passportName : profile.getPassportsList()) { profilePassportCountryRepository.insertProfilePassportCountry(new PassportCountry(passportName), value); } for (String nationalityName : profile.getNationalityList()) { profileNationalityRepository.insertProfileNationality(new Nationality(nationalityName), value); } for (String travellerTypeName : profile.getTravellerTypesList()) { profileTravellerTypeRepository.insertProfileTravellerType(new TravellerType(travellerTypeName), value); } } catch (Exception e) { System.err.println("Search This: " + e); } finally { txn.end(); } return Optional.ofNullable(value); }, executionContext); } /** * Update profile in database using Profile model object, * and the raw password from an input field, which will be set if it is not null. * * @param newProfile Profile object with new details * @return */ public CompletionStage<Optional<Integer>> update(Profile newProfile, int userId) { if (isEmailTaken(newProfile.getEmail(), userId)) { throw new IllegalArgumentException("Email is already taken"); } return supplyAsync( () -> { Transaction txn = ebeanServer.beginTransaction(); String updateQuery = "UPDATE profile SET first_name = ?, middle_name = ?, last_name = ?, email = ?, " + "birth_date = ?, gender = ? " + "WHERE profile_id = ?"; Optional<Integer> value = Optional.empty(); try { if (ebeanServer.find(Profile.class).setId(userId).findOne() != null) { SqlUpdate query = Ebean.createSqlUpdate(updateQuery); query.setParameter(1, newProfile.getFirstName()); query.setParameter(2, newProfile.getMiddleName()); query.setParameter(3, newProfile.getLastName()); query.setParameter(4, newProfile.getEmail()); query.setParameter(5, newProfile.getBirthDate()); query.setParameter(6, newProfile.getGender()); query.setParameter(7, userId); query.execute(); txn.commit(); profileNationalityRepository.removeAll(userId); profilePassportCountryRepository.removeAll(userId); profileTravellerTypeRepository.removeAll(userId); for (String passportName : newProfile.getPassportsList()) { profilePassportCountryRepository.insertProfilePassportCountry( new PassportCountry(0, passportName), userId); } for (String nationalityName : newProfile.getNationalityList()) { profileNationalityRepository.insertProfileNationality( new Nationality(0, nationalityName), userId); } for (String travellerTypeName : newProfile.getTravellerTypesList()) { profileTravellerTypeRepository.insertProfileTravellerType( new TravellerType(0, travellerTypeName), userId); } value = Optional.of(userId); } } finally { txn.end(); } return value; }, executionContext); } public CompletionStage<Optional<Integer>> updatePassword(Integer profileId, String newPassword) { return supplyAsync( () -> { String password = BCrypt.hashpw(newPassword, "$2a$12$nODuNzk9U7Hrq6DgspSp4."); Transaction txn = ebeanServer.beginTransaction(); String updateQuery = "UPDATE profile SET password = ? WHERE profile_id = ?"; Optional<Integer> value = Optional.empty(); try { if (ebeanServer.find(Profile.class).setId(profileId).findOne() != null) { SqlUpdate query = Ebean.createSqlUpdate(updateQuery); query.setParameter(1, password); query.setParameter(2, profileId); query.execute(); txn.commit(); value = Optional.of(profileId); } } finally { txn.end(); } return value; }, executionContext); } /** * Deletes a profile from the database that matches the given email * * @param profileId the users id * @return an optional profile id */ public CompletionStage<Optional<Integer>> delete(Integer profileId) { return supplyAsync(() -> { Transaction txn = ebeanServer.beginTransaction(); String deleteQuery = "DELETE FROM profile Where profile_id = ?"; SqlUpdate query = Ebean.createSqlUpdate(deleteQuery); query.setParameter(1, profileId); query.execute(); txn.commit(); return Optional.of(0); }, executionContext); } /** * sets soft delete for a profile which eather deletes it or * undoes the delete * @param profileId The ID of the profile to soft delete * @param value, the value softDelete is to be set to * @return */ public CompletionStage<Integer> setSoftDelete(int profileId, int value) { return supplyAsync(() -> { try { Profile targetProfile = ebeanServer.find(Profile.class).setId(profileId).findOne(); if (targetProfile != null) { targetProfile.setSetSoftDelete(value); targetProfile.update(); return 1; } else { return 0; } } catch(Exception e) { return 0; } }, executionContext); } /** * Used to update (add or remove) admin privilege to another user from the Travellers page. * * @param clickedId the id of the user that is going to have admin privilege updated. * @return The email member who had their admin updated. */ public CompletionStage<Optional<Integer>> updateAdminPrivelege(Integer clickedId) { return supplyAsync(() -> { Transaction txn = ebeanServer.beginTransaction(); Optional<Integer> value = Optional.empty(); try { Profile targetProfile = ebeanServer.find(Profile.class).setId(clickedId).findOne(); if (targetProfile != null) { List<String> roles = targetProfile.getRoles(); if (targetProfile.hasRole("admin")) { roles.remove("admin"); } else { roles.add("admin"); } targetProfile.setRoles(roles); targetProfile.update(); txn.commit(); value = Optional.of(clickedId); } } finally { txn.end(); } return value; }, executionContext); } /** * returns a list of all users Id's * @return a list of integers of the profile Ids of all the users */ public CompletionStage<Optional<List<Integer>>> getAllUsersId() { return supplyAsync(() -> { String qry = "Select profile_id from profile"; List<SqlRow> rowList = ebeanServer.createSqlQuery(qry).findList(); List<Integer> profileIdList = new ArrayList<>(); for (SqlRow aRowList : rowList) { profileIdList.add(aRowList.getInteger("profile_id")); } return Optional.of(profileIdList); }, executionContext); } /** * Function to get all the destinations created by the signed in user. * * @param profileId users profile Id * @param rowOffset - The row to begin retrieving data from. Used for pagination * @return destList arrayList of destinations registered by the user */ public Optional<ArrayList<Destination>> getDestinations(int profileId, int rowOffset) { String sql = ("SELECT * FROM destination WHERE profile_id = ? AND soft_delete = 0 LIMIT 7 OFFSET ?"); List<SqlRow> rowList = ebeanServer.createSqlQuery(sql).setParameter(1, profileId).setParameter(2, rowOffset).findList(); ArrayList<Destination> destList = new ArrayList<>(); Destination dest; for (SqlRow aRowList : rowList) { dest = new Destination(); dest.setDestinationId(aRowList.getInteger("destination_id")); dest.setProfileId(aRowList.getInteger("profile_id")); dest.setName(aRowList.getString("name")); dest.setType(aRowList.getString("type")); dest.setCountry(aRowList.getString("country")); dest.setDistrict(aRowList.getString("district")); dest.setLatitude(aRowList.getDouble("latitude")); dest.setLongitude(aRowList.getDouble("longitude")); dest.setVisible(aRowList.getBoolean("visible") ? 1 : 0); if ((aRowList.getBoolean("soft_delete") ? 1: 0) == 0) { destList.add(dest); } } return Optional.of(destList); } /** * Function to get ten of the users destinations * * @param profileId users id * @return destination list */ public Optional<List<Destination>> getTenDestinations(int profileId) { return Optional.of(ebeanServer.find(Destination.class).setMaxRows(10).where().eq("profile_id", profileId).eq("soft_delete", 0).findList()); } /** * Finds the number of profiles in the database * Used for pagination purposes * @return int of number found */ public int getNumProfiles() { return ebeanServer.find(Profile.class).where().eq("soft_delete", 0).findCount(); } /** * Method for edit profile-email to check if there is a traveller account under the supplied email that already * exists (not the same user) * * @param email String The new email the user has proposed to change to * @param profileId int of the porfileid of the user * @return boolean true if email is taken, false if it is a change that will be allowed */ public boolean isEmailTaken(String email, int profileId) { boolean isTaken = false; String selectQuery = "Select * from profile WHERE email = ?"; List<SqlRow> rowList = ebeanServer.createSqlQuery(selectQuery).setParameter(1, email).findList(); for (SqlRow aRow : rowList) { if (aRow.getInteger("profile_id") != profileId) { isTaken = true; } } return isTaken; } /** * Method for create profile to check if there is a traveller account under the supplied email that already * exists (not the same user) * * @param email String The email the user has proposed to use * @return boolean true if email is taken, false if it is a change that will be allowed */ public boolean isEmailTakenSignup(String email) { boolean isTaken = false; return ebeanServer.find(Profile.class).where().eq("email", email).exists(); } /** * Gets the number of admins * @return int number of admins */ public int getNumAdmins() { return ebeanServer.find(ProfileRoles.class).setDistinct(true).findCount(); } /** * Method to get a page of profiles to display * * @param offset offset for profiles to find * @param limit number of profiles to find * @return List of found profiles */ public List<Profile> getPage(Integer offset, Integer limit) { String selectQuery = "SELECT * FROM profile WHERE soft_delete = 0 LIMIT ? OFFSET ?;"; List<SqlRow> rows = ebeanServer.createSqlQuery(selectQuery).setParameter(1, limit).setParameter(2, offset).findList(); List<Profile> profiles = new ArrayList<>(); for (SqlRow row : rows) { profiles.add(profileFromRow(row)); } return profiles; } }
41.998643
157
0.60104
42ab629f9d66386f31b90f6b6dbb5a2ce18046d1
11,569
/* --------------------------------------------------------------------------------------------------------------------- * AUTO-GENERATED CLASS - DO NOT EDIT MANUALLY - for any changes edit TestCharSegmentedSortedArray and regenerate * ------------------------------------------------------------------------------------------------------------------ */ package io.deephaven.db.v2.ssa; import io.deephaven.db.tables.Table; import io.deephaven.db.tables.live.LiveTableMonitor; import io.deephaven.db.v2.*; import io.deephaven.db.v2.sources.ColumnSource; import io.deephaven.db.v2.sources.chunk.Attributes; import io.deephaven.db.v2.sources.chunk.Attributes.KeyIndices; import io.deephaven.db.v2.sources.chunk.Attributes.Values; import io.deephaven.db.v2.sources.chunk.DoubleChunk; import io.deephaven.db.v2.sources.chunk.LongChunk; import io.deephaven.db.v2.utils.Index; import io.deephaven.db.v2.utils.IndexShiftData; import io.deephaven.test.types.ParallelTest; import junit.framework.TestCase; import org.junit.experimental.categories.Category; import java.util.Random; import static io.deephaven.db.v2.TstUtils.getTable; import static io.deephaven.db.v2.TstUtils.initColumnInfos; @Category(ParallelTest.class) public class TestDoubleSegmentedSortedArray extends LiveTableTestCase { public void testInsertion() { for (int seed = 0; seed < 10; ++seed) { for (int tableSize = 100; tableSize <= 1000; tableSize *= 10) { for (int nodeSize = 8; nodeSize <= 2048; nodeSize *= 2) { testUpdates(seed, tableSize, nodeSize, true, false); } } } } public void testRemove() { for (int seed = 0; seed < 20; ++seed) { for (int tableSize = 100; tableSize <= 10000; tableSize *= 10) { for (int nodeSize = 16; nodeSize <= 2048; nodeSize *= 2) { testUpdates(seed, tableSize, nodeSize, false, true); } } } } public void testInsertAndRemove() { for (int seed = 0; seed < 10; ++seed) { for (int tableSize = 100; tableSize <= 10000; tableSize *= 10) { for (int nodeSize = 16; nodeSize <= 2048; nodeSize *= 2) { testUpdates(seed, tableSize, nodeSize, true, true); } } } } public void testShifts() { for (int seed = 0; seed < 20; ++seed) { for (int tableSize = 10; tableSize <= 10000; tableSize *= 10) { for (int nodeSize = 16; nodeSize <= 2048; nodeSize *= 2) { testShifts(seed, tableSize, nodeSize); } } } } private void testShifts(final int seed, final int tableSize, final int nodeSize) { final Random random = new Random(seed); final TstUtils.ColumnInfo[] columnInfo; final QueryTable table = getTable(tableSize, random, columnInfo = initColumnInfos(new String[]{"Value"}, SsaTestHelpers.getGeneratorForDouble())); final Table asDouble = SsaTestHelpers.prepareTestTableForDouble(table); final DoubleSegmentedSortedArray ssa = new DoubleSegmentedSortedArray(nodeSize); //noinspection unchecked final ColumnSource<Double> valueSource = asDouble.getColumnSource("Value"); System.out.println("Creation seed=" + seed + ", tableSize=" + tableSize + ", nodeSize=" + nodeSize); checkSsaInitial(asDouble, ssa, valueSource); ((DynamicTable)asDouble).listenForUpdates(new InstrumentedShiftAwareListenerAdapter((DynamicTable) asDouble) { @Override public void onUpdate(Update upstream) { try (final ColumnSource.GetContext checkContext = valueSource.makeGetContext(asDouble.getIndex().getPrevIndex().intSize())) { final Index relevantIndices = asDouble.getIndex().getPrevIndex(); checkSsa(ssa, valueSource.getPrevChunk(checkContext, relevantIndices).asDoubleChunk(), relevantIndices.asKeyIndicesChunk()); } final int size = Math.max(upstream.modified.intSize() + Math.max(upstream.added.intSize(), upstream.removed.intSize()), (int)upstream.shifted.getEffectiveSize()); try (final ColumnSource.GetContext getContext = valueSource.makeGetContext(size)) { ssa.validate(); final Index takeout = upstream.removed.union(upstream.getModifiedPreShift()); if (takeout.nonempty()) { final DoubleChunk<? extends Values> valuesToRemove = valueSource.getPrevChunk(getContext, takeout).asDoubleChunk(); ssa.remove(valuesToRemove, takeout.asKeyIndicesChunk()); } ssa.validate(); try (final ColumnSource.GetContext checkContext = valueSource.makeGetContext(asDouble.getIndex().getPrevIndex().intSize())) { final Index relevantIndices = asDouble.getIndex().getPrevIndex().minus(takeout); checkSsa(ssa, valueSource.getPrevChunk(checkContext, relevantIndices).asDoubleChunk(), relevantIndices.asKeyIndicesChunk()); } if (upstream.shifted.nonempty()) { final IndexShiftData.Iterator sit = upstream.shifted.applyIterator(); while (sit.hasNext()) { sit.next(); final Index indexToShift = table.getIndex().getPrevIndex().subindexByKey(sit.beginRange(), sit.endRange()).minus(upstream.getModifiedPreShift()).minus(upstream.removed); if (indexToShift.empty()) { continue; } final DoubleChunk<? extends Values> shiftValues = valueSource.getPrevChunk(getContext, indexToShift).asDoubleChunk(); if (sit.polarityReversed()) { ssa.applyShiftReverse(shiftValues, indexToShift.asKeyIndicesChunk(), sit.shiftDelta()); } else { ssa.applyShift(shiftValues, indexToShift.asKeyIndicesChunk(), sit.shiftDelta()); } } } ssa.validate(); final Index putin = upstream.added.union(upstream.modified); try (final ColumnSource.GetContext checkContext = valueSource.makeGetContext(asDouble.intSize())) { final Index relevantIndices = asDouble.getIndex().minus(putin); checkSsa(ssa, valueSource.getChunk(checkContext, relevantIndices).asDoubleChunk(), relevantIndices.asKeyIndicesChunk()); } if (putin.nonempty()) { final DoubleChunk<? extends Values> valuesToInsert = valueSource.getChunk(getContext, putin).asDoubleChunk(); ssa.insert(valuesToInsert, putin.asKeyIndicesChunk()); } ssa.validate(); } } }); for (int step = 0; step < 50; ++step) { System.out.println("Seed = " + seed + ", tableSize=" + tableSize + ", nodeSize=" + nodeSize + ", step = " + step); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> GenerateTableUpdates.generateShiftAwareTableUpdates(GenerateTableUpdates.DEFAULT_PROFILE, tableSize, random, table, columnInfo)); try (final ColumnSource.GetContext getContext = valueSource.makeGetContext(asDouble.intSize())) { checkSsa(ssa, valueSource.getChunk(getContext, asDouble.getIndex()).asDoubleChunk(), asDouble.getIndex().asKeyIndicesChunk()); } } } private void testUpdates(final int seed, final int tableSize, final int nodeSize, boolean allowAddition, boolean allowRemoval) { final Random random = new Random(seed); final TstUtils.ColumnInfo[] columnInfo; final QueryTable table = getTable(tableSize, random, columnInfo = initColumnInfos(new String[]{"Value"}, SsaTestHelpers.getGeneratorForDouble())); final Table asDouble = SsaTestHelpers.prepareTestTableForDouble(table); final DoubleSegmentedSortedArray ssa = new DoubleSegmentedSortedArray(nodeSize); //noinspection unchecked final ColumnSource<Double> valueSource = asDouble.getColumnSource("Value"); System.out.println("Creation seed=" + seed + ", tableSize=" + tableSize + ", nodeSize=" + nodeSize); checkSsaInitial(asDouble, ssa, valueSource); ((DynamicTable)asDouble).listenForUpdates(new InstrumentedListenerAdapter((DynamicTable) asDouble) { @Override public void onUpdate(Index added, Index removed, Index modified) { try (final ColumnSource.GetContext getContext = valueSource.makeGetContext(Math.max(added.intSize(), removed.intSize()))) { if (removed.nonempty()) { final DoubleChunk<? extends Values> valuesToRemove = valueSource.getPrevChunk(getContext, removed).asDoubleChunk(); ssa.remove(valuesToRemove, removed.asKeyIndicesChunk()); } if (added.nonempty()) { ssa.insert(valueSource.getChunk(getContext, added).asDoubleChunk(), added.asKeyIndicesChunk()); } } } }); for (int step = 0; step < 50; ++step) { System.out.println("Seed = " + seed + ", tableSize=" + tableSize + ", nodeSize=" + nodeSize + ", step = " + step); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { final Index [] notify = GenerateTableUpdates.computeTableUpdates(tableSize, random, table, columnInfo, allowAddition, allowRemoval, false); assertTrue(notify[2].empty()); table.notifyListeners(notify[0], notify[1], notify[2]); }); try (final ColumnSource.GetContext getContext = valueSource.makeGetContext(asDouble.intSize())) { checkSsa(ssa, valueSource.getChunk(getContext, asDouble.getIndex()).asDoubleChunk(), asDouble.getIndex().asKeyIndicesChunk()); } if (!allowAddition && table.size() == 0) { System.out.println("All values removed."); break; } } } private void checkSsaInitial(Table asDouble, DoubleSegmentedSortedArray ssa, ColumnSource<?> valueSource) { try (final ColumnSource.GetContext getContext = valueSource.makeGetContext(asDouble.intSize())) { final DoubleChunk<? extends Values> valueChunk = valueSource.getChunk(getContext, asDouble.getIndex()).asDoubleChunk(); final LongChunk<Attributes.OrderedKeyIndices> tableIndexChunk = asDouble.getIndex().asKeyIndicesChunk(); ssa.insert(valueChunk, tableIndexChunk); checkSsa(ssa, valueChunk, tableIndexChunk); } } private void checkSsa(DoubleSegmentedSortedArray ssa, DoubleChunk<? extends Values> valueChunk, LongChunk<? extends KeyIndices> tableIndexChunk) { ssa.validate(); try { DoubleSsaChecker.checkSsa(ssa, valueChunk, tableIndexChunk); } catch (SsaChecker.SsaCheckException e) { TestCase.fail(e.getMessage()); } } }
50.3
197
0.59936
48fa73d4bd991e18219bd45e02c2db24b4463c78
727
package com.dd.news; import com.dd.framework.base.BaseApp; import com.dd.framework.base.CustomFragment; import com.dd.framework.services.ServiceManager; import com.dd.framework.widgets.BottomView; import com.dd.framework.widgets.CommonTopView; import com.dd.framework.widgets.EmptyView; import com.dd.framework.widgets.LoadingView; import com.dd.framework.widgets.TopView; import com.dd.framework.widgets.UIViewFactory; import com.dd.framework.widgets.ViewBuilder; import com.dd.news.services.AppServiceManager; /** * Created by J.Tommy on 17/2/10. */ public class App extends BaseApp { @Override public void initApp() { } @Override public ServiceManager configServerManager() { return new AppServiceManager(); } }
26.925926
48
0.795048
cf2d1064defcb5cc6c39355fa6889ad195bd9293
748
package io.github.kuyer.rpc.codec; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; /** * Netty解码器 * @author Rory.Zhang */ public class NettyRpcDecode extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if(in.readableBytes() < 0) { return; } in.markReaderIndex(); int dataLength = in.readInt(); if(dataLength < 0) { ctx.close(); } if(in.readableBytes() < dataLength) { in.resetReaderIndex(); } byte[] bytes = new byte[dataLength]; in.readBytes(bytes); Object obj = BaseCodec.decode(bytes); out.add(obj); } }
20.216216
61
0.708556
16aa0c9252c168ebef234e0556e30f3f2c682c55
1,321
/* * Copyright (C) 2017 Sylvain Leroy - BYOSkill Company All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license, which unfortunately won't be * written for another century. * * You should have received a copy of the MIT license with * this file. If not, please write to: sleroy at byoskill.com, or visit : www.byoskill.com * */ package com.byoskill.spring.cqrs.api; import java.util.concurrent.ForkJoinPool; /** * The Interface CqrsConfiguration defines the configuration required to boot * the module. */ public interface CqrsConfiguration { /** * Provides a fork join pool to allow async executions for the commands. * * @return the fork join pool for async execution */ ForkJoinPool getForkJoinPool(); /** * Gets the logging configuration. * * @return the logging configuration */ LoggingConfiguration getLoggingConfiguration(); /** * Returns a throttling interface. The default behaviour is simply ignoring the * throttling. * * @return the i throttling interface */ ThrottlingInterface getThrottlingInterface(); /** * Gets the trace configuration. * * @return the trace configuration */ TraceConfiguration getTraceConfiguration(); }
26.959184
90
0.690386
68f3abd6c2a63b4433ca7f4b99cf4120b94f0fd4
12,111
/* * Copyright 2019 Miroslav Pokorny (github.com/mP1) * * 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 walkingkooka.spreadsheet.parser; import org.junit.jupiter.api.Test; import walkingkooka.collect.list.Lists; import walkingkooka.text.cursor.parser.ParserToken; import walkingkooka.tree.expression.Expression; import walkingkooka.tree.expression.ExpressionEvaluationContext; import walkingkooka.tree.expression.ExpressionNumber; import walkingkooka.tree.expression.ExpressionNumberKind; import walkingkooka.tree.expression.FakeExpressionEvaluationContext; import walkingkooka.tree.json.JsonNode; import walkingkooka.tree.json.marshall.JsonNodeUnmarshallContext; import java.math.MathContext; import java.time.LocalDate; import java.util.List; import static org.junit.jupiter.api.Assertions.assertThrows; public final class SpreadsheetNumberParserTokenTest extends SpreadsheetParentParserTokenTestCase<SpreadsheetNumberParserToken> { @Test public void testWithZeroTokensFails() { this.createToken("1/2/2003"); } @Test public void testNumberNullContextFails() { assertThrows(NullPointerException.class, () -> this.createToken().toNumber(null)); } @Test public void testToExpressionNumber0() { this.toExpressionAndCheck2( 0.0, digit("0") ); } @Test public void testToExpressionNumber01() { this.toExpressionAndCheck2( 1.0, digit("01") ); } @Test public void testToExpressionNumber001() { this.toExpressionAndCheck2( 1.0, digit("001") ); } @Test public void testToExpressionNumber1() { this.toExpressionAndCheck2( 1.0, digit("1") ); } @Test public void testToExpressionNumber5600() { this.toExpressionAndCheck2( 5600.0, digit("5600") ); } @Test public void testToExpressionNumber123() { this.toExpressionAndCheck2( 123.0, digit("123") ); } @Test public void testToExpressionPlusNumber1() { this.toExpressionAndCheck2( 1.0, plus(), digit("1") ); } @Test public void testToExpressionNumber0Dot0() { this.toExpressionAndCheck2( 0.0, plus(), digit("0"), decimalSeparator(), digit("0") ); } @Test public void testToExpressionPlusNumber1Dot0() { this.toExpressionAndCheck2( 1.0, plus(), digit("1"), decimalSeparator(), digit("0") ); } @Test public void testToExpressionPlusNumber1Dot23() { this.toExpressionAndCheck2( 1.23, plus(), digit("1"), decimalSeparator(), digit("23") ); } @Test public void testToExpressionMinusNumber1() { this.toExpressionAndCheck2( -1.0, minus(), digit("1") ); } @Test public void testToExpressionMinusNumber1Dot0() { this.toExpressionAndCheck2( -1.0, minus(), digit("1"), decimalSeparator(), digit("0") ); } @Test public void testToExpressionMinusNumber1Dot23() { this.toExpressionAndCheck2( -1.23, minus(), digit("1"), decimalSeparator(), digit("23") ); } @Test public void testToExpressionNumber1ExponentNumber1() { this.toExpressionAndCheck2( 1E2, digit("1"), exponent(), digit("2") ); } @Test public void testToExpressionNumber1ExponentNumber12() { this.toExpressionAndCheck2( 1E12, digit("1"), exponent(), digit("12") ); } @Test public void testToExpressionNumber1DecimalNumber2ExponentPlusNumber3() { this.toExpressionAndCheck2( 1.2E+3, digit("1"), decimalSeparator(), digit("2"), exponent(), plus(), digit("3") ); } @Test public void testToExpressionNumber1DecimalNumber2ExponentPlusNumber34() { this.toExpressionAndCheck2( 1.2E+34, digit("1"), decimalSeparator(), digit("2"), exponent(), plus(), digit("34") ); } @Test public void testToExpressionNumber1DecimalNumber2ExponentMinusNumber3() { this.toExpressionAndCheck2( 1.2E-3, digit("1"), decimalSeparator(), digit("2"), exponent(), minus(), digit("3") ); } @Test public void testToExpressionNumber1DecimalNumber2ExponentMinusNumber34() { this.toExpressionAndCheck2( 1.2E-34, digit("1"), decimalSeparator(), digit("2"), exponent(), minus(), digit("34") ); } @Test public void testToExpressionNumber1ExponentPlusNumber1() { this.toExpressionAndCheck2( 1E+2, digit("1"), exponent(), plus(), digit("2") ); } @Test public void testToExpressionNumber1ExponentPlusNumber12() { this.toExpressionAndCheck2( 1E+12, digit("1"), exponent(), plus(), digit("12") ); } @Test public void testToExpressionNumber1ExponentMinusNumber1() { this.toExpressionAndCheck2( 1E-2, digit("1"), exponent(), minus(), digit("2") ); } @Test public void testToExpressionNumber1ExponentMinusNumber23() { this.toExpressionAndCheck2( 1E-23, digit("1"), exponent(), minus(), digit("23") ); } @Test public void testToExpressionNumber0Percent() { this.toExpressionAndCheck2( 0.0, digit("0"), percent() ); } @Test public void testToExpressionNumber50Percent() { this.toExpressionAndCheck2( 0.5, digit("50"), percent() ); } @Test public void testToExpressionNumber200Percent() { this.toExpressionAndCheck2( 2.0, digit("200"), percent() ); } @Test public void testToExpressionNumberPercent300() { this.toExpressionAndCheck2( 3.0, digit("300"), percent() ); } @Test public void testToExpressionNumberMinusPercent400() { this.toExpressionAndCheck2( -4.0, minus(), digit("400"), percent() ); } private static SpreadsheetDigitsParserToken digit(final String text) { return SpreadsheetDigitsParserToken.digits(text, text); } private static SpreadsheetExponentSymbolParserToken exponent() { return SpreadsheetDigitsParserToken.exponentSymbol("E", "E"); } private static SpreadsheetMinusSymbolParserToken minus() { return SpreadsheetDigitsParserToken.minusSymbol("-", "-"); } private static SpreadsheetPercentSymbolParserToken percent() { return SpreadsheetDigitsParserToken.percentSymbol("%", "%"); } private static SpreadsheetPlusSymbolParserToken plus() { return SpreadsheetDigitsParserToken.plusSymbol("+", "+"); } private void toExpressionAndCheck2(final Double expected, final SpreadsheetParserToken... tokens) { final List<ParserToken> tokensList = Lists.of(tokens); final SpreadsheetNumberParserToken numberParserToken = SpreadsheetNumberParserToken.with( tokensList, ParserToken.text(tokensList) ); this.toExpressionAndCheck2( numberParserToken, ExpressionNumberKind.BIG_DECIMAL, expected ); this.toExpressionAndCheck2( numberParserToken, ExpressionNumberKind.DOUBLE, expected ); } private void toExpressionAndCheck2(final SpreadsheetNumberParserToken token, final ExpressionNumberKind kind, final Double expected) { final ExpressionNumber expressionNumber = kind.create(expected); final ExpressionEvaluationContext context = this.expressionEvaluationContext(kind); this.checkEquals( expressionNumber, token.toNumber(context), () -> "toNumber() " + token ); this.toExpressionAndCheck( token, context, Expression.expressionNumber(expressionNumber) ); } private ExpressionEvaluationContext expressionEvaluationContext(final ExpressionNumberKind kind) { return new FakeExpressionEvaluationContext() { @Override public MathContext mathContext() { return MathContext.DECIMAL32; } @Override public ExpressionNumberKind expressionNumberKind() { return kind; } }; } @Override SpreadsheetNumberParserToken createToken(final String text, final List<ParserToken> tokens) { return SpreadsheetParserToken.number(tokens, text); } @Override public String text() { return "" + DAY + "/" + MONTH + "/" + YEAR; } @Override List<ParserToken> tokens() { return Lists.of( this.dayNumber(), this.slashTextLiteral(), this.monthNumber(), this.slashTextLiteral(), this.year() ); } private LocalDate date() { return LocalDate.of(YEAR, MONTH, DAY); } @Override public SpreadsheetNumberParserToken createDifferentToken() { final String different = "" + YEAR + "/" + MONTH + "/" + DAY; return this.createToken( different, year(), slashTextLiteral(), monthNumber(), slashTextLiteral(), dayNumber() ); } @Override public Class<SpreadsheetNumberParserToken> type() { return SpreadsheetNumberParserToken.class; } @Override public SpreadsheetNumberParserToken unmarshall(final JsonNode from, final JsonNodeUnmarshallContext context) { return SpreadsheetParserToken.unmarshallNumber(from, context); } }
26.501094
128
0.535381
439e87725b0b38e23f83f652e52a4b4785f72e6c
2,920
package waffleoRai_schedulebot; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import waffleoRai_Utils.FileBuffer.UnsupportedFileTypeException; public class MonthlyDOMEvent extends EventAdapter { //public static ReminderTime[] reminderTimes; public static final int MAX_REMINDERS = 4; public MonthlyDOMEvent(String tsvRecord) throws UnsupportedFileTypeException { super.readFromTSV_record(tsvRecord); } public MonthlyDOMEvent(long reqUser) { super.setRequestTime(); super.instantiateStructures(); super.setRequestingUser(reqUser); super.setEventID(); } private MonthlyDOMEvent(MonthlyDOMEvent prequel) { super.makeSequelBase(prequel, 1, 0); } @Override public EventType getType() { return EventType.MONTHLYA; } public CalendarEvent spawnSequel() { MonthlyDOMEvent seq = new MonthlyDOMEvent(this); return seq; } public static ReminderTime getStaticReminderTime(int level) { /*if (reminderTimes == null) reminderTimes = new ReminderTime[CalendarEvent.STD_REMINDER_COUNT]; if (level < 1) return null; if (level > STD_REMINDER_COUNT) return null; return reminderTimes[level-1];*/ return Schedule.getReminderTime(EventType.MONTHLYA, level); } public void loadReminderTimes() { for (int i = 1; i <= CalendarEvent.STD_REMINDER_COUNT; i++) { super.setReminderTime(i, getStaticReminderTime(i)); } } public int getMaxReminders() { return MAX_REMINDERS; } public boolean acceptsRSVP() { return true; } public boolean isRecurring() { return true; } public void setName(String ename) { super.setEventName(ename); } public void setReqChannel(long chid) { super.setRequesterChannel(chid); } public void setTargChannel(long chid) { super.setTargetChannel(chid); } public void setEventTime(int dayOfMonth, int hour, int minute, TimeZone tz) { GregorianCalendar now = new GregorianCalendar(); now.setTimeZone(tz); GregorianCalendar next = new GregorianCalendar(); next.setTimeZone(tz); next.set(Calendar.HOUR_OF_DAY, hour); next.set(Calendar.MINUTE, minute); int nowday = now.get(Calendar.DAY_OF_MONTH); if (nowday == dayOfMonth) { //See if it's before or after. int nowhr = now.get(Calendar.HOUR_OF_DAY); if (hour == nowhr) { int nowmin = now.get(Calendar.MINUTE); if (minute >= nowmin) { //Add seven days next.add(Calendar.MONTH, 1); } } else if (hour > nowhr) { //Add seven days next.add(Calendar.MONTH, 1); } } else { if (nowday > dayOfMonth) { //Add a month next.add(Calendar.MONTH, 1); } //Set the day directly next.set(Calendar.DAY_OF_MONTH, dayOfMonth); } super.setEventTime(next); determineNextReminder(); } }
21.62963
99
0.677055
06eb6b65474b815d7e50a463895192f31235cf26
8,948
package com.svs.finance.controller; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.svs.finance.bean.LoginBean; import com.svs.finance.helper.C_FinanceHelperController; import com.svs.finance.service.IN_LoginService; import com.svs.finance.util.AppLogger; import com.svs.finance.util.ConvertStackTracetoString; @Controller public class C_LoginController { @Autowired IN_LoginService in_loginservice; @Autowired C_FinanceHelperController hlp_fin; @Autowired ConvertStackTracetoString util_stos; @Value("${login.error1}") String loginerror; @Value("${resort.success}") String successmsg; @Value("${resort.update}") String updatesuccess; private boolean insertorupdate = false; private HashMap logindetails = new HashMap(); final static Logger logger = Logger.getLogger(C_LoginController.class); @RequestMapping(value = "login.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String loginPage(ModelMap model) { AppLogger.debug("::Login Page:::"); model.addAttribute(new LoginBean()); return "login"; } @RequestMapping(value = "loginstatus.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String loginForward(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request) { String loginforward = null; /*System.out.println("UserName\t"+username); System.out.println("Password\t"+password);*/ String company = null; if (username.equals("admin") && (password.equals("admin"))) { request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); AppLogger.debug("::loginForward:::"); loginforward = "admin_main"; } else if ((username.equals("fn_svs")) && (password.equals("fn_svs"))) { request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); loginforward = "executive_main"; } else if ((username.equals(" ")) && (password.equals(" "))) { request.getSession().setAttribute("loginerror", loginerror); loginforward = "login"; } return loginforward; } @RequestMapping(value = "loginCheckup.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String checkLogin(@ModelAttribute LoginBean loginbean, HttpServletRequest request) { String username = loginbean.getUsername(); String password = loginbean.getPassword(); String status = null; String companyname1 = null; String designation = null; JSONObject logindetails = new JSONObject(); //System.out.println("Username\t"+username); //System.out.println("Password\t"+password); insertorupdate = in_loginservice.loginCheckup(username, password);//Login Controller for Login Check up. AppLogger.info("::checkLogin Login Page:::"); if (insertorupdate) { //logindetails=hlp_fin.gettingLoginDetails(username, password); List<LoginBean> list1 = in_loginservice.getLoginDetails(username, password); companyname1 = list1.get(0).getCompanyname(); designation = list1.get(0).getDesignation(); //designation=logindetails.getString("designation"); // System.out.println("Company Name\t" + companyname1 + "\t" + designation); AppLogger.debug("Login Credentials::: Company Name" + companyname1 + " designation is::" + designation); if (designation.equals("Admin")) { AppLogger.debug("User ID:\t" + username + "Comapany Name:" + companyname1 + "Login Status:\t Successful"); request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); request.getSession().setAttribute("compname", companyname1); //System.out.println("Login Error"+loginerror); status = "admin_main"; } else if (designation.equals("Employee")) { AppLogger.debug("User ID:\t" + username + "Comapany Name:" + companyname1 + "Login Status:\t Successful"); request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); request.getSession().setAttribute("compname", companyname1); status = "executive_main"; } else if ((username.equals("")) && (password.equals(""))) { AppLogger.debug("User ID:\t" + username + "Comapany Name:" + companyname1 + "Login Status:\t Failed"); request.getSession().setAttribute("loginerror", loginerror); status = "login"; } } else { request.getSession().setAttribute("loginerror", loginerror); status = "login"; } return status; } @RequestMapping(value = "logout.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String logOff(ModelMap model) { AppLogger.debug("::LogOut Successfully:::"); return "logout"; } //Change Password. @RequestMapping(value = "admin_change_password.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String changePassword(ModelMap model) { AppLogger.debug("::Change Password:::"); model.addAttribute(new LoginBean()); return "fn_admin_change_password"; } @RequestMapping(value = "fn_changed_password.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String changingPassword(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); String password = request.getParameter("password"); String newpassword = request.getParameter("newpassword"); String comp = request.getParameter("login_comp"); // System.out.println(username); // System.out.println(password); // System.out.println(comp); insertorupdate = in_loginservice.updatePassword(username, newpassword, comp); if (insertorupdate) { AppLogger.debug("::Password Changed Successfully::"); request.getSession().setAttribute("updatesuccess", updatesuccess); } else { AppLogger.debug("::Unable to Change Password::"); } return "redirect:admin_change_password.fin"; } @RequestMapping(value = "user_change_password.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String changeUserPassword(ModelMap model) { AppLogger.debug("::Changing user password::"); model.addAttribute(new LoginBean()); return "fn_user_change_password"; } @RequestMapping(value = "fn_user_changed_password.fin", method = {RequestMethod.GET, RequestMethod.POST}) public String changingUserPassword(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); String password = request.getParameter("password"); String newpassword = request.getParameter("newpassword"); String comp = request.getParameter("login_comp"); System.out.println(username); System.out.println(password); System.out.println(comp); AppLogger.debug("::Changing user password:::"); insertorupdate = in_loginservice.updatePassword(username, newpassword, comp); if (insertorupdate) { AppLogger.debug("::User Password Successfully::"); request.getSession().setAttribute("updatesuccess", updatesuccess); } else { AppLogger.debug("Unable to change user password"); } return "redirect:user_change_password.fin"; } @RequestMapping(value="companyRegistration.fin",method= {RequestMethod.GET,RequestMethod.POST}) public String registerCompany(HttpServletRequest request,HttpServletResponse resp) { return "hr_companyRegistration"; } }
45.42132
146
0.658471
469e3fac725eede07e71e3eb0dc27e8d8de37d9e
1,687
/** * Unlicensed code created by A Softer Space, 2020 * www.asofterspace.com/licenses/unlicense.txt */ package com.asofterspace.boardGamePlayer.games; import com.asofterspace.toolbox.utils.Record; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class Player { // the player's id private int id; // a unique token that maps to a particular player playing a particular game private String token; // the self-given name of the player private String name; // the messages that are waiting for this player to consume private List<Record> msgs; public Player(int id, String name) { this.id = id; this.name = name; this.token = "" + UUID.randomUUID(); this.msgs = new ArrayList<>(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getToken() { return token; } public String getName() { return name; } public void setName(String name) { this.name = name; } public synchronized void addMsg(Record msg) { this.msgs.add(msg); } public synchronized Record flushMsgs() { List<Record> result = this.msgs; this.msgs = new ArrayList<>(); return Record.fromAnything(result); } public void awaitNothingOngoing() { while (this.msgs.size() > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { // whoops } } } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other instanceof Player) { Player otherPlayer = (Player) other; if (this.id == otherPlayer.id) { return true; } } return false; } @Override public int hashCode() { return this.id; } }
17.572917
77
0.671606
06775283a84135d09ebccaece0e6a33870d9268e
4,310
/* * Copyright 2018-2022 adorsys GmbH & Co KG * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. This program is distributed in the hope that * it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. * * This project is also available under a separate commercial license. You can * contact us at [email protected]. */ package de.adorsys.xs2a.adapter.sparda; import com.google.common.collect.Maps; import de.adorsys.xs2a.adapter.api.*; import de.adorsys.xs2a.adapter.api.http.HttpClient; import de.adorsys.xs2a.adapter.api.http.HttpClientConfig; import de.adorsys.xs2a.adapter.api.http.HttpClientFactory; import de.adorsys.xs2a.adapter.api.http.Request; import de.adorsys.xs2a.adapter.api.link.LinksRewriter; import de.adorsys.xs2a.adapter.api.model.Aspsp; import de.adorsys.xs2a.adapter.api.model.PaymentInitationRequestResponse201; import de.adorsys.xs2a.adapter.api.model.PaymentInitiationJson; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashMap; import java.util.Map; import static de.adorsys.xs2a.adapter.api.model.PaymentProduct.SEPA_CREDIT_TRANSFERS; import static de.adorsys.xs2a.adapter.api.model.PaymentService.PAYMENTS; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class SpardaPaymentInitiationServiceTest { private static final String PSU_ID = "psuId"; private PaymentInitiationService paymentInitiationService; @Mock private HttpClientFactory httpClientFactory; @Mock private HttpClientConfig httpClientConfig; @Mock private HttpClient httpClient; @Mock private LinksRewriter linksRewriter; @Mock private SpardaJwtService spardaJwtService; @Captor private ArgumentCaptor<Map<String, String>> headersCaptor; private final Aspsp aspsp = getAspsp(); @BeforeEach void setUp() { when(httpClientFactory.getHttpClient(any())).thenReturn(httpClient); when(httpClientFactory.getHttpClientConfig()).thenReturn(httpClientConfig); paymentInitiationService = new SpardaPaymentInitiationService(aspsp, httpClientFactory, linksRewriter, spardaJwtService); } @Test void initiatePayment() { Request.Builder requestBuilder = mock(Request.Builder.class); when(httpClient.post(any())).thenReturn(requestBuilder); when(requestBuilder.headers(anyMap())).thenReturn(requestBuilder); when(requestBuilder.send(any(), anyList())) .thenReturn(new Response<>(-1, new PaymentInitationRequestResponse201(), ResponseHeaders.emptyResponseHeaders())); when(spardaJwtService.getPsuId(any())).thenReturn(PSU_ID); paymentInitiationService.initiatePayment(PAYMENTS, SEPA_CREDIT_TRANSFERS, getAuthRequestHeaders(), RequestParams.empty(), new PaymentInitiationJson()); verify(requestBuilder, times(1)).headers(headersCaptor.capture()); Map<String, String> actualHeaders = headersCaptor.getValue(); assertThat(actualHeaders) .hasSize(2) .contains(Maps.immutableEntry(RequestHeaders.PSU_ID, PSU_ID)); } private RequestHeaders getAuthRequestHeaders() { Map<String, String> headers = new HashMap<>(); headers.put(RequestHeaders.AUTHORIZATION, "Bearer token"); return RequestHeaders.fromMap(headers); } private Aspsp getAspsp() { Aspsp aspsp = new Aspsp(); aspsp.setIdpUrl("https://foo.boo"); return aspsp; } }
37.478261
129
0.745012
1b2cffc829abc6685d12cc7430b32c537ca724a5
656
package com.github.acme.quarkus.petclinic.api; import com.github.acme.quarkus.petclinic.model.Vet; import com.github.acme.quarkus.petclinic.repository.VetRepository; import java.util.List; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/vets") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class VetResource { @Inject VetRepository vetRepository; @GET public List<Vet> list() { return vetRepository.listAllVets(); } @GET @Path("/by-name/{name}") public Vet findByName(@PathParam("name") String name) { return vetRepository.findByName(name); } }
23.428571
66
0.753049
cdae5da67b8dc1427fa3849ac0e2c82e41e07c34
36
package g.o; class k extends j { }
7.2
19
0.638889
fcfce38a8c73b4e90d25bac255371a0124f8127d
13,031
package com.smeanox.games.ld35.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture.TextureWrap; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer; import com.smeanox.games.ld35.Consts; import com.smeanox.games.ld35.Font; import com.smeanox.games.ld35.LD35; import com.smeanox.games.ld35.Sounds; import com.smeanox.games.ld35.io.LevelReader; import com.smeanox.games.ld35.io.Textures; import com.smeanox.games.ld35.world.GameWorld; import com.smeanox.games.ld35.world.HeroForm; import com.smeanox.games.ld35.world.narrator.Narrator; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class GameScreen implements Screen { private LD35 game; private Narrator narrator; private GameWorld gameWorld; private SpriteBatch spriteBatch; private Box2DDebugRenderer debugRenderer; private OrthographicCamera camera; private List<Renderable> renderables; private ShaderProgram waterShader; private float cameraX; private TextureRegion overlayRegion; private String loadedLevel; private float jumpFreezeTime; private float waveTime; public GameScreen(LD35 game) { this.game = game; narrator = new Narrator(); spriteBatch = new SpriteBatch(); camera = new OrthographicCamera(Consts.WIDTH, Consts.HEIGHT); camera.update(); spriteBatch.setProjectionMatrix(camera.combined); waterShader = new ShaderProgram( "attribute vec4 a_position;\n" + "attribute vec2 a_texCoord0;\n" + "uniform mat4 u_projTrans;\n" + "varying vec2 v_texCoord;\n" + "void main() {\n" + " v_texCoord = a_texCoord0;\n" + " gl_Position = u_projTrans * a_position;\n" + "}\n", "#ifdef GL_ES\n"+ " precision mediump float;\n"+ "#endif\n"+ "varying vec2 v_texCoord;\n"+ "uniform sampler2D u_texture;\n"+ "uniform sampler2D u_texture2;\n"+ "uniform float u_mult;\n"+ "uniform vec2 u_offset;\n"+ "uniform float u_time;\n"+ "vec4 text2D(sampler2D t, vec2 tc) {\n"+ " vec4 col = texture2D(t,tc);\n"+ " return col.a > 0.5 ? col : vec4(0.388, 0.607, 1.0, 1.0);\n"+ " }\n"+ "vec4 gaussSamp(sampler2D t, vec2 tc, vec2 d) {\n"+ " return 0.4*text2D(t,tc)+0.24*text2D(t,tc+d)+0.24*text2D(t,tc-d)+0.06*text2D(t,tc-d-d)+0.06*text2D(t,tc+d+d);\n"+ "}\n"+ "void main() {\n"+ " vec4 col = texture2D(u_texture, v_texCoord);\n"+ " if (distance(col.rgb, vec3(1.0, 0.0, 1.0)) < 0.1){\n"+ " float z = 1.0/v_texCoord.y;\n"+ " vec2 tc = vec2(v_texCoord.x+0.007*cos(70.0*v_texCoord.x ), 1.0-1.3*v_texCoord.y+0.005*sin(300.0*z + u_time));\n"+ " gl_FragColor = gaussSamp(u_texture2, tc + u_offset, vec2(1.0/256.0, 0.0));\n"+ " gl_FragColor.xyz *= 0.8;\n"+ " } else {\n"+ " gl_FragColor = col;\n"+ " }\n"+ "}\n" ); Textures.bg1.get().setWrap(TextureWrap.Repeat, TextureWrap.ClampToEdge); Textures.sky.get().setWrap(TextureWrap.Repeat, TextureWrap.ClampToEdge); System.out.println(waterShader.getLog()); ShaderProgram.pedantic = false; debugRenderer = new Box2DDebugRenderer(); overlayRegion = new TextureRegion(Textures.spritesheet.get(), 3*32, 7*32, 32, 32); loadGameWorld(narrator.getCurrentFile()); } private boolean loadGameWorld(String file) { try { gameWorld = LevelReader.readLevel(Gdx.files.internal(file)); } catch (IOException e) { e.printStackTrace(); Gdx.app.exit(); return false; } loadedLevel = file; cameraX = gameWorld.getCameraInfo().getStartX(); camera.position.x = gameWorld.getCameraInfo().getStartX(); camera.update(); addGameWorldObjectsToRenderables(); narrator.loadedLevel(file); return true; } private void addGameWorldObjectsToRenderables() { renderables = new ArrayList<Renderable>(); addGameWorldObjectsToRenderables(gameWorld.getWaters()); addGameWorldObjectsToRenderables(gameWorld.getButtons()); addGameWorldObjectsToRenderables(gameWorld.getPlatforms()); addGameWorldObjectsToRenderables(gameWorld.getLadders()); addGameWorldObjectsToRenderables(gameWorld.getActors()); addGameWorldObjectsToRenderables(gameWorld.getTexts()); addGameWorldObjectsToRenderables(gameWorld.getDecos()); renderables.add(gameWorld.getHero()); } private void addGameWorldObjectsToRenderables(List<? extends Renderable> list){ for (Renderable renderable : list) { renderables.add(renderable); } } @Override public void show() { } @Override public void render(float delta) { game.getMusicManager().update(delta); updateInput(delta); update(delta); renderWorld(delta); } private void updateInput(float delta) { if(Gdx.input.isKeyJustPressed(Consts.KEY_SKIP)){ narrator.skip(gameWorld); } if(Gdx.input.isKeyJustPressed(Consts.KEY_BACK_TO_MENU)){ game.showMenuScreen(); return; } if(narrator.isHeroFrozen()){ return; } if (Gdx.input.isKeyJustPressed(Consts.KEY_RESTART)) { loadGameWorld(loadedLevel); } if(gameWorld.isGameLost()){ return; } jumpFreezeTime -= delta; if (Gdx.input.isKeyJustPressed(Consts.KEY_HUMAN)) { gameWorld.getHero().setCurrentForm(HeroForm.human); } if (Gdx.input.isKeyJustPressed(Consts.KEY_TURTLE)) { gameWorld.getHero().setCurrentForm(HeroForm.turtle); } if (Gdx.input.isKeyJustPressed(Consts.KEY_WOLF)) { gameWorld.getHero().setCurrentForm(HeroForm.wolf); } Body body = gameWorld.getHero().getBody(); float impulseX = gameWorld.getHero().getCurrentForm().getImpulseX(); if(!gameWorld.getHero().isOnGround()){ impulseX *= Consts.HERO_IMPULSE_AIR_MODIFIER; } float maxVeloX = gameWorld.getHero().getCurrentForm().getMaxVelo(); if (gameWorld.getHero().isInWater()) { maxVeloX = Consts.HERO_WATER_MAX_VELO_X; } if(!gameWorld.getHero().isTurtleActive()) { if(!gameWorld.getHero().isOnWallLeft()) { if (Gdx.input.isKeyPressed(Consts.KEY_LEFT)) { if (body.getLinearVelocity().x > -maxVeloX) { body.applyLinearImpulse(new Vector2(-impulseX, 0), body.getWorldCenter(), true); } } } if(!gameWorld.getHero().isOnWallRight()){ if (Gdx.input.isKeyPressed(Consts.KEY_RIGHT)) { if (body.getLinearVelocity().x < maxVeloX) { body.applyLinearImpulse(new Vector2(impulseX, 0), body.getWorldCenter(), true); } } } if (Gdx.input.isKeyPressed(Consts.KEY_JUMP)) { if (gameWorld.getHero().isOnGround() && jumpFreezeTime < 0) { body.applyLinearImpulse(new Vector2(0, gameWorld.getHero().getCurrentForm().getImpulseY()), body.getWorldCenter(), true); jumpFreezeTime = Consts.HERO_JUMP_FREEZE_TIME; } } } if(!gameWorld.getHero().isOnGround() && gameWorld.getHero().isOnLadder() && gameWorld.getHero().getCurrentForm() == HeroForm.human) { if (Gdx.input.isKeyPressed(Consts.KEY_UP)) { if (body.getLinearVelocity().y < Consts.HERO_LADDER_MAX_VELO_Y) { body.applyLinearImpulse(new Vector2(0, Consts.HERO_LADDER_IMPULSE_Y), body.getWorldCenter(), true); body.applyForceToCenter(-body.getLinearVelocity().x * Consts.HERO_DAMPING_X_COEF_LADDER, 0, true); } } } if(gameWorld.getHero().isInWater() && !gameWorld.getHero().isTurtleActive()){ if(Gdx.input.isKeyPressed(Consts.KEY_UP)) { if (body.getLinearVelocity().y < Consts.HERO_WATER_MAX_VELO_Y) { body.applyLinearImpulse(new Vector2(0, Consts.HERO_WATER_IMPULSE_Y), body.getWorldCenter(), true); } } if(Gdx.input.isKeyPressed(Consts.KEY_DOWN)){ if (body.getLinearVelocity().y > -Consts.HERO_WATER_MAX_VELO_Y) { body.applyLinearImpulse(new Vector2(0, -Consts.HERO_WATER_IMPULSE_Y), body.getWorldCenter(), true); } } } if(!Gdx.input.isKeyPressed(Consts.KEY_LEFT) && !Gdx.input.isKeyPressed(Consts.KEY_RIGHT) && (gameWorld.getHero().isOnGround() || gameWorld.getHero().isOnLadder() || gameWorld.getHero().isInWater())){ body.applyForceToCenter(-body.getLinearVelocity().x * Consts.HERO_DAMPING_X_COEF, 0, true); } if(Gdx.input.isKeyJustPressed(Consts.KEY_INTERACT)) { if (gameWorld.getHero().getLastButton() != null && gameWorld.getHero().getCurrentForm() == HeroForm.human) { Sounds.BUTTON.play(); gameWorld.getHero().getLastButton().interact(gameWorld); } if(gameWorld.getHero().getCurrentForm() == HeroForm.turtle){ gameWorld.getHero().toggleTurtleActive(); } } } private void update(float delta) { gameWorld.update(delta); narrator.update(delta, gameWorld); if(narrator.isRollCredits()){ game.showCreditsScreen(); } else if(narrator.isNeedLevelReload()) { loadGameWorld(narrator.getCurrentFile()); } } private void renderWorld(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); if (gameWorld.getHero().getBody().getPosition().x > cameraX + Consts.WIDTH / 2 - Consts.CAMERA_BORDER) { cameraX = gameWorld.getHero().getBody().getPosition().x - Consts.WIDTH / 2 + Consts.CAMERA_BORDER; cameraX = Math.min(gameWorld.getCameraInfo().getMaxX(), cameraX); camera.position.x = cameraX; camera.update(); } if (gameWorld.getHero().getBody().getPosition().x < cameraX - Consts.WIDTH / 2 + Consts.CAMERA_BORDER) { cameraX = gameWorld.getHero().getBody().getPosition().x + Consts.WIDTH / 2 - Consts.CAMERA_BORDER; cameraX = Math.max(gameWorld.getCameraInfo().getMinX(), cameraX); camera.position.x = cameraX; camera.update(); } spriteBatch.setProjectionMatrix(camera.combined); spriteBatch.begin(); // sky float width = Consts.HEIGHT* Textures.sky.get().getWidth() / ((float) Textures.sky.get().getHeight()); for (int i = -10; i < 11; i++) { spriteBatch.draw(Textures.sky.get(), -width / 2 + i * width + camera.position.x, -Consts.HEIGHT / 2, width, Consts.HEIGHT); } // bg1 width = Consts.HEIGHT * Consts.BG1_HEIGHT_PART * Textures.bg1.get().getWidth() / ((float) Textures.bg1.get().getHeight()); float off = camera.position.x - camera.position.x / Consts.BG1_DIST; for(int i = -10; i < 11; i++) { spriteBatch.draw(Textures.bg1.get(), -width / 2 + off + i * width, -Consts.HEIGHT / 2 + Consts.HEIGHT * Consts.BG1_HEIGHT_OFF, width, Consts.HEIGHT * Consts.BG1_HEIGHT_PART); } spriteBatch.end(); spriteBatch.setShader(waterShader); Textures.bg1.get().setFilter(TextureFilter.Linear, TextureFilter.Linear); spriteBatch.begin(); Textures.bg1.get().bind(1); waveTime += delta; waterShader.setUniformi("u_texture2", 1); waterShader.setUniformf("u_mult", 1.0f/100f); waterShader.setUniformf("u_time", waveTime); waterShader.setUniformf("u_offset", -(cameraX/width)*(1.0f/Consts.BG2_DIST - 1.0f/Consts.BG1_DIST), 0.3f); Gdx.gl.glActiveTexture(GL20.GL_TEXTURE0); // bg2 width = Consts.HEIGHT * Consts.BG2_HEIGHT_PART * Textures.bg2.get().getWidth() / ((float) Textures.bg2.get().getHeight()); off = camera.position.x - camera.position.x / Consts.BG2_DIST; for(int i = -10; i < 11; i++) { spriteBatch.draw(Textures.bg2.get(), -width / 2 + off + i * width, -Consts.HEIGHT / 2 + Consts.HEIGHT * Consts.BG2_HEIGHT_OFF, width, Consts.HEIGHT * Consts.BG2_HEIGHT_PART); } spriteBatch.end(); Textures.bg1.get().setFilter(TextureFilter.Nearest, TextureFilter.Nearest); spriteBatch.setShader(null); spriteBatch.begin(); for (Renderable renderable : renderables) { renderable.render(spriteBatch, gameWorld.isGameLost() ? 0 : delta); } if(gameWorld.isGameWon()) { spriteBatch.setColor(Color.RED); Font.FONT1.drawBordered(spriteBatch, "LEVEL FINISHED", camera.position.x - 15, 5, 0.25f); spriteBatch.setColor(Color.WHITE); } else if(gameWorld.isGameLost()){ spriteBatch.setColor(1, 0, 0, 0.3f); spriteBatch.draw(overlayRegion, camera.position.x - Consts.WIDTH/2, -Consts.HEIGHT/2, Consts.WIDTH, Consts.HEIGHT); spriteBatch.setColor(Color.RED); Font.FONT1.drawBordered(spriteBatch, "YOU DIED", camera.position.x - 15, 5, 0.5f); spriteBatch.setColor(Color.WHITE); } narrator.setCameraX(cameraX); narrator.drawCurrentSubtitles(spriteBatch); spriteBatch.end(); if (Consts.USE_DEBUG_RENDERER) { debugRenderer.render(gameWorld.getWorld(), camera.combined); } } @Override public void resize(int width, int height) { Consts.WIDTH = Consts.HEIGHT * width / ((float) height); camera = new OrthographicCamera(Consts.WIDTH, Consts.HEIGHT); camera.position.x = cameraX; camera.update(); spriteBatch.setProjectionMatrix(camera.combined); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
35.218919
135
0.707237
bf6897caaf07d13b8a218d85f0b2f00d9e8c8e92
465
public class arrangeCoins{ public static void main(String argv[]){ int input = 0; arrangeCoins ac = new arrangeCoins(); int output = ac.arrangeCoins(input); System.out.print(output); } public int arrangeCoins(int n) { long sum = 0; int i = 0; if(n == 0){ return 0; } while (sum < n){ sum += i ++; } return (n == sum) ?i - 1:i - 2; } }
21.136364
45
0.462366
8bcdc92ba1a5d0b7db986025e35846b5c281df5c
3,584
package com.example.akin.bilekpartner; /** * Created by AKIN Ç on 28.04.2019. */ import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.net.ServerSocket; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import me.aflak.bluetooth.Bluetooth; import static app.akexorcist.bluetotohspp.library.BluetoothState.REQUEST_ENABLE_BT; public class SplashActivity extends AppCompatActivity { static Bluetooth b; static weekData walk = new weekData(); static weekData stair = new weekData(); static weekData sitting = new weekData(); static weekData run = new weekData(); static weekData stand = new weekData(); static weekData totaldata = new weekData(); protected Typeface mTfRegular; TextView app_name; DataBaseHelper db=new DataBaseHelper(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.happy); app_name = (TextView) findViewById(R.id.app_name); mTfRegular = Typeface.createFromAsset(getAssets(), "logo_regular.ttf"); app_name.setTypeface(mTfRegular); app_name.setTextColor(Color.parseColor("#000000")); app_name.startAnimation(AnimationUtils.loadAnimation(SplashActivity.this,R.anim.right_in)); b = new Bluetooth(this); b.enableBluetooth(); int pos = 0; b.connectToDevice(b.getPairedDevices().get(pos)); Button bt=findViewById(R.id.strt); bt.setTextColor(Color.parseColor("#ffffff")); bt.setBackgroundColor(Color.parseColor("#9400D3")); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm"); String date = df.format(Calendar.getInstance().getTime()); startActivity(new Intent(SplashActivity.this, LoginActivity.class)); finish(); } }, 5); } }); } public void onBackPressed() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashActivity.this); alertDialog.setTitle("Uygulamadan Çık?"); alertDialog.setMessage("Çıkmak istediğinize emin misiniz?"); alertDialog.setPositiveButton("Evet", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alertDialog.setNegativeButton("Hayır", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } }
36.20202
99
0.65067
d3c93c8418243d84ab7298d42c4948c459d881c5
410
package com.sparta.eng82.components.pages; import com.sparta.eng82.interfaces.pages.OurStoresPage; import org.openqa.selenium.WebDriver; public class OurStoresPageImpl implements OurStoresPage { private final WebDriver driver; public OurStoresPageImpl(WebDriver driver) { this.driver = driver; } @Override public String getUrl() { return driver.getCurrentUrl(); } }
22.777778
57
0.729268
b83174c5bd2c3577de4777ee1adc10b43a8d5196
1,341
package org.musicbox.miscs; public final class Constants { public static boolean ENABLE_EMBED_THUMBNAILS = false; public static final long DEBUG_BOT_ID = 893259644217225270L; public static final long MAIN_BOT_ID = 892542872811884584L; public static final String PT_BR = "PT_BR"; public static final String KEY_SENDER_NAME = "senderTag"; public static final String KEY_SENDER_AVATAR = "senderAvatar"; public static final String KEY_TRACK_TITLE = "trackTitle"; public static final String KEY_TRACK_TIMESTAMP = "trackTimestamp"; public static final String KEY_FAIL_REASON = "failReason"; public static final String KEY_COMMAND_LIST = "commandList"; public static final String KEY_OWNER = "owner"; public static final String KEY_USER_INPUT = "userInput"; public static final String KEY_COMMAND_USAGE = "commandUsage"; public static final String KEY_GLOBAL_PREFIX = "globalPrefix"; public static final String KEY_EXCEPTION_MESSAGE = "exceptionMessage"; public static final String KEY_MISSING_PERMISSIONS = "missingPermissions"; public static final String KEY_INFORMATIVE_QUEUE = "informativeQueue"; public static final String KEY_MAX_PAGES = "maxPage"; public static final String KEY_CURRENT_PAGE = "currentPage"; public static final String KEY_CONTENT = "content"; }
40.636364
77
0.773304
1522083d11f40af44548d5ecabdf04231c45d2f7
508
package de.fpyttel.teams.chatbot.elasticsearch.parser.entity; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; @AllArgsConstructor @RequiredArgsConstructor public class Answer { @NonNull private String text; private int numberOfParams; public String getText(final Object... params) { if (numberOfParams > 0) { if (numberOfParams == params.length) { return String.format(text, params); } else { return null; } } return text; } }
18.814815
61
0.740157
3b6bfa4947cc03d4d7bab169e6c60c3c362889a3
3,094
/** * 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.oodt.pcs.health; //OODT imports import org.apache.oodt.pcs.input.PGEConfigurationFile; import org.apache.oodt.pcs.input.PGEGroup; import org.apache.oodt.pcs.input.PGEConfigFileReader; import org.apache.oodt.cas.metadata.util.PathUtils; //JDK imports import java.io.FileInputStream; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; /** * * Properties used by the {@link PCSHealthMonitor} tool to determine * {@link ProductCrawler} status. * * @author mattmann * @version $Revision$ */ public class CrawlPropertiesFile implements CrawlerPropertiesMetKeys { private PGEConfigurationFile file; /** * Constructs a new CrawlPropertiesFile. * * @param filePath * The path to the CrawlPropertiesFile to load. * @throws InstantiationException * If there is some error reading the file. */ public CrawlPropertiesFile(String filePath) throws InstantiationException { try { this.file = new PGEConfigFileReader().read(new FileInputStream(filePath)); } catch (Exception e) { throw new InstantiationException(e.getMessage()); } } /** * * @return A {@link List} of {@link CrawlInfo} objects describing a Crawler. */ public List getCrawlers() { PGEGroup crawlInfo = (PGEGroup) this.file.getPgeSpecificGroups().get( CRAWLER_INFO_GROUP); Map scalars = crawlInfo.getScalars(); List crawlers = new Vector(scalars.keySet().size()); for (Iterator i = scalars.keySet().iterator(); i.hasNext();) { String crawlerName = (String) i.next(); String crawlerPort = crawlInfo.getScalar(crawlerName).getValue(); CrawlInfo info = new CrawlInfo(crawlerName, crawlerPort); crawlers.add(info); } return crawlers; } /** * * @return The String hostname that the Crawlers run on. This is used by the * {@link PCSHealthMonitor} tool to communicate with the Crawlers and * to check their status. */ public String getCrawlHost() { String crawlHost = ((PGEGroup) this.file.getPgeSpecificGroups().get( CRAWLER_PROPERTIES_GROUP)).getScalar(CRAWLER_HOST_NAME).getValue(); crawlHost = PathUtils.replaceEnvVariables(crawlHost); return crawlHost; } }
32.568421
80
0.713316
ab4766fd5f5ab7a999795103633b3be29ec3aae9
1,627
/* * Id: NotFoundException.java 12-Mar-2022 3:14:03 am SubhajoyLaskar * Copyright (©) 2022 Subhajoy Laskar * https://www.linkedin.com/in/subhajoylaskar */ package com.xyz.apps.ticketeer.general.service; import java.util.ResourceBundle; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; /** * The not found exception. * * @author Subhajoy Laskar * @version 1.0 */ public abstract class NotFoundException extends ServiceException { /** The serial version UID. */ private static final long serialVersionUID = -230187555370136858L; /** * Instantiates a new not found exception. * * @param resourceBundle the resource bundle * @param messageKey the message key * @param messageArguments the message arguments */ public NotFoundException(final ResourceBundle resourceBundle, final String messageKey, final Object ...messageArguments) { super(resourceBundle, messageKey, messageArguments); } /** * Instantiates a new not found exception. * * @param messageSource the message source * @param messageKey the message key * @param messageArguments the message arguments */ public NotFoundException(final MessageSource messageSource, final String messageKey, final Object ...messageArguments) { super(messageSource, messageKey, messageArguments); } /** * {@inheritDoc} */ @Override public HttpStatus httpStatus() { return HTTP_STATUS; } /** The http status. */ public static final HttpStatus HTTP_STATUS = HttpStatus.NOT_FOUND; }
27.576271
126
0.704978
537e90815c8dae3f9192a7284b57e5c78636e05f
2,270
package com.progwml6.natura.plugin; import com.progwml6.natura.Natura; import com.progwml6.natura.nether.NaturaNether; import com.progwml6.natura.overworld.NaturaOverworld; import mezz.jei.api.IJeiHelpers; import mezz.jei.api.IModPlugin; import mezz.jei.api.IModRegistry; import mezz.jei.api.JEIPlugin; import mezz.jei.api.ingredients.IIngredientBlacklist; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; @JEIPlugin public class PluginJEI implements IModPlugin { @Override public void register(IModRegistry registry) { IJeiHelpers jeiHelpers = registry.getJeiHelpers(); IIngredientBlacklist ingredientBlacklist = jeiHelpers.getIngredientBlacklist(); if (Natura.pulseManager.isPulseLoaded(NaturaOverworld.PulseId)) { ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.eucalyptusDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.hopseedDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.sakuraDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.redwoodDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.redwoodBarkDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.barleyCrop, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaOverworld.cottonCrop, 1, OreDictionary.WILDCARD_VALUE)); } if (Natura.pulseManager.isPulseLoaded(NaturaNether.PulseId)) { ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaNether.ghostwoodDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaNether.bloodwoodDoor, 1, OreDictionary.WILDCARD_VALUE)); ingredientBlacklist.addIngredientToBlacklist(new ItemStack(NaturaNether.litNetherrackFurnace, 1, OreDictionary.WILDCARD_VALUE)); } } }
50.444444
140
0.787225
e2ef2fa3eb92db9a30b1958943f19895f56330f7
1,432
package com.biz; import java.io.Serializable; import java.util.List; public interface BaseBiz<T, PK extends Serializable> { /** * 通过id加载po实例 * @param id * @return 实体对象 */ public T load(PK id); /** * 通过id加载po实例 * @param id * @return 实体对象 */ public T get(PK id); /** * 根据ID数组获取实体对象集合. * @param ids * @return 实体对象集合 */ public List<T> get(PK[] ids); /** * 根据属性名和属性值获取实体对象. * @param propertyName * @param value * @return 实体对象 */ public T get(String propertyName, Object value); /** * 根据属性名和属性值获取实体对象集合. * @param propertyName * @param value * @return 实体对象集合 */ public List<T> getList(String propertyName, Object value); /** * 获取所有实体对象总数. * @return 实体对象总数 */ public Integer getAllCount(); /** * 保存实体对象. * @param entity * @return ID */ public PK save(T entity); /** * 保存或更新一个对象 * @param entity */ public void saveOrUpdate(T entity); /** * 更新实体对象. * @param entity */ public void update(T entity); /** * 合并一个对象 * @param entity */ public void merge(T entity); /** * 删除实体对象. * @param entity * @return */ public void delete(T entity); /** * 根据ID删除实体对象. * @param id */ public void delete(PK id); /** * 根据ID数组删除实体对象. * @param ids */ public void delete(PK[] ids); /** * 根据实体集合删除实体对象 * @param list */ public void delete(List<T> list); /** * 获取全部列表 * @return */ public List<T> list(); }
13.137615
59
0.589385
f1f4e2aa1e03fbc8a87533ea264c777affd45e14
1,081
import java.util.ArrayList; import java.util.List; public class Client { public static void main(String args[]) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Client1","Male", "Single")); persons.add(new Person("Client2", "Male", "Married")); persons.add(new Person("Client3", "Female", "Married")); persons.add(new Person("Client4", "Female", "Single")); persons.add(new Person("Client5", "Male", "Single")); persons.add(new Person("Client6", "Male", "Single")); CriteriaMale maleCriteria = new CriteriaMale(); CriteriaSingle singleCriteria = new CriteriaSingle(); List<Person> malePersons = maleCriteria.meetsCriteria(persons); List<Person> singlePersons = singleCriteria.meetsCriteria(persons); AndCriteria oc = new AndCriteria(maleCriteria, singleCriteria); List<Person> singleMales = oc.meetsCriteria(persons); for(Person p: singleMales) { System.out.println("[" +p.getName()+ ", "+p.getGender()+ ", " +p.getMaritalStatus()+ "]"); } } }
36.033333
96
0.654024
fe4f5c3a6e4d8fb040bd3eae3926826b3a0e93e1
3,115
// $Id: CheckOutMethod.java,v 1.2 2005/03/07 01:29:09 jim Exp $ package us.temerity.pipeline; import java.util.*; /*------------------------------------------------------------------------------------------*/ /* C H E C K - O U T M E T H O D */ /*------------------------------------------------------------------------------------------*/ /** * The method for creating working area files/links from the checked-in files. */ public enum CheckOutMethod { /** * Copy the checked-in files associated with all nodes to the working area. */ Modifiable, /** * Determine whether a node should be checked-out frozen based on the frozen state of * existing working versions. When a frozn existing working version is encountered, the * node and all nodes upstream of the frozen node will be checked-out frozen. Otherwise, * nodes are checked-out modifiable. */ PreserveFrozen, /** * Copy the checked-in files associated with the root node of the check-out to the * working area, but create symlinks from the working area to the checked-in files for * all nodes upstream of the root node. */ FrozenUpstream, /** * Create symlinks from the working area to the checked-in files for all nodes. */ AllFrozen; /*----------------------------------------------------------------------------------------*/ /* A C C E S S */ /*----------------------------------------------------------------------------------------*/ /** * Get the list of all possible states. */ public static ArrayList<CheckOutMethod> all() { CheckOutMethod values[] = values(); ArrayList<CheckOutMethod> all = new ArrayList<CheckOutMethod>(values.length); int wk; for(wk=0; wk<values.length; wk++) all.add(values[wk]); return all; } /** * Get the list of human friendly string representation for all possible values. */ public static ArrayList<String> titles() { ArrayList<String> titles = new ArrayList<String>(); for(CheckOutMethod method : CheckOutMethod.all()) titles.add(method.toTitle()); return titles; } /*----------------------------------------------------------------------------------------*/ /* C O N V E R S I O N */ /*----------------------------------------------------------------------------------------*/ /** * Convert to a more human friendly string representation. */ public String toTitle() { return sTitles[ordinal()]; } /*----------------------------------------------------------------------------------------*/ /* S T A T I C I N T E R N A L S */ /*----------------------------------------------------------------------------------------*/ private static String sTitles[] = { "Modifiable", "Preserve Frozen", "Frozen Upstream", "All Frozen" }; }
30.841584
94
0.434992
5e294f0b90e7e98f9f112502e406b2a57f907841
1,869
package au.org.greekwelfaresa.idempiere.test.assertj.bankstatementmatchinfo; import org.compiere.impexp.BankStatementMatchInfo; import au.org.greekwelfaresa.idempiere.test.assertj.AbstractIDAssert; public abstract class AbstractBankStatementMatchInfoAssert<SELF extends AbstractBankStatementMatchInfoAssert<SELF, ACTUAL>, ACTUAL extends BankStatementMatchInfo> extends AbstractIDAssert<SELF, ACTUAL> { public AbstractBankStatementMatchInfoAssert(ACTUAL actual, Class<SELF> selfType) { super(actual, selfType); } protected String getDescription() { return "BankStatementMatchInfo"; } public SELF isMatched() { isNotNull(); if (!actual.isMatched()) { failWithMessage("\nExpecting BankStatementMatchInfo to be Matched\nbut it was not"); } return myself; } public SELF isNotMatched() { isNotNull(); if (!actual.isMatched()) { failWithMessage("\nExpecting BankStatementMatchInfo to not be Matched\nbut it was"); } return myself; } public SELF hasC_BPartner_ID(int expected) { isNotNull(); int actualField = actual.getC_BPartner_ID(); if (expected != actualField) { failWithMessage("\nExpecting BankStatementMatchInfo:\n to have C_BPartner_ID: <%s>\nbut it was: <%s>", expected, actualField); } return myself; } public SELF hasC_Payment_ID(int expected) { isNotNull(); int actualField = actual.getC_Payment_ID(); if (expected != actualField) { failWithMessage("\nExpecting BankStatementMatchInfo:\n to have C_Payment_ID: <%s>\nbut it was: <%s>", expected, actualField); } return myself; } public SELF hasC_Invoice_ID(int expected) { isNotNull(); int actualField = actual.getC_Invoice_ID(); if (expected != actualField) { failWithMessage("\nExpecting BankStatementMatchInfo:\n to have C_Invoice_ID: <%s>\nbut it was: <%s>", expected, actualField); } return myself; } }
28.318182
162
0.742643
14dd8f8e72ec39a462804f2678e0d16dcf954796
896
package com.zdcf.leetcode; //104. Maximum Depth of Binary Tree //Given a binary tree, find its maximum depth. // //The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. public class MaximumDepthofBinaryTree { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public int maxDepth(TreeNode root) { int left =0; int right = 0; if(null!=root){ left++; right++; }else{ return 0; } return Math.max(calSum(root.left,left),calSum(root.right,right)); } private int calSum(TreeNode temp,int count){ if(null==temp){ return count; }else{ return Math.max(calSum(temp.left,count+1),calSum(temp.right,count+1)); } } }
27.151515
116
0.579241
c2420e088c6146a077150a6341737677b9630514
2,375
/* * Project Sc2gears * * Copyright (c) 2010 Andras Belicza <[email protected]> * * This software is the property of Andras Belicza. * Copying, modifying, distributing, refactoring without the authors permission * is prohibited and protected by Law. */ package hu.belicza.andras.sc2gears.util; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** * Base64 encoding utility. * <p>Info about Base64: <a href="http://en.wikipedia.org/wiki/Base64">Base64 on Wikipedia</a></p> * * @author Andras Belicza */ public class Base64 { /** Symbols used in the base64 format. */ private static char[] BASE64_SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); /** Base64 padding character. */ private static char BASE64_PADDING = '='; /** * Returns the base64 encoded form of the specified file. * @param file file to be encoded * @return the base64 encoded form of the specified file; or <code>null</code> if some error occurs */ public static String encodeFile( final File file ) { if ( !file.exists() ) return null; // 3 bytes results in 4: charCount = RoundUp( size / 3 ) * 4 int bytesLeft = (int) file.length(); final char[] encoded = new char[ ( (bytesLeft+2) / 3 ) * 4 ]; int charPos = 0; try ( final InputStream input = new FileInputStream( file ) ) { while ( bytesLeft > 0 ) { final int byte1 = input.read(); final int byte2 = bytesLeft > 1 ? input.read() : 0; final int byte3 = bytesLeft > 2 ? input.read() : 0; encoded[ charPos++ ] = BASE64_SYMBOLS[ byte1 >> 2 ]; encoded[ charPos++ ] = BASE64_SYMBOLS[ ( byte1 & 0x03 ) << 4 | ( byte2 & 0xf0 ) >> 4 ]; if ( bytesLeft > 1 ) { encoded[ charPos++ ] = BASE64_SYMBOLS[ ( byte2 & 0x0f ) << 2 | ( byte3 & 0xc0 ) >> 6 ]; if ( bytesLeft > 2 ) encoded[ charPos++ ] = BASE64_SYMBOLS[ byte3 &0x3f ]; else // 1 padding byte encoded[ charPos++ ] = BASE64_PADDING; } else { // 2 padding bytes encoded[ charPos++ ] = BASE64_PADDING; encoded[ charPos++ ] = BASE64_PADDING; } bytesLeft -= 3; } } catch ( final Exception e ) { e.printStackTrace(); return null; } return new String( encoded ); } }
30.448718
122
0.611368
1ba235d353bb8dda1c5cc58970ccfacaf220c4a7
3,383
package assignemnt2; // Aleksandr Kudin, 101258693 // Matthew Campbell, 101289518 // Michael Sirna, 101278670 // Stephen Davis, 101294116 public class QuadraticHashTable { private int numItems; private int tableSize; private KeyValuePair[] table; private final double LOAD_FACTOR = 0.80; // Constructor. Table size is hardcoded. public QuadraticHashTable(){ numItems = 0; tableSize = 101; // 101 is a prime number suitable for the hash table. table = new KeyValuePair[101]; } // Hash Method. Returns the hash value of the Weapon key (weapon name). private int hashFunction(String key){ key = key.toLowerCase(); int value = 0, weight = 1; for (int x = 0; x < key.length(); x++){ value += (key.charAt(x) -'a'+ 1) * weight; weight++; } if (value < 0) { value *= -1; } // If the value is negative, make it positive. return value % tableSize; } // Insert Method. Insert Weapon object in the location based on the value of the hash method. public boolean insert (Weapon weapon){ if ((double)numItems/tableSize < LOAD_FACTOR){ int count = 1; int loc = hashFunction(weapon.name); // Loop while it's not NULL AND the Key Value Pair value is not deleted. while (table[loc] != null && table[loc].key != null){ loc = (loc + count * count) % tableSize; // Quadratic probing. count++; } table[loc] = new KeyValuePair(weapon.name, weapon); numItems++; return true; } return false; // Load Factor Error. } // Search Method. Search for a Weapon object in the hash table by its key (weapon name) and returns its location. public int search(String key){ int loc = hashFunction(key); int count = 1; // Loop while it's not NULL AND the key value in the Key Value Pair does not match. while (table[loc] != null && !table[loc].getKey().equalsIgnoreCase(key)){ loc = (loc + count * count) % tableSize; // Quadratic probing. count++; } if (table[loc] == null){ // Weapon not found. return -1; } return loc; } // Delete Method. Search for a Weapon object in the hash table by its key (weapon name) and reset the Key Value Pair object. public void delete(String key){ int loc = search(key); if (loc == -1){ return; } // Weapon not found. table[loc].drop(); // Reset the Key Value Pair object with the Weapon object in it. numItems--; } // Get Method. Search for a Weapon object in the hash table by its key (weapon name) and returns the object if found. public Weapon getWeapon(String key){ int loc = search(key); if (loc != -1){ // Weapon is found. return table[search(key)].getValue(); // Return the Weapon object. } return null; // Weapon not found. } // Print Method. Check for existing in the hash table Weapon objects and print their value. public void printTable(){ for (int x = 0; x < tableSize; x++){ if (table[x] != null && table[x].getValue() != null){ System.out.println(table[x].getValue().toString()); } } } }
38.443182
128
0.582619
de9dd5ec67c32eb522c9625d21c3ea0d18862f65
271
package souza.charles.domain.usecases.user; import souza.charles.domain.entities.user.User; import souza.charles.domain.usecases.utils.DAO; import java.util.Optional; public interface UserDAO extends DAO<User, String> { Optional<User> findByEmail(String email); }
24.636364
52
0.793358
18f5052a5557038033770ecd492e24112120e141
1,526
package com.min.base; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; /** * Created by Dawish on 2016/6/17. * Base Fragment */ public abstract class BaseFragment extends Fragment { protected Activity mActivity; protected View contentView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mActivity = getActivity(); contentView = getContentView(inflater,container); return contentView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initViews(view); initDatas(); initListeners(); } /** * set content view * @param inflater * @return */ protected abstract View getContentView(LayoutInflater inflater ,ViewGroup container); /** * init view * @param contentView * @return */ protected abstract void initViews(View contentView); /*** * set listeners */ protected abstract void initListeners(); /** * init data */ protected abstract void initDatas(); /** * show toast */ protected void showToast(String msg){ if(msg != null){ Toast.makeText(mActivity , msg,Toast.LENGTH_SHORT).show(); } } }
23.121212
105
0.650721
5848d8c81d494b18632ea8650b114a2efc2d2087
977
package de.timmi6790.mpstats.api.client.bedrock.player.deserializers; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import de.timmi6790.mpstats.api.client.bedrock.player.models.BedrockPlayer; import java.io.IOException; import java.io.Serial; public class BedrockPlayerDeserializer extends StdDeserializer<BedrockPlayer> { @Serial private static final long serialVersionUID = 1972105464341747687L; public BedrockPlayerDeserializer() { super(BedrockPlayer.class); } @Override public BedrockPlayer deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException { final JsonNode node = jsonParser.getCodec().readTree(jsonParser); return new BedrockPlayer( node.get("name").textValue() ); } }
34.892857
121
0.769703
2789db6dc8da8390371a647926d51a009822476b
2,614
/* * Copyright (C) 2014-2018, Amobee 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 */ package com.turn.camino; import java.util.TimeZone; import java.util.concurrent.ExecutorService; import org.apache.hadoop.fs.FileSystem; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; /** * Unit test for EnvBuilder * * @author llo */ @Test public class EnvBuilderTest { /** * Test with all options */ @Test public void testWithAll() { TimeZone timeZone = TimeZone.getTimeZone("GMT"); FileSystem fileSystem = mock(FileSystem.class); ExecutorService executorService = mock(ExecutorService.class); Env env = new EnvBuilder().withTimeZone(timeZone).withFileSystem(fileSystem) .withExecutorService(executorService).build(); assertEquals(env.getFileSystem(), fileSystem); assertEquals(env.getTimeZone(), timeZone); assertEquals(env.getExecutorService(), executorService); } /** * Test not specifying time zone */ @Test public void testDefaultTimeZone() { FileSystem fileSystem = mock(FileSystem.class); ExecutorService executorService = mock(ExecutorService.class); Env env = new EnvBuilder().withFileSystem(fileSystem) .withExecutorService(executorService).build(); assertEquals(env.getFileSystem(), fileSystem); assertEquals(env.getTimeZone(), TimeZone.getDefault()); assertEquals(env.getExecutorService(), executorService); } /** * Test error handler */ @Test public void testWithErrorHandler() { Env env = new EnvBuilder().withFileSystem(mock(FileSystem.class)) .build(); assertNotNull(env.getErrorHandler()); ErrorHandler errorHandler = mock(ErrorHandler.class); env = new EnvBuilder().withFileSystem(mock(FileSystem.class)) .withErrorHandler(errorHandler) .build(); assertEquals(env.getErrorHandler(), errorHandler); } /** * Test not specifying any options, throws exception */ @Test(expectedExceptions = NullPointerException.class) public void testMissingFileSystem() { new EnvBuilder().build(); } }
29.704545
78
0.747131
09522a8df5fc59971800abd3751dd86dad031200
6,414
/* * Copyright 2019 Orient Securities Co., Ltd. * Copyright 2019 BoCloud 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.orientsec.grpc.consumer.task; import com.orientsec.grpc.common.constant.GlobalConstants; import com.orientsec.grpc.common.constant.RegistryConstants; import com.orientsec.grpc.common.exception.BusinessException; import com.orientsec.grpc.common.util.StringUtils; import com.orientsec.grpc.consumer.common.ConsumerConstants; import com.orientsec.grpc.consumer.core.ConsumerConfigUtils; import com.orientsec.grpc.consumer.core.DefaultConsumerServiceRegistryImpl; import com.orientsec.grpc.consumer.watch.ConsumerListener; import com.orientsec.grpc.registry.common.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 注册服务 * <p> * 消费者调用服务时,基于配置文件,自动注册该consumer。 <br> * 从配置文件中获取服务注册必选参数和部分可选参数,为注册服务做准备。 * 同时需要订阅相关的目录 * </p> * * @author dengjq * @since V1.0 2017/3/30 */ public class RegistryTask extends AbstractTask { private static final Logger logger = LoggerFactory.getLogger(RegistryTask.class); Map<String, Object> listeners; /** * consumer 运行时属性参数 */ private Map<String, Object> consumersParams = null; /** * 该服务器上的所有服务接口名 */ private List<String> interfaceNames; /** * 由consumer运行时属性参数和配置文件属性参数生成的最终属性参数 */ private Map<String, Object> confItem; public RegistryTask(DefaultConsumerServiceRegistryImpl caller, Map<String, Object> consumersParams, Map<String, Object> listeners) { super(caller); this.listeners = listeners; this.consumersParams = consumersParams; } /** * 主方法 * * @author djq * @since V1.0 2017/3/30 */ public String work() throws Exception { if (consumersParams == null) { throw new BusinessException("注册服务失败:传入的参数servicesParams为空"); } // 校验和保存配置文件信息 confItem = ConsumerConfigUtils.mergeConsumerConfig(consumersParams); // 注册并增加监听器 return doRegister(); } private Map<String, String> initConsumerParams() { Map<String, String> parameters = new HashMap<String, String>(); parameters.put(GlobalConstants.Consumer.Key.CATEGORY, RegistryConstants.CONSUMERS_CATEGORY); parameters.put(GlobalConstants.Consumer.Key.SIDE, RegistryConstants.CONSUMER_SIDE); parameters.put(RegistryConstants.DYNAMIC_KEY, "true"); return parameters; } /** * 注册并增加监听器 * * @author dengjq * @since V1.0 2017/3/24 */ private String doRegister() throws Exception { Map<String, Object> listenersInfo = caller.getListenersInfo(); URL urlOfConsumer, urlOfProviders, urlOfRouters, urlOfConfigurators; Map<String, String> consumerInfo; Map<String, String> parameters; Object value; String valueOfS; int port = 0; String interfaceName = confItem.get(GlobalConstants.Consumer.Key.INTERFACE).toString(); if (confItem.containsKey(GlobalConstants.CONSUMER_REQUEST_PORT)) { port = Integer.valueOf(confItem.get(GlobalConstants.CONSUMER_REQUEST_PORT).toString()); } consumerInfo = initConsumerParams(); //遍历配置项 for (Map.Entry<String, Object> entry : confItem.entrySet()) { if (GlobalConstants.CONSUMER_REQUEST_PORT.equals(entry.getKey()) || GlobalConstants.Consumer.Key.METHODS.equals(entry.getKey())) { continue; } value = entry.getValue(); valueOfS = (value == null) ? (null) : String.valueOf(value); if (!StringUtils.isEmpty(valueOfS)) { consumerInfo.put(entry.getKey(), valueOfS); } } // 注册服务(providers) parameters = new HashMap<String, String>(consumerInfo); urlOfConsumer = new URL(RegistryConstants.CONSUMER_PROTOCOL, caller.getIp(), port, interfaceName, parameters); logger.info( "客户端注册:" + urlOfConsumer); safeRegistry(urlOfConsumer); String uuid = urlOfConsumer.toFullString(); listeners.put("urlOfConsumer", urlOfConsumer); if (listenersInfo != null && listenersInfo.size() > 0) { ConsumerListener providerListener = (ConsumerListener) listenersInfo.get(ConsumerConstants.PROVIDERS_LISTENER_KEY); if (providerListener != null) { logger.info( "消费者订阅providers目录"); //调低日志级别,默认不输出日志 consumerInfo.put(RegistryConstants.CATEGORY_KEY, RegistryConstants.PROVIDERS_CATEGORY); parameters = new HashMap<String, String>(consumerInfo); urlOfProviders = new URL(RegistryConstants.GRPC_PROTOCOL, caller.getIp(), port, interfaceName, parameters); safeSubscribe(urlOfProviders, providerListener); listeners.put("urlOfProviders", urlOfProviders); } ConsumerListener routerListener = (ConsumerListener) listenersInfo.get(ConsumerConstants.ROUTERS_LISTENER_KEY); if (routerListener != null) { logger.info("消费者订阅routers目录"); consumerInfo.put(RegistryConstants.CATEGORY_KEY, RegistryConstants.ROUTERS_CATEGORY); parameters = new HashMap<String, String>(consumerInfo); urlOfRouters = new URL(RegistryConstants.ROUTER_PROTOCOL, caller.getIp(), port, interfaceName, parameters); safeSubscribe(urlOfRouters, routerListener); listeners.put("urlOfRouters", urlOfRouters); } ConsumerListener configuratorListener = (ConsumerListener) listenersInfo.get(ConsumerConstants.CONFIGURATORS_LISTENER_KEY); if (configuratorListener != null) { logger.info("消费者订阅configurators目录"); consumerInfo.put(RegistryConstants.CATEGORY_KEY, RegistryConstants.CONFIGURATORS_CATEGORY); parameters = new HashMap<String, String>(consumerInfo); urlOfConfigurators = new URL(RegistryConstants.OVERRIDE_PROTOCOL, caller.getIp(), port, interfaceName, parameters); safeSubscribe(urlOfConfigurators, configuratorListener); listeners.put("urlOfConfigurators", urlOfConfigurators); } } return uuid; } }
35.241758
134
0.727315
e8e6e0d4556ce1f269d6f3749298e299e64c74f9
1,079
package com.example.android.pickerfortime; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.text.format.DateFormat; import android.widget.TimePicker; import java.util.Calendar; public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity())); } @Override public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) { MainActivity activity = (MainActivity) getActivity(); activity.processTimePickerResult(hourOfDay, minute); } }
25.690476
77
0.736793
e62d29d62cc2382819b5d05dd08da6c2fff91cfd
1,159
package ru.job4j.mapcollection; import java.util.HashMap; import java.util.Map; /** * */ public class MapMethodsInAction { private User user; private Map<User, Object> map; /** * Put on map 2 equal key type User without override * methods: equals and hashcode. Then print map. */ public void dontOverrideEuqalsAndHashCode() { map = new HashMap<>(); User firstUser = new User("Boris", 3, 1984, 12, 12); User secondUser = new User("Boris", 3, 1984, 12, 12); map.put(firstUser, firstUser); map.put(secondUser, secondUser); for (Map.Entry<User, Object> entry : map.entrySet()) { User key = entry.getKey(); Object value = entry.getValue(); System.out.printf("User name is: %s\nUser birthday is: %s\n" + "Amount of children: %s\n", key.getName(), key.getBirthday().getTime(), key.getChildren()); } } /** * main method. * @param args - args. */ public static void main(String[] args) { new MapMethodsInAction().dontOverrideEuqalsAndHashCode(); } }
27.595238
83
0.575496
92cc0b847bd2b1cb03c762123de05ab5f8d615d5
476
package com.pointlion.sys.mvc.common.model; import com.pointlion.sys.mvc.common.model.base.BaseSysUserRole; /** * Generated by JFinal. */ @SuppressWarnings("serial") public class SysUserRole extends BaseSysUserRole<SysUserRole> { public static final SysUserRole dao = new SysUserRole(); public SysUserRole findByUserId(String userId) { SysUserRole sysUserRole = dao.findFirst("select * from sys_user_role where user_id = ?",userId); return sysUserRole; } }
25.052632
98
0.760504
611d8133ee3ba3950c13eb1db778ab2d1efcac1a
5,015
/** * 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.hadoop.yarn.server.resourcemanager.scheduler.policy; import java.util.*; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; /** * 决定调度实体的调度顺序 * OrderingPolicy is used by the scheduler to order SchedulableEntities for * container assignment and preemption. * @param <S> the type of {@link SchedulableEntity} that will be compared */ public interface OrderingPolicy<S extends SchedulableEntity> { /* * Note: OrderingPolicy depends upon external * synchronization of all use of the SchedulableEntity Collection and * Iterators for correctness and to avoid concurrent modification issues */ /** * Get the collection of {@link SchedulableEntity} Objects which are managed * by this OrderingPolicy - should include processes returned by the * Assignment and Preemption iterator with no guarantees regarding order. * @return a collection of {@link SchedulableEntity} objects */ public Collection<S> getSchedulableEntities(); /** * Return an iterator over the collection of {@link SchedulableEntity} * objects which orders them for container assignment. * @return an iterator over the collection of {@link SchedulableEntity} * objects */ public Iterator<S> getAssignmentIterator(); /** * Return an iterator over the collection of {@link SchedulableEntity} * objects which orders them for preemption. * @return an iterator over the collection of {@link SchedulableEntity} */ public Iterator<S> getPreemptionIterator(); /** * Add a {@link SchedulableEntity} to be managed for allocation and preemption * ordering. * @param s the {@link SchedulableEntity} to add */ public void addSchedulableEntity(S s); /** * Remove a {@link SchedulableEntity} from management for allocation and * preemption ordering. * @param s the {@link SchedulableEntity} to remove * @return whether the {@link SchedulableEntity} was present before this * operation */ public boolean removeSchedulableEntity(S s); /** * Add a collection of {@link SchedulableEntity} objects to be managed for * allocation and preemption ordering. * @param sc the collection of {@link SchedulableEntity} objects to add */ public void addAllSchedulableEntities(Collection<S> sc); /** * Get the number of {@link SchedulableEntity} objects managed for allocation * and preemption ordering. * @return the number of {@link SchedulableEntity} objects */ public int getNumSchedulableEntities(); /** * Provides configuration information for the policy from the scheduler * configuration. * @param conf a map of scheduler configuration properties and values */ public void configure(Map<String, String> conf); /** * Notify the {@code OrderingPolicy} that the {@link SchedulableEntity} * has been allocated the given {@link RMContainer}, enabling the * {@code OrderingPolicy} to take appropriate action. Depending on the * comparator, a reordering of the {@link SchedulableEntity} may be required. * @param schedulableEntity the {@link SchedulableEntity} * @param r the allocated {@link RMContainer} */ public void containerAllocated(S schedulableEntity, RMContainer r); /** * Notify the {@code OrderingPolicy} that the {@link SchedulableEntity} * has released the given {@link RMContainer}, enabling the * {@code OrderingPolicy} to take appropriate action. Depending on the * comparator, a reordering of the {@link SchedulableEntity} may be required. * @param schedulableEntity the {@link SchedulableEntity} * @param r the released {@link RMContainer} */ public void containerReleased(S schedulableEntity, RMContainer r); /** * Notify the {@code OrderingPolicy} that the demand for the * {@link SchedulableEntity} has been updated, enabling the * {@code OrderingPolicy} to reorder the {@link SchedulableEntity} if needed. * @param schedulableEntity the updated {@link SchedulableEntity} */ void demandUpdated(S schedulableEntity); /** * Return information regarding configuration and status. * @return configuration and status information */ public String getInfo(); }
37.706767
80
0.73659
e86d6f61711f97143bfe1932ffff32ca3ab0fcd0
3,101
package nb.barmie.modes.attack; import java.util.ArrayList; import nb.barmie.modes.enumeration.RMIEndpoint; /*********************************************************** * Deserialization payload factory class. * * Essentially maintains a list of all supported Java * deserialization payloads and the classes/objects * implementing them. * * Written by Nicky Bloor (@NickstaDB). **********************************************************/ public class DeserPayloadFactory { /******************* * Properties ******************/ private static final ArrayList<DeserPayload> _payloads; //All deserialization payloads /******************* * Initialise the list of supported deserialization payloads ******************/ static { //Create the list of deserialization payloads _payloads = new ArrayList<DeserPayload>(); //Add all supported payloads to the list _payloads.add(new nb.barmie.modes.attack.deser.payloads.CommonsCollectionsPayload1()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.CommonsCollectionsPayload2()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.GroovyPayload1()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.GroovyPayload2()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.JBossInterceptorsPayload1()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.ROMEPayload1()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.ROMEPayload2()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.RhinoPayload1()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.RhinoPayload2()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.RhinoPayload3()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.RhinoPayload4()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.RhinoPayload5()); _payloads.add(new nb.barmie.modes.attack.deser.payloads.RhinoPayload6()); } /******************* * Find all deserialization payloads that affect the given RMI endpoint. * * This won't always work as it depends on remote classes being annotated * with CLASSPATH jar files. If these annotations aren't present, as is * often the case, then all payloads can be attempted (or attack/target * specific payloads can be used). * * @param ep The enumerated RMI endpoint. * @return An ArrayList of DeserPayload objects that should affect the given endpoint. ******************/ public static ArrayList<DeserPayload> findGadgetsForEndpoint(RMIEndpoint ep) { ArrayList<DeserPayload> payloads = new ArrayList<DeserPayload>(); //Find all deserialization payloads that can target the given endpoint for(DeserPayload p: _payloads) { if(p.doesAffectEndpoint(ep)) { payloads.add(p); } } //Return the list of deserialization payloads that affect the given endpoint return payloads; } /******************* * Get a list of all known deserialization payloads. * * @return An ArrayList of DeserPayload objects. ******************/ public static ArrayList<DeserPayload> getAllPayloads() { return _payloads; } }
39.75641
88
0.695905
a32ced0701612309ccbcca20bd9c3ec14255de36
4,398
package com.datdeveloper.randomspawn2.events; import com.datdeveloper.randomspawn2.RandomConfig; import com.datdeveloper.randomspawn2.RandomSpawn2; import com.datdeveloper.randomspawn2.Util; import com.datdeveloper.randomspawn2.capability.IRespawn; import com.datdeveloper.randomspawn2.capability.RespawnProvider; import com.demmodders.datmoddingapi.util.BlockPosUtil; import com.demmodders.datmoddingapi.util.DemConstants; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.SPacketChangeGameState; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; @Mod.EventBusSubscriber(modid = RandomSpawn2.MOD_ID) public class SpawnWatcher { @SubscribeEvent public static void onPlayerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) { if (event.player.getCapability(RespawnProvider.RESPAWN_CAPABILITY, null).getSpawn(event.player.getSpawnDimension()) == null) { Util.randomiseSpawnPoint((EntityPlayerMP) event.player, event.player.getSpawnDimension()); Util.teleportPlayer((EntityPlayerMP) event.player, event.player.getSpawnDimension()); } } @SubscribeEvent public static void onLivingDeath(LivingDeathEvent event) { if (!(event.getEntityLiving() instanceof EntityPlayerMP)) return; EntityPlayerMP player = (EntityPlayerMP) event.getEntityLiving(); // Predict the next dimension int dimension = Util.getValidSpawnDimension(player, player.dimension); if (player.isSpawnForced(dimension)) { if (!RandomConfig.saveSpawn) Util.randomiseSpawnPoint(player, dimension); } else { World world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(dimension); BlockPos spawn = EntityPlayer.getBedSpawnLocation(world, player.getBedLocation(dimension), player.forceSpawn); if (spawn == null) { IRespawn respawn = player.getCapability(RespawnProvider.RESPAWN_CAPABILITY, null); respawn.setBedReset(true); if (RandomConfig.saveSpawn) { player.setSpawnChunk(respawn.getSpawn(dimension), true, dimension); } else { Util.randomiseSpawnPoint(player, dimension); } } } } @SubscribeEvent public static void playerRespawn(PlayerEvent.PlayerRespawnEvent e){ if (!e.isEndConquered()) { IRespawn respawn = e.player.getCapability(RespawnProvider.RESPAWN_CAPABILITY, null); if (respawn.isBedReset()) { ((EntityPlayerMP) e.player).connection.sendPacket(new SPacketChangeGameState(0, 0.0F)); respawn.setBedReset(false); } else if (e.player.getBedLocation(e.player.dimension) == null) { Util.randomiseSpawnPoint((EntityPlayerMP) e.player, e.player.dimension); Util.teleportPlayer((EntityPlayerMP) e.player, e.player.dimension); e.player.sendMessage(new TextComponentString(DemConstants.TextColour.ERROR + "or rather, your spawn was, thus has been reset")); } else if (RandomConfig.safeSpawn && e.player.isSpawnForced(e.player.dimension)) { BlockPos pos = Util.getSafeBlockPos(e.player.getPosition(), e.player.dimension); if (pos == null) { Util.randomiseSpawnPoint((EntityPlayerMP) e.player, e.player.dimension); Util.teleportPlayer((EntityPlayerMP) e.player, e.player.dimension); e.player.sendMessage(new TextComponentString(DemConstants.TextColour.ERROR + "Your spawn point is unavailable, resetting")); } else { Util.setPlayerSpawn((EntityPlayerMP) e.player, pos, e.player.dimension); } } respawn.setLastTeleport(System.currentTimeMillis()); } } }
51.139535
145
0.684857
042a450a1876f1796f30d28e685d78655f0b80f3
192
package fr.lespoulpes.messaging.bridge.subscriber; public class MessageReaderException extends Exception { public MessageReaderException(Throwable cause) { super(cause); } }
21.333333
55
0.755208
68fa40701bcfeb9ae061b9f9775d329e71defc01
2,467
package feamer.desktop; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.file.Paths; import mslinks.ShellLink; public class Setup { public static void setup() { File linkFile = new File("%APPDATA%\\Microsoft\\Windows\\SendTo\\Feamer.lnk"); if (!linkFile.exists()) { String workingDirectory = Paths.get(".").toAbsolutePath().normalize().toString(); System.out.println(workingDirectory + "\\feamer.ico"); String path = Setup.class.getProtectionDomain().getCodeSource().getLocation().getPath(); try { String decodedPath = URLDecoder.decode(path, "UTF-8"); ShellLink sl = ShellLink.createLink(workingDirectory+"\\feamer_me.exe").setWorkingDir("") .setIconLocation(Paths.get(".").toAbsolutePath().normalize().toString() + "\\feamer.ico"); // sl.getHeader().setIconIndex(128); sl.getConsoleData().setFont(mslinks.extra.ConsoleData.Font.Consolas).setFontSize(24).setTextColor(5); try { sl.saveTo(System.getenv("APPDATA") + "\\Microsoft\\Windows\\SendTo\\feamer (my devices).lnk"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ShellLink sl2 = ShellLink.createLink(workingDirectory+"\\feamer_friend.exe").setWorkingDir("") .setIconLocation(Paths.get(".").toAbsolutePath().normalize().toString() + "\\feamer.ico"); // sl.getHeader().setIconIndex(128); sl2.getConsoleData().setFont(mslinks.extra.ConsoleData.Font.Consolas).setFontSize(24).setTextColor(5); try { sl2.saveTo(System.getenv("APPDATA") + "\\Microsoft\\Windows\\SendTo\\feamer (my friends).lnk"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*ShellLink sl3 = ShellLink.createLink(workingDirectory+"\\feamer_all.bat").setWorkingDir("") .setIconLocation(Paths.get(".").toAbsolutePath().normalize().toString() + "\\feamer.ico"); // sl.getHeader().setIconIndex(128); sl3.getConsoleData().setFont(mslinks.extra.ConsoleData.Font.Consolas).setFontSize(24).setTextColor(5); try { sl3.saveTo(System.getenv("APPDATA") + "\\Microsoft\\Windows\\SendTo\\feamer (nearby devices).lnk"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }
39.15873
106
0.692339
723c452904c247b993f085c738dc39796dda079d
4,632
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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.jitsi.android.util; import java.io.*; import java.util.logging.*; /** * Slightly modified <tt>ScLogFormatter</tt> to Android specifics. * * @author Pawel Domas */ public class AndroidLogFormatter extends java.util.logging.Formatter { private static String lineSeparator = System.getProperty("line.separator"); private final boolean useAndroidLevels; public AndroidLogFormatter() { this.useAndroidLevels = AndroidConsoleHandler.isUseAndroidLevels(); } /** * Format the given LogRecord. * @param record the log record to be formatted. * @return a formatted log record */ @Override public synchronized String format(LogRecord record) { StringBuilder sb = new StringBuilder(); if(!useAndroidLevels) { //log level sb.append(record.getLevel().getLocalizedName()); sb.append(": "); } // Thread ID sb.append("[").append( record.getThreadID() ).append("] "); //caller method int lineNumber = inferCaller(record); String loggerName = record.getLoggerName(); if(loggerName == null) loggerName = record.getSourceClassName(); if(loggerName.startsWith("net.java.sip.communicator.")) { sb.append(loggerName.substring("net.java.sip.communicator." .length())); } else sb.append(record.getLoggerName()); if (record.getSourceMethodName() != null) { sb.append("."); sb.append(record.getSourceMethodName()); //include the line number if we have it. if(lineNumber != -1) sb.append("().").append(Integer.toString(lineNumber)); else sb.append("()"); } sb.append(" "); sb.append(record.getMessage()); sb.append(lineSeparator); if (record.getThrown() != null) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); sb.append(sw.toString()); } catch (Exception ex) { } } return sb.toString(); } /** * Try to extract the name of the class and method that called the current * log statement. * * @param record the logrecord where class and method name should be stored. * * @return the line number that the call was made from in the caller. */ private int inferCaller(LogRecord record) { // Get the stack trace. StackTraceElement stack[] = (new Throwable()).getStackTrace(); //the line number that the caller made the call from int lineNumber = -1; // First, search back to a method in the SIP Communicator Logger class. int ix = 0; while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (cname.equals("net.java.sip.communicator.util.Logger")) { break; } ix++; } // Now search for the first frame before the SIP Communicator Logger class. while (ix < stack.length) { StackTraceElement frame = stack[ix]; lineNumber=stack[ix].getLineNumber(); String cname = frame.getClassName(); if (!cname.equals("net.java.sip.communicator.util.Logger")) { // We've found the relevant frame. record.setSourceClassName(cname); record.setSourceMethodName(frame.getMethodName()); break; } ix++; } return lineNumber; } }
30.27451
83
0.572107
b7c3f0a4eae240f95ab9299829a8f11ad530ad4a
1,682
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.p1nesap.ezdungeon.items.bags; import com.p1nesap.ezdungeon.items.Item; import com.p1nesap.ezdungeon.items.wands.Wand; import com.p1nesap.ezdungeon.sprites.ItemSpriteSheet; public class WandHolster extends Bag { { name = "wand holster"; image = ItemSpriteSheet.HOLSTER; size = 12; } @Override public boolean grab( Item item ) { return item instanceof Wand; } @Override public boolean collect( Bag container ) { if (super.collect( container )) { if (owner != null) { for (Item item : items) { ((Wand)item).charge( owner ); } } return true; } else { return false; } } @Override public void onDetach( ) { for (Item item : items) { ((Wand)item).stopCharging(); } } @Override public int price() { return 50; } @Override public String info() { return "This slim holder is made of leather of some exotic animal. " + "It allows to compactly carry up to " + size + " wands."; } }
23.690141
71
0.687872
59af5032e7effb2efd421f879b1b34bb3c6913ce
103
package com.example.footer.utils; /** * Created by 乃军 on 2017/12/21. */ public class HttpUtil { }
10.3
33
0.660194
923082a1cdf4626dc14ae5a4021aaccfffcc5a76
478
import java.util.Scanner; public class Binary { public static void main (String args []) { //variables Scanner input = new Scanner (System.in); //variables String binary; //Prompt user to enter a binary line System.out.println("Enter a binary line please:"); binary = input.next(); //Display the binary conversion to decimal System.out.println("Decimal number is: " + Integer.parseInt(binary , 2)); }//end of main method }//end of class
21.727273
75
0.67364
f0b06adb41451ec3bd5a9e2dbdbc7f18f5e93a85
13,707
/* */ package com.sun.jna.platform.win32.COM; /* */ /* */ import com.sun.jna.Native; /* */ import com.sun.jna.Pointer; /* */ import com.sun.jna.platform.win32.Guid; /* */ import com.sun.jna.platform.win32.Kernel32; /* */ import com.sun.jna.platform.win32.OaIdl; /* */ import com.sun.jna.platform.win32.Ole32; /* */ import com.sun.jna.platform.win32.OleAuto; /* */ import com.sun.jna.platform.win32.WTypes; /* */ import com.sun.jna.platform.win32.WinDef; /* */ import com.sun.jna.platform.win32.WinNT; /* */ import com.sun.jna.ptr.PointerByReference; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class TypeLibUtil /* */ { /* 56 */ public static final OleAuto OLEAUTO = OleAuto.INSTANCE; /* */ /* */ /* */ private ITypeLib typelib; /* */ /* */ /* 62 */ private WinDef.LCID lcid = Kernel32.INSTANCE.GetUserDefaultLCID(); /* */ /* */ /* */ /* */ /* */ private String name; /* */ /* */ /* */ /* */ /* */ private String docString; /* */ /* */ /* */ /* */ /* */ private int helpContext; /* */ /* */ /* */ /* */ private String helpFile; /* */ /* */ /* */ /* */ /* */ public TypeLibUtil(String clsidStr, int wVerMajor, int wVerMinor) { /* 87 */ Guid.CLSID.ByReference clsid = new Guid.CLSID.ByReference(); /* */ /* 89 */ WinNT.HRESULT hr = Ole32.INSTANCE.CLSIDFromString(clsidStr, clsid); /* 90 */ COMUtils.checkRC(hr); /* */ /* */ /* 93 */ PointerByReference pTypeLib = new PointerByReference(); /* 94 */ hr = OleAuto.INSTANCE.LoadRegTypeLib((Guid.GUID)clsid, wVerMajor, wVerMinor, this.lcid, pTypeLib); /* */ /* 96 */ COMUtils.checkRC(hr); /* */ /* */ /* 99 */ this.typelib = new TypeLib(pTypeLib.getValue()); /* */ /* 101 */ initTypeLibInfo(); /* */ } /* */ /* */ /* */ public TypeLibUtil(String file) { /* 106 */ PointerByReference pTypeLib = new PointerByReference(); /* 107 */ WinNT.HRESULT hr = OleAuto.INSTANCE.LoadTypeLib(file, pTypeLib); /* 108 */ COMUtils.checkRC(hr); /* */ /* */ /* 111 */ this.typelib = new TypeLib(pTypeLib.getValue()); /* */ /* 113 */ initTypeLibInfo(); /* */ } /* */ /* */ /* */ /* */ /* */ private void initTypeLibInfo() { /* 120 */ TypeLibDoc documentation = getDocumentation(-1); /* 121 */ this.name = documentation.getName(); /* 122 */ this.docString = documentation.getDocString(); /* 123 */ this.helpContext = documentation.getHelpContext(); /* 124 */ this.helpFile = documentation.getHelpFile(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public int getTypeInfoCount() { /* 133 */ return this.typelib.GetTypeInfoCount().intValue(); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public OaIdl.TYPEKIND getTypeInfoType(int index) { /* 144 */ OaIdl.TYPEKIND.ByReference typekind = new OaIdl.TYPEKIND.ByReference(); /* 145 */ WinNT.HRESULT hr = this.typelib.GetTypeInfoType(new WinDef.UINT(index), typekind); /* 146 */ COMUtils.checkRC(hr); /* 147 */ return (OaIdl.TYPEKIND)typekind; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public ITypeInfo getTypeInfo(int index) { /* 158 */ PointerByReference ppTInfo = new PointerByReference(); /* 159 */ WinNT.HRESULT hr = this.typelib.GetTypeInfo(new WinDef.UINT(index), ppTInfo); /* 160 */ COMUtils.checkRC(hr); /* 161 */ return new TypeInfo(ppTInfo.getValue()); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public TypeInfoUtil getTypeInfoUtil(int index) { /* 172 */ return new TypeInfoUtil(getTypeInfo(index)); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public OaIdl.TLIBATTR getLibAttr() { /* 181 */ PointerByReference ppTLibAttr = new PointerByReference(); /* 182 */ WinNT.HRESULT hr = this.typelib.GetLibAttr(ppTLibAttr); /* 183 */ COMUtils.checkRC(hr); /* */ /* 185 */ return new OaIdl.TLIBATTR(ppTLibAttr.getValue()); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public TypeComp GetTypeComp() { /* 194 */ PointerByReference ppTComp = new PointerByReference(); /* 195 */ WinNT.HRESULT hr = this.typelib.GetTypeComp(ppTComp); /* 196 */ COMUtils.checkRC(hr); /* */ /* 198 */ return new TypeComp(ppTComp.getValue()); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public TypeLibDoc getDocumentation(int index) { /* 209 */ WTypes.BSTRByReference pBstrName = new WTypes.BSTRByReference(); /* 210 */ WTypes.BSTRByReference pBstrDocString = new WTypes.BSTRByReference(); /* 211 */ WinDef.DWORDByReference pdwHelpContext = new WinDef.DWORDByReference(); /* 212 */ WTypes.BSTRByReference pBstrHelpFile = new WTypes.BSTRByReference(); /* */ /* 214 */ WinNT.HRESULT hr = this.typelib.GetDocumentation(index, pBstrName, pBstrDocString, pdwHelpContext, pBstrHelpFile); /* */ /* 216 */ COMUtils.checkRC(hr); /* */ /* */ /* */ /* 220 */ TypeLibDoc typeLibDoc = new TypeLibDoc(pBstrName.getString(), pBstrDocString.getString(), pdwHelpContext.getValue().intValue(), pBstrHelpFile.getString()); /* */ /* 222 */ OLEAUTO.SysFreeString(pBstrName.getValue()); /* 223 */ OLEAUTO.SysFreeString(pBstrDocString.getValue()); /* 224 */ OLEAUTO.SysFreeString(pBstrHelpFile.getValue()); /* */ /* 226 */ return typeLibDoc; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static class TypeLibDoc /* */ { /* */ private String name; /* */ /* */ /* */ /* */ /* */ /* */ private String docString; /* */ /* */ /* */ /* */ /* */ /* */ private int helpContext; /* */ /* */ /* */ /* */ /* */ /* */ private String helpFile; /* */ /* */ /* */ /* */ /* */ /* */ /* */ public TypeLibDoc(String name, String docString, int helpContext, String helpFile) { /* 262 */ this.name = name; /* 263 */ this.docString = docString; /* 264 */ this.helpContext = helpContext; /* 265 */ this.helpFile = helpFile; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getName() { /* 274 */ return this.name; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getDocString() { /* 283 */ return this.docString; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public int getHelpContext() { /* 292 */ return this.helpContext; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getHelpFile() { /* 301 */ return this.helpFile; /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public IsName IsName(String nameBuf, int hashVal) { /* 316 */ WTypes.LPOLESTR szNameBuf = new WTypes.LPOLESTR(nameBuf); /* 317 */ WinDef.ULONG lHashVal = new WinDef.ULONG(hashVal); /* 318 */ WinDef.BOOLByReference pfName = new WinDef.BOOLByReference(); /* */ /* 320 */ WinNT.HRESULT hr = this.typelib.IsName(szNameBuf, lHashVal, pfName); /* 321 */ COMUtils.checkRC(hr); /* */ /* 323 */ return new IsName(szNameBuf.getValue(), pfName.getValue() /* 324 */ .booleanValue()); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static class IsName /* */ { /* */ private String nameBuf; /* */ /* */ /* */ /* */ /* */ /* */ private boolean name; /* */ /* */ /* */ /* */ /* */ /* */ /* */ public IsName(String nameBuf, boolean name) { /* 349 */ this.nameBuf = nameBuf; /* 350 */ this.name = name; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getNameBuf() { /* 359 */ return this.nameBuf; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public boolean isName() { /* 368 */ return this.name; /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public FindName FindName(String name, int hashVal, short maxResult) { /* 384 */ Pointer p = Ole32.INSTANCE.CoTaskMemAlloc((name.length() + 1L) * Native.WCHAR_SIZE); /* 385 */ WTypes.LPOLESTR olestr = new WTypes.LPOLESTR(p); /* 386 */ olestr.setValue(name); /* */ /* 388 */ WinDef.ULONG lHashVal = new WinDef.ULONG(hashVal); /* 389 */ WinDef.USHORTByReference pcFound = new WinDef.USHORTByReference(maxResult); /* */ /* 391 */ Pointer[] ppTInfo = new Pointer[maxResult]; /* 392 */ OaIdl.MEMBERID[] rgMemId = new OaIdl.MEMBERID[maxResult]; /* 393 */ WinNT.HRESULT hr = this.typelib.FindName(olestr, lHashVal, ppTInfo, rgMemId, pcFound); /* */ /* 395 */ COMUtils.checkRC(hr); /* */ /* */ /* 398 */ FindName findName = new FindName(olestr.getValue(), ppTInfo, rgMemId, pcFound.getValue().shortValue()); /* */ /* 400 */ Ole32.INSTANCE.CoTaskMemFree(p); /* */ /* 402 */ return findName; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public static class FindName /* */ { /* */ private String nameBuf; /* */ /* */ /* */ /* */ /* */ /* */ private Pointer[] pTInfo; /* */ /* */ /* */ /* */ /* */ /* */ private OaIdl.MEMBERID[] rgMemId; /* */ /* */ /* */ /* */ /* */ private short pcFound; /* */ /* */ /* */ /* */ /* */ /* */ FindName(String nameBuf, Pointer[] pTInfo, OaIdl.MEMBERID[] rgMemId, short pcFound) { /* 436 */ this.nameBuf = nameBuf; /* 437 */ this.pTInfo = new Pointer[pcFound]; /* 438 */ this.rgMemId = new OaIdl.MEMBERID[pcFound]; /* 439 */ this.pcFound = pcFound; /* 440 */ System.arraycopy(pTInfo, 0, this.pTInfo, 0, pcFound); /* 441 */ System.arraycopy(rgMemId, 0, this.rgMemId, 0, pcFound); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getNameBuf() { /* 450 */ return this.nameBuf; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public ITypeInfo[] getTInfo() { /* 459 */ ITypeInfo[] values = new ITypeInfo[this.pcFound]; /* 460 */ for (int i = 0; i < this.pcFound; i++) /* */ { /* 462 */ values[i] = new TypeInfo(this.pTInfo[i]); /* */ } /* 464 */ return values; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public OaIdl.MEMBERID[] getMemId() { /* 473 */ return this.rgMemId; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public short getFound() { /* 482 */ return this.pcFound; /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public void ReleaseTLibAttr(OaIdl.TLIBATTR pTLibAttr) { /* 493 */ this.typelib.ReleaseTLibAttr(pTLibAttr); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public WinDef.LCID getLcid() { /* 502 */ return this.lcid; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public ITypeLib getTypelib() { /* 511 */ return this.typelib; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getName() { /* 520 */ return this.name; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getDocString() { /* 529 */ return this.docString; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public int getHelpContext() { /* 538 */ return this.helpContext; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ public String getHelpFile() { /* 547 */ return this.helpFile; /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/com/sun/jna/platform/win32/COM/TypeLibUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
24.697297
169
0.417597
dd2d8fcc79a76a739ad688529ce9317a8e11c471
231
package simulation.model.wrapping; import simulation.common.globals.SlotCurrentState; import simulation.common.globals.UpdaterBase; public abstract class SlotCurrentStateUpdater extends UpdaterBase<SlotCurrentState> { }
25.666667
86
0.82684
13dabab8e7a579274a5cb83c2d16892a8ba6ce0e
550
import java.util.Scanner; public class A1433 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); int val,to_add; while(t--!=0){ char[] goal = input.next().toCharArray(); val = Integer.parseInt(Character.toString(goal[0])); to_add = 10*(val - 1); for(int i =0;i<goal.length;i++){ to_add+=(i+1); } System.out.println(to_add); } input.close(); } }
27.5
64
0.494545
4bc6744fcda8541dbf82e3b0321d80dc0a235b20
1,478
package com.gaof.mvpdemo; import android.os.Bundle; import android.widget.ListView; import android.widget.Toast; import com.gaof.mvpdemo.adapter.GirlAdapter; import com.gaof.mvpdemo.base.BaseActivity; import com.gaof.mvpdemo.bean.Girl; import com.gaof.mvpdemo.contact.GirlContact; import com.gaof.mvpdemo.presenter.GirlPresenter; import com.gaof.mvpdemo.view.IGirlView; import java.util.List; public class MainActivity extends BaseActivity<GirlContact.View,GirlContact.Presenter> implements GirlContact.View{ private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView=findViewById(R.id.listView); // girlPresenter=new GirlPresenter<>(); // girlPresenter.attachView(this); mPresenter.fetch(); } @Override public GirlContact.Presenter createPresenter() { return new GirlPresenter(); } @Override public void showLoading() { Toast.makeText(this,"显示数据",Toast.LENGTH_SHORT).show(); } @Override public void dismissLoading() { } @Override public void showGirl(List<Girl> girls) { if(null!=girls){ GirlAdapter girlAdapter=new GirlAdapter(this,girls); listView.setAdapter(girlAdapter); } // listView.setAdapter(new ArrayAdapter<Girl>(this,android.R.layout.simple_list_item_1,girls)); } }
27.37037
115
0.70839
1372f5a4ef354f595829282b756c6519a6fe9a86
1,531
package indi.uhyils.rpc.netty; import indi.uhyils.rpc.enums.RpcTypeEnum; import indi.uhyils.rpc.exchange.pojo.data.RpcData; import indi.uhyils.rpc.exchange.pojo.head.RpcHeader; import indi.uhyils.rpc.exchange.pojo.data.RpcFactory; import indi.uhyils.rpc.exchange.pojo.data.RpcFactoryProducer; /** * @author uhyils <[email protected]> * @date 文件创建日期 2020年12月19日 10时22分 */ class TestTest { @org.junit.jupiter.api.Test void testRequest() throws Exception { RpcFactory build = RpcFactoryProducer.build(RpcTypeEnum.REQUEST); RpcHeader rpcHeader = new RpcHeader(); rpcHeader.setName("a"); rpcHeader.setValue("b"); assert build != null; RpcData getHeader = build.createByInfo(9L, null, new RpcHeader[]{rpcHeader}, "indi.uhyils.rpc.netty.RpcHeader", "1", "getHeader", "", "[]", "[]"); byte[] bytes = getHeader.toBytes(); RpcData byBytes = build.createByBytes(bytes); assert byBytes != null; } @org.junit.jupiter.api.Test void testResponse() throws Exception { RpcFactory build = RpcFactoryProducer.build(RpcTypeEnum.RESPONSE); RpcHeader rpcHeader = new RpcHeader(); rpcHeader.setName("a"); rpcHeader.setValue("b"); assert build != null; RpcData response = build.createByInfo(9L, new Object[]{(byte) 10}, new RpcHeader[]{rpcHeader}, "1", "{\"a\":\"b\"}"); byte[] bytes = response.toBytes(); RpcData byBytes = build.createByBytes(bytes); assert byBytes != null; } }
36.452381
154
0.662965
7f8e83ae37b7d883235ef4f4b7c5e0c2dbd8b2db
617
package com.skunk.acl; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.stereotype.Component; /** * 资源定义及其描述 * * @author walker * @date 2019.6.11 * @since 0.0.1 */ @Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Component @Inherited public @interface ResourceInfo { String type(); String description() default "未描述"; }
19.903226
58
0.768233
26bddd311a95dbad9e121853647e7d2a6460658c
4,007
/* * 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.dolphinscheduler.dao.mapper; import org.apache.dolphinscheduler.common.enums.ExecutionStatus; import org.apache.dolphinscheduler.common.enums.Flag; import org.apache.dolphinscheduler.dao.entity.ExecuteStatusCount; import org.apache.dolphinscheduler.dao.entity.TaskInstance; import org.apache.ibatis.annotations.Param; import java.util.Date; import java.util.List; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; /** * task instance mapper interface */ public interface TaskInstanceMapper extends BaseMapper<TaskInstance> { List<Integer> queryTaskByProcessIdAndState(@Param("processInstanceId") Integer processInstanceId, @Param("state") Integer state); List<TaskInstance> findValidTaskListByProcessId(@Param("processInstanceId") Integer processInstanceId, @Param("flag") Flag flag); List<TaskInstance> queryByHostAndStatus(@Param("host") String host, @Param("states") int[] stateArray); int setFailoverByHostAndStateArray(@Param("host") String host, @Param("states") int[] stateArray, @Param("destStatus") ExecutionStatus destStatus); TaskInstance queryByInstanceIdAndName(@Param("processInstanceId") int processInstanceId, @Param("name") String name); TaskInstance queryByInstanceIdAndCode(@Param("processInstanceId") int processInstanceId, @Param("taskCode") Long taskCode); Integer countTask(@Param("projectCodes") Long[] projectCodes, @Param("taskIds") int[] taskIds); List<ExecuteStatusCount> countTaskInstanceStateByUser(@Param("startTime") Date startTime, @Param("endTime") Date endTime, @Param("projectCodes") Long[] projectCodes); IPage<TaskInstance> queryTaskInstanceListPaging(IPage<TaskInstance> page, @Param("projectCode") Long projectCode, @Param("processInstanceId") Integer processInstanceId, @Param("processInstanceName") String processInstanceName, @Param("searchVal") String searchVal, @Param("taskName") String taskName, @Param("executorId") int executorId, @Param("states") int[] statusArray, @Param("host") String host, @Param("startTime") Date startTime, @Param("endTime") Date endTime ); List<TaskInstance> loadAllInfosNoRelease(@Param("processInstanceId") int processInstanceId,@Param("status") int status); }
50.721519
124
0.598203
1f9ad4f439247bdfbf8944b49641bd67f7e59c66
733
package com.fcgl.madrid.shopping.repository; import com.fcgl.madrid.shopping.dataModel.ShoppingList; import com.fcgl.madrid.shopping.payload.response.ShoppingListNoProduct; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; public interface ShoppingListRepository extends JpaRepository<ShoppingList, Long> { public List<ShoppingListNoProduct> findAllByUserIdOrderByCreatedDate(Long userId, Pageable pageable); public Optional<ShoppingList> findByActiveTrueAndUserId(Long userId); public Optional<ShoppingList> findByIdAndUserId(Long id, Long userId); }
40.722222
105
0.837653
d4b2fb42fc996573aa027445745f1c4d9c427d15
3,367
/* * Copyright 2020 Developer Gao. * * 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 tech.devgao.hailong.benchmarks; import static org.mockito.Mockito.mock; import com.google.common.eventbus.EventBus; import java.util.List; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import tech.devgao.hailong.benchmarks.gen.BlockIO; import tech.devgao.hailong.benchmarks.gen.BlockIO.Reader; import tech.devgao.hailong.benchmarks.gen.BlsKeyPairIO; import tech.devgao.hailong.datastructures.blocks.SignedBeaconBlock; import tech.devgao.hailong.datastructures.util.BeaconStateUtil; import tech.devgao.hailong.statetransition.BeaconChainUtil; import tech.devgao.hailong.statetransition.blockimport.BlockImportResult; import tech.devgao.hailong.statetransition.blockimport.BlockImporter; import tech.devgao.hailong.storage.ChainStorageClient; import tech.devgao.hailong.util.bls.BLSKeyPair; import tech.devgao.hailong.util.config.Constants; /** The test to be run manually for profiling block imports */ public class ProfilingRun { @Disabled @Test public void importBlocks() throws Exception { Constants.SLOTS_PER_EPOCH = 6; BeaconStateUtil.BLS_VERIFY_DEPOSIT = false; BeaconStateUtil.DEPOSIT_PROOFS_ENABLED = false; int validatorsCount = 1 * 1024; String blocksFile = "/blocks/blocks_epoch_" + Constants.SLOTS_PER_EPOCH + "_validators_" + validatorsCount + ".ssz.gz"; System.out.println("Generating keypairs..."); // List<BLSKeyPair> validatorKeys = BLSKeyGenerator.generateKeyPairs(validatorsCount); // List<BLSKeyPair> validatorKeys = // BlsKeyPairIO.createReaderWithDefaultSource().readAll(validatorsCount); List<BLSKeyPair> validatorKeys = BlsKeyPairIO.createReaderForResource("/bls-key-pairs/bls-key-pairs-100k-seed-0.txt.gz") .readAll(validatorsCount); EventBus localEventBus = mock(EventBus.class); ChainStorageClient localStorage = ChainStorageClient.memoryOnlyClient(localEventBus); BeaconChainUtil localChain = BeaconChainUtil.create(localStorage, validatorKeys, false); localChain.initializeStorage(); BlockImporter blockImporter = new BlockImporter(localStorage, localEventBus); System.out.println("Start blocks import from " + blocksFile); try (Reader blockReader = BlockIO.createResourceReader(blocksFile)) { for (SignedBeaconBlock block : blockReader) { long s = System.currentTimeMillis(); localChain.setSlot(block.getSlot()); BlockImportResult result = blockImporter.importBlock(block); System.out.println( "Imported block at #" + block.getSlot() + " in " + (System.currentTimeMillis() - s) + " ms: " + result); } } } }
39.151163
118
0.729136
260273ef2aed494461c0b4acabfad17f5d5cdec6
1,086
package com.nuofankj.socket.util; import com.alibaba.fastjson.JSON; import com.nuofankj.socket.manager.ChannelManager; import com.nuofankj.socket.manager.ChannelSession; import com.nuofankj.socket.proto.AbstractMessage; import io.netty.channel.Channel; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import java.util.Map; /** * @author xifanxiaxue * @date 2020/6/3 8:09 * @desc 协议推送工具 */ public class PacketSendUtil { /** * 给session推送协议 * * @param session * @param message */ public static void sendMessage(ChannelSession session, AbstractMessage message) { session.getChannel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message))); } public static void broadcastMessage(AbstractMessage message) { for (Map.Entry<Channel, ChannelSession> sessionEntry : ChannelManager.sessionMap.entrySet()) { ChannelSession targetSession = sessionEntry.getValue(); if (targetSession.isAuth()) { sendMessage(targetSession, message); } } } }
28.578947
102
0.701657
64faa6bbebde7b76c5f98afb1e855d5857aefaf4
219
package com.aganticsoft.phyxhidephotosandvideos.view.activity; import android.support.v7.app.AppCompatActivity; /** * Created by ttson * Date: 9/22/2017. */ public class BaseActivity extends AppCompatActivity { }
18.25
62
0.776256
c052bbbeb4643613cb66d5e7550e230db124a5eb
1,018
package au.com.digitalspider.biblegame.model; import org.apache.commons.lang3.StringUtils; public enum State { FREE(State.DESCRIPTION_FREE), SHOP(State.DESCRIPTION_SHOP), STUDY(State.DESCRIPTION_STUDY), VISIT(State.DESCRIPTION_VISIT); private static final String DESCRIPTION_FREE = ""; private static final String DESCRIPTION_SHOP = "is buying at the shops"; private static final String DESCRIPTION_STUDY = "is studing at the library"; private static final String DESCRIPTION_VISIT = "is visiting someone"; private String description; private State(String description) { this.description = description; } public String getDescription() { return description; } public static State parse(String value) throws IllegalArgumentException { if (StringUtils.isNotBlank(value)) { value = value.toUpperCase(); for (State state : State.values()) { if (state.name().equals(value)) { return state; } } } throw new IllegalArgumentException("State not valid: " + value); } }
26.102564
77
0.74165
25aeefc3c18cec3a1c691d345f0c28e3ca77796c
182
package com.cryo.entities; import java.util.Date; public interface CronJob { boolean checkTime(Date date, int dayOfWeek, int hour, int minute, int second); void run(); }
16.545455
82
0.714286
32d705f559508a0575a95d7d4abb1317bf8294cd
1,276
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.hardware.DcMotor; import org.junit.Before; import org.junit.Test; import static com.qualcomm.robotcore.hardware.DcMotorSimple.Direction.FORWARD; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Created by cdowling on 11/29/17. */ public class LeftWheelForwardActionTest { AutoBot bot; DcMotor leftMotor; RobotAction action; @Before public void setUp() { leftMotor = mock(DcMotor.class); bot = new AutoBot(); bot.leftMotor = leftMotor; action = new LeftWheelForwardAction(27); action.bot = bot; } @Test public void constructor_setsDuration() { assertThat(action.duration, is(27L)); } @Test public void beginState_setsDirection() { action.beginState(); verify(leftMotor).setDirection(FORWARD); } @Test public void beginState_setsPower() { action.beginState(); verify(leftMotor).setPower(0.75); } @Test public void endState_setPower() { action.endState(); verify(leftMotor).setPower(0.0); } }
23.2
78
0.677116
f3311e2b5f26e789a232923b53fc37f7f83ad4b6
2,395
package com.parthparekh.service; import com.mongodb.DB; import com.mongodb.Mongo; import com.parthparekh.api.Product; import com.parthparekh.api.ProductStatus; import com.parthparekh.service.cache.Cache; import com.parthparekh.service.cache.EhCacheImpl; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.net.UnknownHostException; /** * Utility functions for test * * @author: Parth Parekh **/ @Component public class TestUtils { private static final Logger logger = LoggerFactory.getLogger(TestUtils.class); @Autowired @Qualifier("defaultCache") private Cache cache; public Product createProduct() { Product product = new Product().setName("test product 1") .setDescription("test description 1") .setPrice(BigDecimal.ONE); return product; } public void clearDb() throws UnknownHostException { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("test"); db.getCollection("product").drop(); logger.info("mongoDb cleared"); } public void clearCache() { // assuming it's ehcache ((EhCacheImpl) cache).removeAll(); logger.info("cache cleared"); } public void validateProduct(Product product) { Assert.assertNotNull(product); Assert.assertNotNull(product.getId()); Assert.assertEquals("test product 1", product.getName()); Assert.assertEquals("test description 1", product.getDescription()); Assert.assertEquals(ProductStatus.ACTIVE, product.getStatus()); Assert.assertEquals(BigDecimal.ONE, product.getPrice()); } public void validateUpdatedProduct(Product expected, Product actual) { Assert.assertNotNull(expected); Assert.assertNotNull(actual); Assert.assertEquals(expected.getId(), actual.getId()); Assert.assertEquals(expected.getName(), actual.getName()); Assert.assertEquals(expected.getDescription(), actual.getDescription()); Assert.assertEquals(expected.getStatus(), actual.getStatus()); Assert.assertEquals(expected.getPrice(), actual.getPrice()); } }
34.214286
82
0.703549
6d97063666c0dba84ef19973b384abe9bb91cb05
851
package com.bilulo.androidtest04.data.model.response; import com.bilulo.androidtest04.data.model.ErrorModel; import com.bilulo.androidtest04.data.model.StatementModel; import com.google.gson.annotations.SerializedName; import java.util.List; public class StatementsResponse { @SerializedName("statementList") private List<StatementModel> statementModelList; @SerializedName("error") private ErrorModel errorModel; public List<StatementModel> getStatementModelList() { return statementModelList; } public void setStatementModelList(List<StatementModel> statementModelList) { this.statementModelList = statementModelList; } public ErrorModel getErrorModel() { return errorModel; } public void setErrorModel(ErrorModel errorModel) { this.errorModel = errorModel; } }
27.451613
80
0.750881
b8d5649d12a333f9515090557f6aeb65264c236b
393
package kwasilewski.marketplace.dto.hint; import java.util.List; public class CategoryData extends HintData { private List<HintData> subcategories; public CategoryData() { } public List<HintData> getSubcategories() { return subcategories; } public void setSubcategories(List<HintData> subcategories) { this.subcategories = subcategories; } }
18.714286
64
0.70229
00bfee0475ddc9f1cd203b0389fc205b6d712e7b
4,552
package com.xlsoft.publicsamples; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import eu.kudan.kudan.ARAPIKey; public class TitleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_title); requestPermissions(); // This key will only work when using the com.xlsoft.publicsamples (this app) application Id. ARAPIKey key = ARAPIKey.getInstance(); key.setAPIKey("fb5BokyKQbGvAtakUwuJqlJS8CDuRycSYR0P57E9GTRUPmgPtFyvUjsX79dHSo5KFKzJTppnBFpDsMbtotW+kD+vOQSylZ89EhW9O4SRubZmzSR8s8nZujfkTbi5DdItkXixWdDlQSmsWfWC9dX2lczQGbns83A81rQHUSm6J7EaxF8uL6yp6TyoBvSVHYBc0/XelYd39MwtP7txWZrQbmXMIDZsdzVkTM7I+HgwehzNkf9zjBVN6iuKopI+/5Q0p/X4JT2FmpzWFA/XY5mEJElk4T56BBAFm9ib7WrXOqAVcYgmHm7WL1K8BLIfa11mJMBMkOjoHQY8K865IKP1rbfqUrIifTS1MUQjVsHbQL6jQReYqqErqcEmYNFKw9CP99q+HEnV4liF0ikwVZaj16HLXPYzstGXmj1bPj574+AGY9aDX3ixSQoqI/Idx/fGMySPQXCFjxps19nMFaVY6lYG/rSiKhIKF+io2sFPFrL5DrRqb6Da9IeWGPCk6NOSW4RWVa+8pxItpCgyeY+doh4AkMTKgw0QOcrsZ/arww1jZqegdDlRpImJ07zUYDMJnsACD1N9wA4mG/VJ6Zpa7xoGFOerAvcBVT5ZjuxbtrjlnxZ4mJB6KRgEHJLbpw4NQZpbG3HcTeUM2+PMKSoXXuP4zXjVKLkK6STRGoAWlVc="); } public void startMarkerActivity(View view) { Intent intent = new Intent(this,MarkerActivity.class); if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { permissionsNotSelected(); requestPermissions(); } else { startActivity(intent); } } public void startMakerlessFloorActivity(View view) { Intent intent = new Intent(this,MarkerlessActivity.class); if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { permissionsNotSelected(); requestPermissions(); } else { startActivity(intent); } } public void startMarkerlessWallActivity(View view) { Intent intent = new Intent(this,Markerless_Wall.class); if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { permissionsNotSelected(); requestPermissions(); } else { startActivity(intent); } } public void startSimultaneousActivity(View view) { Intent intent = new Intent(this,SimultaneousDetectionActivity.class); if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { permissionsNotSelected(); requestPermissions(); } else { startActivity(intent); } } public void requestPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},111); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 111: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { permissionsNotSelected(); } } } } private void permissionsNotSelected() { Toast.makeText(this,"You must enable permissions in settings",Toast.LENGTH_LONG).show(); } }
37.933333
710
0.702768
ccfaac2fc40074d4903e1de6f8b7c4d5d160472c
1,855
package com.hys.exam.model; import java.io.Serializable; /** * * 标题:考试支撑平台 * * 作者:Tony 2010-12-13 * * 描述: * * 说明: 试题分类表 */ public class ExamQuestionType implements Serializable{ /** * */ private static final long serialVersionUID = -6848968524545630850L; /** * 分类ID */ private Long id; /** *父ID */ private Long parent_id; /** * 子系统ID */ private Long sub_sys_id; /** * 分类名称 */ private String name; /** * 分类code */ private String code; /** * 顺序 */ private Integer seq; /** * 状态 * 1正常 */ private Integer state; /** * 层级 */ private Integer layer; /** * 子节点数 */ private int childNum; /** * 备注 */ private String remark; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getParent_id() { return parent_id; } public void setParent_id(Long parentId) { parent_id = parentId; } public Long getSub_sys_id() { return sub_sys_id; } public void setSub_sys_id(Long subSysId) { sub_sys_id = subSysId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getSeq() { return seq; } public void setSeq(Integer seq) { this.seq = seq; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Integer getLayer() { return layer; } public void setLayer(Integer layer) { this.layer = layer; } public int getChildNum() { return childNum; } public void setChildNum(int childNum) { this.childNum = childNum; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
11.891026
68
0.620485
60c9cf2647468c3ec6c0a429af2c5bdee8a14ca8
4,070
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.type; import java.util.Map; import org.springframework.util.MultiValueMap; /** * Defines access to the annotations of a specific type ({@link AnnotationMetadata class} * or {@link MethodMetadata method}), in a form that does not necessarily require the * class-loading. * * @author Juergen Hoeller * @author Mark Fisher * @author Mark Pollack * @author Chris Beams * @author Phillip Webb * @since 4.0 * @see AnnotationMetadata * @see MethodMetadata */ public interface AnnotatedTypeMetadata { /** * Determine whether the underlying type has an annotation or * meta-annotation of the given type defined. * <p>If this method returns {@code true}, then * {@link #getAnnotationAttributes} will return a non-null Map. * @param annotationType the annotation type to look for * @return whether a matching annotation is defined */ boolean isAnnotated(String annotationType); /** * Retrieve the attributes of the annotation of the given type, * if any (i.e. if defined on the underlying class, as direct * annotation or as meta-annotation). * @param annotationType the annotation type to look for * @return a Map of attributes, with the attribute name as key (e.g. "value") * and the defined attribute value as Map value. This return value will be * {@code null} if no matching annotation is defined. */ Map<String, Object> getAnnotationAttributes(String annotationType); /** * Retrieve the attributes of the annotation of the given type, * if any (i.e. if defined on the underlying class, as direct * annotation or as meta-annotation). * @param annotationType the annotation type to look for * @param classValuesAsString whether to convert class references to String * class names for exposure as values in the returned Map, instead of Class * references which might potentially have to be loaded first * @return a Map of attributes, with the attribute name as key (e.g. "value") * and the defined attribute value as Map value. This return value will be * {@code null} if no matching annotation is defined. */ Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString); /** * Retrieve all attributes of all annotations of the given type, if any (i.e. if * defined on the underlying method, as direct annotation or as meta-annotation). * @param annotationType the annotation type to look for * @return a MultiMap of attributes, with the attribute name as key (e.g. "value") * and a list of the defined attribute values as Map value. This return value will * be {@code null} if no matching annotation is defined. */ MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType); /** * Retrieve all attributes of all annotations of the given type, if any (i.e. if * defined on the underlying method, as direct annotation or as meta-annotation). * @param annotationType the annotation type to look for * @param classValuesAsString whether to convert class references to String * @return a MultiMap of attributes, with the attribute name as key (e.g. "value") * and a list of the defined attribute values as Map value. This return value will * be {@code null} if no matching annotation is defined. * @see #getAllAnnotationAttributes(String) */ MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType, boolean classValuesAsString); }
41.958763
110
0.745946
9f0638bc3ee1ce3d938f02ebf6fb64305da2328b
2,925
/* * Copyright 2013-2017 Indiana University * * 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 edu.iu.kmeans.regroupallgather; import edu.iu.harp.partition.Partition; import edu.iu.harp.partition.Table; import edu.iu.harp.resource.DoubleArray; import edu.iu.harp.schdynamic.Task; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class CenCalcTask implements Task<double[], Object> { protected static final Log LOG = LogFactory.getLog(CenCalcTask.class); private double[][] centroids; private double[][] local; private final int cenVecSize; public CenCalcTask(Table<DoubleArray> cenTable, int cenVecSize) { centroids = new double[cenTable.getNumPartitions()][]; local = new double[centroids.length][]; for (Partition<DoubleArray> partition : cenTable .getPartitions()) { int partitionID = partition.id(); DoubleArray array = partition.get(); centroids[partitionID] = array.get(); local[partitionID] = new double[array.size()]; } this.cenVecSize = cenVecSize; } public void update(Table<DoubleArray> cenTable) { for (Partition<DoubleArray> partition : cenTable .getPartitions()) { int partitionID = partition.id(); DoubleArray array = partition.get(); centroids[partitionID] = array.get(); } } public double[][] getLocal() { return local; } @Override public Object run(double[] points) throws Exception { for (int i = 0; i < points.length;) { i++; double minDistance = Double.MAX_VALUE; int minCenParID = 0; int minOffset = 0; for (int j = 0; j < centroids.length; j++) { for (int k = 0; k < local[j].length;) { int pStart = i; k++; double distance = 0.0; for (int l = 1; l < cenVecSize; l++) { double diff = (points[pStart++] - centroids[j][k++]); distance += diff * diff; } if (distance < minDistance) { minDistance = distance; minCenParID = j; minOffset = k - cenVecSize; } } } // Count + 1 local[minCenParID][minOffset++]++; // Add the point for (int j = 1; j < cenVecSize; j++) { local[minCenParID][minOffset++] += points[i++]; } } return null; } }
28.676471
75
0.623248
e564fc1e5d7c9a8d4fbdca422e09d7569634733e
4,585
/******************************************************************************* * DARPA XDATA 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. * * Copyright 2013 Raytheon BBN Technologies Corp. All Rights Reserved. ******************************************************************************/ /* ============================================================================= * * COPYRIGHT 2010 BBN Technologies Corp. * 1300 North 17th Street, Suite 600 * Arlington, VA 22209 * (703) 284-1200 * * This program is the subject of intellectual property rights * licensed from BBN Technologies * * This legend must continue to appear in the source code * despite modifications or enhancements by any party. * * * ============================================================================== */ package com.bbn.c2s2.pint.pf.evaluators; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bbn.c2s2.pint.Binding; import com.bbn.c2s2.pint.pf.EvaluatedSolution; import com.bbn.c2s2.pint.pf.Solution; import com.bbn.c2s2.pint.pf.util.ContinuousSpatialViolationCalculator; import com.bbn.c2s2.pint.pf.util.SimpleComCalculator; import com.bbn.c2s2.pint.pf.util.ViolationRatios; /** * Evaluates potential process solutions and determines a score. * * @author tself * */ public class SolutionEvaluator { private static Logger logger = LoggerFactory .getLogger(SolutionEvaluator.class); protected static final int ScoreRange = 100; /** * Generate a list of {@link EvaluatedSolution}'s from a list of * {@link Solution}'s * * @param solutions * The {@link Solution}'s to evaluate * @return The list of {@link EvaluatedSolution}'s */ public static List<EvaluatedSolution> getEvaluatedList( List<Solution> solutions) { List<EvaluatedSolution> evalList = new ArrayList<EvaluatedSolution>(); for (Solution cs : solutions) { // get this solutions evaluation score double eval = evaluate(cs); EvaluatedSolution es = new EvaluatedSolution(cs, eval); if (null != es) { evalList.add(es); } } if (logger.isDebugEnabled()) { logger.debug("getEvaluatedList() generated a list of: " + evalList.size() + " evaluated solutions."); } return evalList; } /** * Evaluate the solution in order to assign a score of 1 to 100 The score * indicates the strength of the solution in terms of its minimization of * violations. Lower score indicates that the solution has more violations * than a higher scored solution. * * @param solution * The solution to evaluate * @return A representation of the solution's score (between 1 and 100) */ public static double evaluate(Solution solution) { double toReturn = -1.0; // get a reference to the set of non-null bindings for this solution Collection<Binding> bindings = solution.getNonNullBindings(); double[] center = SimpleComCalculator.getCenter(solution .getObservations()); double cumulativeScore = 0.0; for (Binding b : bindings) { // The spatial portion of the score double spatialScore = ContinuousSpatialViolationCalculator .evaluateBinding(center, b); // The temporal portion of the score double temporalScore = ViolationRatios.evaluateTemporalValidRatio( solution, b); // The product of the scores double product_eval = spatialScore * temporalScore; // add the score of this binding to the cumulative score for this // sln cumulativeScore += product_eval; } double weightedPerf = 1.0; if (solution.getProcess().size() > 0) { weightedPerf = cumulativeScore / (double) solution.getProcess().size(); } toReturn = ScoreRange * weightedPerf; if (logger.isDebugEnabled()) { logger.debug("evaluate() created a score of: " + toReturn + " for solution: " + solution.toString()); } return toReturn; } }
31.62069
81
0.650818
f660b94e55f45e99727bcf88aeb38a49cca94cf2
8,686
package com.acmezon.acmezon_dash; import android.graphics.Point; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import com.dev.sacot41.scviewpager.DotsView; import com.dev.sacot41.scviewpager.SCPositionAnimation; import com.dev.sacot41.scviewpager.SCViewAnimation; import com.dev.sacot41.scviewpager.SCViewAnimationUtil; import com.dev.sacot41.scviewpager.SCViewPager; import com.dev.sacot41.scviewpager.SCViewPagerAdapter; public class AboutUs extends FragmentActivity { private static final int NUM_PAGES = 5; private DotsView mDotsView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_aboutus); SCViewPager mViewPager = (SCViewPager) findViewById(R.id.viewpager_main_activity); mDotsView = (DotsView) findViewById(R.id.dotsview_main); mDotsView.setDotRessource(R.drawable.dot_selected, R.drawable.dot_unselected); mDotsView.setNumberOfPage(NUM_PAGES); SCViewPagerAdapter mPageAdapter = new SCViewPagerAdapter(getSupportFragmentManager()); mPageAdapter.setNumberOfPage(NUM_PAGES); mPageAdapter.setFragmentBackgroundColor(R.color.theme_100); mViewPager.setAdapter(mPageAdapter); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mDotsView.selectDot(position); } @Override public void onPageScrollStateChanged(int state) { } }); final Point size = SCViewAnimationUtil.getDisplaySize(this); View nameTag = findViewById(R.id.imageview_main_activity_name_tag); SCViewAnimation nameTagAnimation = new SCViewAnimation(nameTag); nameTagAnimation.addPageAnimation(new SCPositionAnimation(this, 0,0,-size.y/2)); mViewPager.addAnimation(nameTagAnimation); View thisis = findViewById(R.id.imageview_thisis); SCViewAnimation thisiskAnimation = new SCViewAnimation(thisis); thisiskAnimation.addPageAnimation(new SCPositionAnimation(this, 0, -size.x, 0)); mViewPager.addAnimation(thisiskAnimation); View acmes = findViewById(R.id.imageview_acmesupermarket); SCViewAnimationUtil.prepareViewToGetSize(acmes); SCViewAnimation acmesAnimation = new SCViewAnimation(acmes); acmesAnimation.addPageAnimation(new SCPositionAnimation(getApplicationContext(), 0, 0, -( size.y*2 - acmes.getHeight() ))); acmesAnimation.addPageAnimation(new SCPositionAnimation(getApplicationContext(), 1, -size.x, 0)); mViewPager.addAnimation(acmesAnimation); View mobileView = findViewById(R.id.imageview_mobile); SCViewAnimation mobileAnimation = new SCViewAnimation(mobileView); mobileAnimation.startToPosition((int)(size.x*1.5), null); mobileAnimation.addPageAnimation(new SCPositionAnimation(this, 0, -(int)(size.x*1.5), 0)); mobileAnimation.addPageAnimation(new SCPositionAnimation(this, 1, -(int)(size.x*1.5), 0)); mViewPager.addAnimation(mobileAnimation); View techs = findViewById(R.id.imageview_techs); SCViewAnimation techsAnimation = new SCViewAnimation(techs); techsAnimation.startToPosition(null, -size.y); techsAnimation.addPageAnimation(new SCPositionAnimation(this, 0, 0, size.y)); techsAnimation.addPageAnimation(new SCPositionAnimation(this, 1, 0, size.y)); mViewPager.addAnimation(techsAnimation); View appMade = findViewById(R.id.imageview_app_made); SCViewAnimation appMadeAnimation = new SCViewAnimation(appMade); appMadeAnimation.startToPosition(size.x, null); appMadeAnimation.addPageAnimation(new SCPositionAnimation(this, 0, -size.x, 0)); appMadeAnimation.addPageAnimation(new SCPositionAnimation(this, 1, -size.x, 0)); mViewPager.addAnimation(appMadeAnimation); View acad = findViewById(R.id.imageview_acad); SCViewAnimation acadAnimation = new SCViewAnimation(acad); acadAnimation.startToPosition(size.x, null); acadAnimation.addPageAnimation(new SCPositionAnimation(this, 1, -size.x,0)); acadAnimation.addPageAnimation(new SCPositionAnimation(this, 2, -size.x,0)); mViewPager.addAnimation(acadAnimation); View diplomeView = findViewById(R.id.imageview_diploma); SCViewAnimation diplomeAnimation = new SCViewAnimation(diplomeView); diplomeAnimation.startToPosition((size.x *2), null); diplomeAnimation.addPageAnimation(new SCPositionAnimation(this, 1, -size.x*2,0)); diplomeAnimation.addPageAnimation(new SCPositionAnimation(this, 2, -size.x*2 ,0)); mViewPager.addAnimation(diplomeAnimation); View sedu = findViewById(R.id.imageview_sedu); SCViewAnimation seduAnimation = new SCViewAnimation(sedu); seduAnimation.startToPosition(null, -size.y); seduAnimation.addPageAnimation(new SCPositionAnimation(this, 2, 0, size.y)); seduAnimation.addPageAnimation(new SCPositionAnimation(this, 3, -size.x, 0)); mViewPager.addAnimation(seduAnimation); View arduinoView = findViewById(R.id.imageview_main_arduino); SCViewAnimation arduinoAnimation = new SCViewAnimation(arduinoView); arduinoAnimation.startToPosition(size.x * 2, null); arduinoAnimation.addPageAnimation(new SCPositionAnimation(this, 2, - size.x *2, 0)); arduinoAnimation.addPageAnimation(new SCPositionAnimation(this, 3, - size.x, 0)); mViewPager.addAnimation(arduinoAnimation); View raspberryView = findViewById(R.id.imageview_main_raspberry_pi); SCViewAnimation raspberryAnimation = new SCViewAnimation(raspberryView); raspberryAnimation.startToPosition(-size.x, null); raspberryAnimation.addPageAnimation(new SCPositionAnimation(this, 2, size.x, 0)); raspberryAnimation.addPageAnimation(new SCPositionAnimation(this, 3, -size.x, 0)); mViewPager.addAnimation(raspberryAnimation); View nucleoView = findViewById(R.id.imageview_nucleo); SCViewAnimation nucleoAnimation = new SCViewAnimation(nucleoView); nucleoAnimation.startToPosition((int)(size.x *1.5), null); nucleoAnimation.addPageAnimation(new SCPositionAnimation(this, 2, -(int) (size.x * 1.5), 0)); nucleoAnimation.addPageAnimation(new SCPositionAnimation(this, 3, - size.x, 0)); mViewPager.addAnimation(nucleoAnimation); View checkOutView = findViewById(R.id.imageview_main_check_out); SCViewAnimation checkOutAnimation = new SCViewAnimation(checkOutView); checkOutAnimation.startToPosition(size.x, null); checkOutAnimation.addPageAnimation(new SCPositionAnimation(this, 3, -size.x, 0)); mViewPager.addAnimation(checkOutAnimation); View dandeleaLink = findViewById(R.id.textview_dandelea_link); SCViewAnimation dandeleaAnimation = new SCViewAnimation(dandeleaLink); dandeleaAnimation.startToPosition(size.x, null); dandeleaAnimation.addPageAnimation(new SCPositionAnimation(this, 3, -size.x, 0)); mViewPager.addAnimation(dandeleaAnimation); View alesanmedLink = findViewById(R.id.textview_alesanmed_link); SCViewAnimation alesanmedAnimation = new SCViewAnimation(alesanmedLink); alesanmedAnimation.startToPosition(size.x, null); alesanmedAnimation.addPageAnimation(new SCPositionAnimation(this, 3, -size.x, 0)); mViewPager.addAnimation(alesanmedAnimation); View buttonBack = findViewById(R.id.button_back_aboutus); SCViewAnimation backAnimation = new SCViewAnimation(buttonBack); backAnimation.startToPosition(size.x, null); backAnimation.addPageAnimation(new SCPositionAnimation(this, 3, -size.x, 0)); mViewPager.addAnimation(backAnimation); Button back = (Button) buttonBack; back.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
49.634286
131
0.726111
52183fd97dbf86462a781eb9ddf6a2fe0f424ea2
4,504
package vrpsim.core.model.structure.storage; import java.util.List; import vrpsim.core.model.structure.storage.impl.CanStoreType; import vrpsim.core.model.structure.storage.impl.StorableParameters; import vrpsim.core.model.structure.storage.impl.StorableType; import vrpsim.core.model.util.exceptions.StorageException; import vrpsim.core.model.util.exceptions.VRPArithmeticException; public interface ICanStoreManager { /** * Returns true if the storage still has place for the given capacity. * * @param storableType * @param number * @return * @throws VRPArithmeticException */ public boolean canLoad(StorableParameters storableParameters, int number); /** * Returns true if the storage provides the given capacity. * * @param storableType * @param numberToStoreFromStorableType * @return * @throws VRPArithmeticException */ public boolean canUnload(StorableParameters storableParameters, int number); /** * Loads one {@link IStorable} into the storage. * * @param storable * @throws VRPArithmeticException * @throws StorageException */ public void load(IStorable storable) throws StorageException; /** * Loads the given {@link IStorable} into the storage. * * @param storable * @throws VRPArithmeticException * @throws StorageException */ public void load(List<IStorable> storables) throws StorageException; /** * Loads the given number into the storage. * * @param storable * @throws VRPArithmeticException * @throws StorageException */ public void load(StorableParameters storableParameters, int number) throws StorageException; /** * Remove and returns one {@link IStorable} with given * {@link StorableParameters} from the storage. * * @param storableType * @return * @throws StorageException */ public IStorable unload(StorableParameters storableParameters) throws StorageException; /** * Remove and returns one {@link IStorable} with given * {@link StorableParameters} from the storage. * * @param storableType * @return * @throws StorageException */ public List<IStorable> unload(StorableParameters storableParameters, int number) throws StorageException; /** * Returns the current available capacity of the given * {@link StorableParameters}. * * @param storableType * @return * @throws VRPArithmeticException */ public double getCurrentCapacity(StorableParameters storableParameters); /** * Returns the capacity left for the given {@link StorableParameters}. * * @param storableParameters * @return */ public double getFreeCapacity(StorableParameters storableParameters); /** * Returns the unused capacity of the {@link ICanStore} defined by given * {@link CanStoreType}. * * @param canStoreType * @return * @throws VRPArithmeticException */ public double getFreeCapacity(CanStoreType canStoreType, StorableParameters storableParameters); /** * Returns the unused capacity of the {@link ICanStore} defined by given * {@link CanStoreType} independent from {@link StorableParameters}. * * @param canStoreType * @return */ public double getFreeCapacity(CanStoreType canStoreType); /** * Returns the unused capacity of the {@link ICanStore} defined by given * {@link CanStoreType}. * * @param canStoreType * @return * @throws VRPArithmeticException */ public double getMaxCapacity(CanStoreType canStoreType); /** * Returns the current capacity of {@link IStorable} in {@link ICanStore} defined * by given {@link CanStoreType} and the {@link StorableParameters}. * * Note, that the returned value is calculated independent from * {@link StorableType}. Example: if in the {@link ICanStore} are one * {@link IStorable} from type {@link StorableType} 'apple' and another * {@link IStorable} from type {@link StorableType} 'cucumber', the method * returns two. * * @param canStoreType * @return * @throws VRPArithmeticException */ public double getCurrentCapacity(CanStoreType canStoreType, StorableParameters storableParameters); /** * Returns the current capacity of {@link IStorable} in {@link ICanStore} defined * by given {@link CanStoreType} independent from {@link StorableParameters}. * * @param canStoreType * @return */ public double getCurrentCapacity(CanStoreType canStoreType); /** * Returns a list of all {@link CanStoreType}. * * @return */ public List<CanStoreType> getAllCanStoreTypes(); public void reset(); }
27.802469
106
0.733792
a7e954ba0c8c00123314d1b8023a7f63337aa134
797
import com.hazelcast.config.Config; import com.hazelcast.config.QueueConfig; public class QueueConfiguration { public static void main( String[] args ) throws Exception { //tag::queueconf[] Config config = new Config(); QueueConfig queueConfig = config.getQueueConfig("default"); queueConfig.setName("MyQueue") .setBackupCount(1) .setMaxSize(0) .setStatisticsEnabled(true) .setSplitBrainProtectionName("splitbrainprotectionname"); queueConfig.getQueueStoreConfig() .setEnabled(true) .setClassName("com.hazelcast.QueueStoreImpl") .setProperty("binary", "false"); config.addQueueConfig(queueConfig); //end::queueconf[] } }
37.952381
73
0.619824
02128a1c67c5a6ecfec7bd723c622fbeef7a32fd
599
package io.github.mortuusars.chalk.utils; import io.github.mortuusars.chalk.config.CommonConfig; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; public class DrawingUtils { public static boolean isGlowingItem(Item item){ ResourceLocation itemRegistryName = item.getRegistryName(); if (itemRegistryName == null) return false; for (String itemName : CommonConfig.GLOWING_ITEMS.get()) { if (itemRegistryName.toString().equals(itemName)) return true; } return false; } }
27.227273
67
0.682805
bf82c0ed9d772a05a4f7bb827732a6e29cb0a5a4
877
/** * */ package org.yinyayun.prediction.k3.bayes; /** * @author yinyayun * */ public class OutPutProbability implements Comparable<OutPutProbability> { private int out; private float probability; public OutPutProbability(int out, float probability) { super(); this.out = out; this.probability = probability; } /** * @return the out */ public int getOut() { return out; } /** * @return the probability */ public float getProbability() { return probability; } @Override public int compareTo(OutPutProbability o) { if (o.probability > probability) { return 1; } else if (o.probability < probability) { return -1; } return 0; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "OutPutProbability [out=" + out + ", probability=" + probability + "]"; } }
15.945455
80
0.646522
41301a030385370195caef065852e29a53eefa65
9,820
/* * 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.netbeans.junit.diff; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.netbeans.junit.NbTestCase; /** * * @author Jan Lahoda, ehucka */ public class LineDiffTest extends NbTestCase { public LineDiffTest(String testName) { super(testName); } protected void setUp() throws Exception { } protected void tearDown() throws Exception { } private void doOutputToFile(File f, String content) throws IOException { content = content.replaceAll("\n", System.getProperty("line.separator")); Writer w = new FileWriter(f); try { w.write(content); } finally { w.close(); } } private String getFileContent(File f) throws IOException { BufferedReader br = new BufferedReader(new FileReader(f)); char[] buffer = new char[1024]; int read = br.read(buffer); String t = new String(buffer, 0, read); String ls = System.getProperty("line.separator"); return t.replace(ls, "\n"); } public void testSimple() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); doOutputToFile(test1, "a\nb\nc\nd\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertFalse(diff.diff(test1, test2, null)); } public void testEmpty1() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); doOutputToFile(test1, "a\nb\nc\nd\n"); doOutputToFile(test2, ""); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, null)); } public void testEmpty2() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); doOutputToFile(test1, ""); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, null)); } public void testIgnoreCase() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); doOutputToFile(test1, "A\nb\nC\nd\n"); doOutputToFile(test2, "a\nB\nc\nD\n"); LineDiff diff = new LineDiff(true); assertFalse(diff.diff(test1, test2, null)); } public void testIgnoreEmptyLines() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); doOutputToFile(test1, "a\n\nb\n\nc\n\n\nd\n\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(false, true); assertFalse(diff.diff(test1, test2, null)); } public void testDiff1() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\nb\nc\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 a\n 2 b\n 3 c\n 4 - d\n", getFileContent(test3)); } public void testDiff2() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "b\nc\nd\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 - a\n 2 b\n 3 c\n 4 d\n", getFileContent(test3)); } public void testDiff3() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\nb\nb\nc\nc\nc\nb\nd\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 a\n 2 b\n + b\n 3 c\n + c\n + c\n + b\n 4 d\n", getFileContent(test3)); } public void testDiff4() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\nb\nb\nd\na\nb\nd\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 a\n 2 b\n 3 - c\n + b\n 4 d\n + a\n + b\n + d\n", getFileContent(test3)); } public void testDiff5() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "0\na\nb\nc\nd\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" + 0\n 1 a\n 2 b\n 3 c\n", getFileContent(test3)); } public void testDiff6() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\nb\nc\nd\ne\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 2 b\n 3 c\n 4 d\n + e\n", getFileContent(test3)); } public void testDiff7() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "e\nf\ng\nh\n"); doOutputToFile(test2, "a\nb\nc\nd\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 - a\n + e\n 2 - b\n + f\n 3 - c\n + g\n 4 - d\n + h\n", getFileContent(test3)); } public void testDiff8() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\ne\nc\nd\n\nf\n"); doOutputToFile(test2, "a\nb\n\nc\nd\nf\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 a\n 2 - b\n + e\n 3 - \n 4 c\n 5 d\n + \n 6 f\n", getFileContent(test3)); } public void testDiff9() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\nx\nc\nd\nb\nf\n"); doOutputToFile(test2, "a\nb\nc\nd\nb\nf\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 a\n + x\n 2 - b\n 3 c\n 4 d\n 5 b\n", getFileContent(test3)); } public void testDiff10() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); doOutputToFile(test1, "a\nx\nc\nd\nx\ny\n"); doOutputToFile(test2, "a\nb\nc\nd\nx\ny\n"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 1 a\n 2 - b\n + x\n 3 c\n 4 d\n 5 x\n", getFileContent(test3)); } public void testDiff11() throws Exception { File test1 = new File(getWorkDir(), "test1"); File test2 = new File(getWorkDir(), "test2"); File test3 = new File(getWorkDir(), "test3"); try { doOutputToFile(test1, "a\nx\nc\nd\nx\ny\n"); doOutputToFile(test2, "a\nb\nc\nd\nx\ny\n"); System.setProperty("nbjunit.linediff.context", "0"); LineDiff diff = new LineDiff(); assertTrue(diff.diff(test1, test2, test3)); assertEquals(" 2 - b\n + x\n", getFileContent(test3)); } finally { System.setProperty("nbjunit.linediff.context", ""); } } }
36.641791
112
0.575153
33fc153120ea10c1f3c40b7d8ccce4073b2d3b46
3,913
/* * DISCLAIMER * * 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.c8db.model; /** * */ public class DocumentReplaceOptions { private Boolean waitForSync; private Boolean ignoreRevs; private String ifMatch; private Boolean returnNew; private Boolean returnOld; private Boolean silent; private String streamTransactionId; public DocumentReplaceOptions() { super(); } public Boolean getWaitForSync() { return waitForSync; } /** * @param waitForSync Wait until document has been synced to disk. * @return options */ public DocumentReplaceOptions waitForSync(final Boolean waitForSync) { this.waitForSync = waitForSync; return this; } public Boolean getIgnoreRevs() { return ignoreRevs; } /** * @param ignoreRevs By default, or if this is set to true, the _rev attributes * in the given document is ignored. If this is set to false, * then the _rev attribute given in the body document is taken * as a precondition. The document is only replaced if the * current revision is the one specified. * @return options */ public DocumentReplaceOptions ignoreRevs(final Boolean ignoreRevs) { this.ignoreRevs = ignoreRevs; return this; } public String getIfMatch() { return ifMatch; } /** * @param ifMatch replace a document based on target revision * @return options */ public DocumentReplaceOptions ifMatch(final String ifMatch) { this.ifMatch = ifMatch; return this; } public Boolean getReturnNew() { return returnNew; } /** * @param returnNew Return additionally the complete new document under the * attribute new in the result. * @return options */ public DocumentReplaceOptions returnNew(final Boolean returnNew) { this.returnNew = returnNew; return this; } public Boolean getReturnOld() { return returnOld; } /** * @param returnOld Return additionally the complete previous revision of the * changed document under the attribute old in the result. * @return options */ public DocumentReplaceOptions returnOld(final Boolean returnOld) { this.returnOld = returnOld; return this; } public Boolean getSilent() { return silent; } /** * @param silent If set to true, an empty object will be returned as response. * No meta-data will be returned for the created document. This * option can be used to save some network traffic. * @return options */ public DocumentReplaceOptions silent(final Boolean silent) { this.silent = silent; return this; } public String getStreamTransactionId() { return streamTransactionId; } /** * @param streamTransactionId If set, the operation will be executed within the * transaction. * @return options * @since ArangoDB 3.5.0 */ public DocumentReplaceOptions streamTransactionId(final String streamTransactionId) { this.streamTransactionId = streamTransactionId; return this; } }
28.355072
89
0.635829
430916bb26960f9dd5631fa1a469bef8702c1357
3,818
package test.sort; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import static test.sort.DataUtil.*; public class FuncTest { @org.junit.Test public void testGenerateAndSort1Kb() throws Exception { final int threads = Runtime.getRuntime().availableProcessors(); final Path pathIn = Paths.get("OneKb.bin"); final Path pathOut = Paths.get("OneKb.sorted.bin"); final Path pathAux = Paths.get("OneKb.aux.bin");; final int chunkSize = 128; generateAndSort(SIZE_1Kb, threads, pathIn, pathOut, pathAux, chunkSize); } @org.junit.Test public void testGenerateAndSort1Mb() throws Exception { final int threads = Runtime.getRuntime().availableProcessors(); final Path pathIn = Paths.get("OneMb.bin"); final Path pathOut = Paths.get("OneMb.sorted.bin"); final Path pathAux = Paths.get("OneMb.aux.bin");; final int chunkSize = 128 * 1024; generateAndSort(SIZE_1Mb, threads, pathIn, pathOut, pathAux, chunkSize); } @org.junit.Test public void testGenerateAndSort10Mb() throws Exception { final int threads = Runtime.getRuntime().availableProcessors(); final Path pathIn = Paths.get("One10Mb.bin"); final Path pathOut = Paths.get("One10Mb.sorted.bin"); final Path pathAux = Paths.get("One10Mb.aux.bin");; final int chunkSize = 1024 * 1024; generateAndSort(SIZE_1Mb * 10, threads, pathIn, pathOut, pathAux, chunkSize); } //result: // - env: old MackBook Air, CPU: 4core, JDK 1.8.0_20 // - file size: 1Gb, chuck size: 32Mb // - sort time: 1m 58s @org.junit.Test // public void testGenerateAndSort1Gb() throws Exception { // final int threads = Runtime.getRuntime().availableProcessors(); // final Path pathIn = Paths.get("OneGb.bin"); // final Path pathOut = Paths.get("OneGb.sorted.bin"); // final Path pathAux = Paths.get("OneGb.aux.bin");; // final int chunkSize = 32 * 1024 * 1024; // // generateAndSort(SIZE_1Gb, threads, pathIn, pathOut, pathAux, chunkSize); // } private void generateAndSort(int sizeInKb, int threads, Path pathIn, Path pathOut, Path pathAux, int chunkSize) throws IOException { if (!Files.exists(pathIn)) { DataUtil.generateArrayWithZeroSum(pathIn, sizeInKb); } // check that generated array is not sorted try { DataUtil.checkArrayWithZeroSum(pathIn); fail(); } catch (AssertionError correct) {} // sort and check that output files is sorted Main.sort(threads, chunkSize, pathIn, pathOut, pathAux); DataUtil.checkArrayWithZeroSum(pathOut); Files.delete(pathIn); Files.delete(pathOut); Files.delete(pathAux); } @org.junit.Test public void testGenerateAndSortSimple() throws Exception { final int threads = Runtime.getRuntime().availableProcessors(); final Path pathIn = Paths.get("Simple.bin"); final Path pathOut = Paths.get("Simple.sorted.bin"); final Path pathAux = Paths.get("Simple.aux.bin");; final int chunkSize = 1024 * 1024; if (!Files.exists(pathIn)) { DataUtil.generateSimpleArray(pathIn); } Main.sort(threads, chunkSize, pathIn, pathOut, pathAux); int[] tmp = {1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4}; int[] arr = DataUtil.readArray(pathOut); assertArrayEquals(tmp, arr); Files.delete(pathIn); Files.delete(pathOut); Files.delete(pathAux); } }
36.018868
85
0.630959
7dfd082feb0c031b6a58ef5abfa08ad2d770727e
530
package com.br.distanceCities.enums; import javax.ws.rs.core.MediaType; public enum ReturnType { XML(MediaType.APPLICATION_XML), JSON(MediaType.APPLICATION_JSON); private String type; ReturnType(String type){ this.type = type; } public String type(){ return type; } public static ReturnType fromName(final String name) { for (ReturnType s : ReturnType.values()) { if (s.name().equalsIgnoreCase(name)) { return s; } } return null; } }
17.666667
58
0.620755
cd705b906e6ea40e09f9d474af5bd758a9783ae4
394
package de.adorsys.xs2a.adapter.mapper; import de.adorsys.xs2a.adapter.model.AccountReportTO; import de.adorsys.xs2a.adapter.service.model.AccountReport; import org.mapstruct.Mapper; @Mapper(uses = {TransactionsMapper.class}) public interface AccountReportMapper { AccountReportTO toAccountReportTO(AccountReport accountReport); AccountReport toAccountReport(AccountReportTO to); }
28.142857
67
0.822335
98d24a3e9ce1179e79756f7cdf4497acd2c7df6b
2,625
/** * Copyright (C) 2009-2016 Simonsoft Nordic AB * * 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 se.simonsoft.cms.indexing.abx; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.repos.indexing.IndexingDoc; import se.repos.indexing.IndexingItemHandler; import se.repos.indexing.item.HandlerPathinfo; import se.repos.indexing.item.HandlerProperties; import se.repos.indexing.item.IndexingItemProgress; public class HandlerTitleSelection implements IndexingItemHandler{ private static final String TITLE_FIELD = "title"; private static final Logger logger = LoggerFactory.getLogger(HandlerTitleSelection.class); private Set<String> fieldTitleKeys = new LinkedHashSet<String>(); /*** * Constructor populates a set with possible title properties keys. */ public HandlerTitleSelection() { super(); fieldTitleKeys.add("prop_cms.title"); fieldTitleKeys.add("embd_xml_a_cms.title"); // cms-indexing-xml - namespaced attribute fieldTitleKeys.add("embd_xml_title"); // cms-indexing-xml fieldTitleKeys.add("embd_title"); // Tika fieldTitleKeys.add("xmp_dc.title"); fieldTitleKeys.add("xmp_dc.subject"); fieldTitleKeys.add("xmp_dc.description"); } /*** * Looks after possible title values with given keys. The first hit will be indexed. * The order of the set decides the priority. */ @Override public void handle(IndexingItemProgress progress) { IndexingDoc doc = progress.getFields(); for(String key: this.fieldTitleKeys) { if(doc.containsKey(key)){ String value = doc.getFieldValues(key).iterator().next().toString(); if(value != null && !value.trim().equals("")) { doc.setField(TITLE_FIELD, value); logger.info("Indexing value from {}: \"{}\"", key, value); break; } } } } @SuppressWarnings("serial") @Override public Set<Class<? extends IndexingItemHandler>> getDependencies() { return new HashSet<Class<? extends IndexingItemHandler>>() {{ add(HandlerPathinfo.class); add(HandlerProperties.class); }}; } }
32.8125
91
0.737143
31ba080d49b67cb79a1565f8e94952ff3d9829a4
21,768
// SLDiagram.java // // Part of DAVE-ML utility suite, written by Bruce Jackson, NASA LaRC // <[email protected]> // Visit <http://daveml.org> for more info. // Latest version can be downloaded from http://dscb.larc.nasa.gov/Products/SW/DAVEtools.html // Copyright (c) 2007 United States Government as represented by LAR-17460-1. No copyright is // claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. package gov.nasa.daveml.dave2sl; import gov.nasa.daveml.dave.*; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Iterator; /** * * Helps generate Simulink diagram of DAVE model. * * <p> * The SLDiagram consists of a rectangular grid of cells, arranged * as rows and columns. A simulink block can be contained in a cell, * or a cell may be empty. Each cell can contain a single output * signal and zero or more input signals. Running below each row and * to the left of each column is space for zero or more signal lines * connected inputs and outputs. * *<p> * Modification history: * <ul> * <li>020619: Written EBJ</li> * <li>031220: Substantially modified for DAVE_tools 0.4</li> * <li>040225: Modified for 0.4 EBJ</li> * <li>040515: Added warnOnClip flag for X-37 ALTV model EBJ</li> * <li>040520: Added resetOuputsWhenDisabled, makeLib and makeEnabledSubSys flags EBJ</li> * </ul> * * @author Bruce Jackson {@link <mailto:[email protected]>} * @version 0.9 * **/ public class SLDiagram { /** * Our parent model */ Model model; /** * rows in our diagram */ ArrayList<SLRowColumnVector> rows; /** * columns in our diagram */ ArrayList<SLRowColumnVector> cols; /** * individual cells of our diagram */ ArrayList<SLCell> cells; /** * SLBlocks representing underlying Blocks */ ArrayList<SLBlock> slblockList; /** * input block names in seq as they are created in SLBLock */ ArrayList<String> inputNames; /** * output block names in seq; use for validation script */ ArrayList<String> outputNames; /** * if set, become chatty */ boolean verboseFlag; /** * which version of Simulink to write */ double SLversion; /** * tell Simulink to warn when table input exceeds bounds */ boolean warnOnClip; /** * tell Simulink to set disabled block outputs to zero */ boolean resetOutputsWhenDisabled; /** * generate a Library, not a Model */ boolean makeLib; /** * make the subsystem an enabled subsystem */ boolean makeEnabledSubSys; // Diagram layout parameters /** * padding between block and cell edge (diagram layout parameter) */ static int padding = 5; /** * distance from left edge of window (diagram layout parameter) */ static int xMargin = 10; /** * distance from top edge of window (diagram layout parameter) */ static int yMargin = 10; /** * * Constructor for SLDiagram. * * <p> * When called, the provided <code>Model</code> should contain * a completed, wired network with no dangling lines. Ultimately * this constructor will figure out placement; for now, we use the * one generated by temporary DAVE.createMDL() method. * * @see gov.nasa.daveml.dave.DAVE * @param theModel <code>gov.nasa.daveml.dave.Model</code> object to handle * **/ public SLDiagram( Model theModel ) { int row = 0; // high water mark SLBlock slb = null; this.inputNames = new ArrayList<String>(20); this.outputNames = new ArrayList<String>(20); // default behavior flags this.SLversion = 6.2; this.warnOnClip = false; this.resetOutputsWhenDisabled = true; this.makeLib = false; this.makeEnabledSubSys = false; this.verboseFlag = theModel.isVerbose(); if (this.verboseFlag) { System.out.println("Building diagram in memory..."); } // save pointer to object this.model = theModel; // Loop through all blocks while // 1. convert all blocks to SLblocks // 2. assign row & column number to all blocks this.slblockList = new ArrayList<SLBlock>( this.model.getNumBlocks() ); // Starting with input and constant blocks, assign to column // 1. Follow signal path and set immediate downstream blocks // to minimum of column 2, etc. and recurse. When done, column // set up with be complete. Also can propagate row so next // input block starts below lowest block of previous block. MDLNameList nl = new MDLNameList( this.model.getNumBlocks() ); // create name list for blocks if (this.verboseFlag) { System.out.println("Looping through " + this.model.getNumBlocks() + "-block list to find children, adjust names and set positions."); } BlockArrayList bal = this.model.getBlocks(); if ( bal == null ) { System.err.println("ERROR: No blocks associated with model!"); System.exit(0); } // assign blocks to SLBlocks and gather all SLBlocks to us for(Iterator<Block> iBlks = bal.iterator(); iBlks.hasNext(); ) { Block b = iBlks.next(); if(b != null) { slb = new SLBlock( this, b ); b.setMask( slb ); // let block know "who's yo daddy" } else { System.err.println("ERROR: Null Block found while assigning SLBlocks"); System.exit(0); } try { b.setNameList( nl ); // may change to acceptable SL name } catch (Exception e) { System.err.println("Warning: Unable to properly name " + b.getType() + "block '" + b.getName() + "'."); } this.slblockList.add( slb ); } // find children of all blocks; set inputs/constants to column 1 for(Iterator<SLBlock> islb = this.slblockList.iterator(); islb.hasNext(); ) { slb = islb.next(); slb.findChildren(); Block b = slb.getBlock(); if ( b == null ) { System.err.println("ERROR: Found an SLBlock with no encapsulated Block!"); System.exit(0); } if( (b instanceof BlockInput) || (b instanceof BlockMathConstant) ) { row = slb.setPosition(row+1, 1); // recursive routine } } // loop through new slblock list to find dimensions int numRows = 1; int numCols = 1; Iterator<SLBlock> iblk = this.slblockList.iterator(); while (iblk.hasNext()) { slb = iblk.next(); int theRow = slb.getRow(); int theCol = slb.getCol(); if(theRow > numRows) { numRows = theRow; } if(theCol > numCols) { numCols = theCol; } } if(this.verboseFlag) { System.out.print(" Found " + numRows + " rows and"); System.out.println(" " + numCols + " columns."); } // Create and initialize row & columns for diagram this.rows = new ArrayList<SLRowColumnVector>( numRows+1 ); // create arrays for refs to rows... this.cols = new ArrayList<SLRowColumnVector>( numCols+1 ); // ...columns.. this.cells = new ArrayList<SLCell>( numRows * numCols ); // ...and cells. for(int i = 0; i < numRows; i++) { // now create rows and... this.rows.add(i, new SLRowColumnVector(numCols+1, true)); } for(int i = 0; i < numCols; i++) { // ...columns themselves. this.cols.add(i, new SLRowColumnVector(numRows+1, false)); } // loop through and assign blocks to cells, rows, cols iblk = this.slblockList.iterator(); // this resets to start of list while (iblk.hasNext()) { slb = iblk.next(); // get block SLCell cell = new SLCell(slb, this); // create cell; saves ref to block and diagram this.cells.add( cell ); // add cell to list int rowIndex = slb.getRow()-1; // now assign cell to proper... int colIndex = slb.getCol()-1; // row and column... SLRowColumnVector rowv = this.rows.get( rowIndex ); SLRowColumnVector colv = this.cols.get( colIndex ); rowv.set(colIndex, cell); colv.set(rowIndex, cell); } } /** * * Sets the flag to generate warnings when breakpoint inputs exceed bounds * **/ void setWarnOnClip() { this.warnOnClip = true; } /** * * Returns the status of the warnings generation option * **/ boolean getWarnOnClip() { return this.warnOnClip; } /** * * Sets the SL version output to 4.0 * **/ void setVerFlag4() { this.SLversion = 4.0; } /** * * Returns the status of the SL version output at 4.0 flag * **/ boolean getVerFlag4() { return this.SLversion == 4.0; } /** * * Sets the SL version output to 5.0 * **/ void setVerFlag5() { this.SLversion = 5.0; } /** * * Returns the status of the SL version output at 5.0 flag * **/ boolean getVerFlag5() { return this.SLversion == 5.0; } /** * * Sets flag to generate library instead of model * **/ void setLibFlag() { this.makeLib = true; } /** * * Returns status of make library flag * **/ boolean getLibFlag() { return this.makeLib; } /** * * Sets flag to make enabled subsystem * **/ void setEnabledFlag() { this.makeEnabledSubSys = true; } /** * * Returns status of make enabled subsystem flag * **/ boolean getEnabledFlag() { return this.makeEnabledSubSys; } /** * * Returns the padding for cells in diagram. * **/ public int getPadding() { return SLDiagram.padding; } /** * * Returns the number of inputs to the diagram * **/ public int getNumInputs() { return this.model.getNumInputBlocks(); } /** * * Returns the number of outputs from the diagram * **/ public int getNumOutputs() { return this.model.getNumOutputBlocks(); } /** * * Sets the verbose flag for diagram and all children * **/ public void makeVerbose() { this.verboseFlag = true; if( rows != null ) { Iterator<SLRowColumnVector> it = rows.iterator(); while (it.hasNext()) { SLRowColumnVector dude = it.next(); dude.makeVerbose(); } } if( cols != null ) { Iterator<SLRowColumnVector> it = cols.iterator(); while (it.hasNext()) { SLRowColumnVector dude = it.next(); dude.makeVerbose(); } } if( slblockList != null ) { Iterator<SLBlock> it = slblockList.iterator(); while (it.hasNext()) { SLBlock dude = it.next(); dude.makeVerbose(); } } } /** * * Indicates status of verbose flag * **/ public boolean isVerbose() { return this.verboseFlag; } /** * * Clears the verbose flag * **/ public void silence() { this.verboseFlag = false; if( rows != null ) { Iterator<SLRowColumnVector> it = rows.iterator(); while (it.hasNext()) { SLRowColumnVector dude = it.next(); dude.makeVerbose(); } } if( cols != null ) { Iterator<SLRowColumnVector> it = cols.iterator(); while (it.hasNext()) { SLRowColumnVector dude = it.next(); dude.makeVerbose(); } } if( slblockList != null ) { Iterator<SLBlock> it = slblockList.iterator(); while (it.hasNext()) { SLBlock dude = it.next(); dude.makeVerbose(); } } } /** * * Returns the cell at a given row and column offset. * * @param rowIndex given row * @param colIndex given column * @return the cell at the given location * **/ public SLCell getCell( int rowIndex, int colIndex ) { //System.out.println("Looking for cell at [" + rowIndex + "," + colIndex + "]"); SLRowColumnVector row = this.rows.get( rowIndex ); // if(row!=null) // System.out.println(" found row index " + rowIndex); // else // System.out.println(" NO ROW FOUND with index " + rowIndex ); // return row.get(colIndex); SLCell theCell = row.get(colIndex); // if(theCell != null) // System.out.println(" found cell at column index " + colIndex ); // else // System.out.println(" NO CELL FOUND on row index " + rowIndex + // " at column index " + colIndex ); return theCell; } /** * * Returns SLCell associated with specified Block. * * @param b <code>Block</code> whose parent SLCell is sought * **/ public SLCell getCell( SLBlock b ) { int rowIndex = b.getRow()-1; int colIndex = b.getCol()-1; return this.getCell( rowIndex, colIndex ); } /** * * Returns SLRowColumnVector object representing the specified row * * @param index 0-based offset or index of desired row * **/ public SLRowColumnVector getRow( int index ) { return this.rows.get(index); } /** * * Returns SLRowColumnVector object representing the specified column * * @param index 0-based offset or index of desired column * **/ public SLRowColumnVector getCol( int index ) { return this.cols.get(index); } /** * * Add an input variable name in the right location, so verify * script can specify input vector in the proper sequence * * @param seqNum input block sequence number (1-based) * @param name input variable name * **/ public void addInput( int seqNum, String name ) { if (seqNum < 1) { System.err.println("Error - input block '" + name + "' sequence number (" + seqNum + ") is less than 1."); System.exit(0); } // pad out vector until it's long enough while ( inputNames.size() < seqNum ) { inputNames.add(null); } this.inputNames.set( seqNum-1, name ); } /** * * Returns the inputNames vector * **/ public ArrayList<String> getInputNames() { return this.inputNames; } /** * * Add an output variable name in the right location, so verify * script can specify output vector in the proper sequence * * @param seqNum output block sequence number (1-based) * @param name output variable name * **/ public void addOutput( int seqNum, String name ) { if (seqNum < 1) { System.err.println("Error - output block '" + name + "' sequence number (" + seqNum + ") is less than 1."); System.exit(0); } // pad out vector until it's long enough while ( outputNames.size() < seqNum ) { outputNames.add(null); } // add string to appropriate position this.outputNames.set( seqNum-1, name ); } /** * * Returns the outputNames vector * **/ public ArrayList<String> getOutputNames() { return this.outputNames; } /** * * Create text representation of diagram * **/ public void describeSelf( PrintStream printer) { final int width = 3; // print header printer.println(); // printer.println("Text representation of Simulink diagram:"); // printer.println(); // print column cabletray count printer.print(" "); // margin printer.print(" "); // space printer.print(" "); // margin for( int k = 0; k < width; k++) { printer.print(" "); } printer.print(" "); // margin for(int j = 0; j < cols.size(); j++) { SLRowColumnVector col = cols.get(j); printer.print(col.cableTray.size()); // need to set size to 2 printer.print(" "); // margin for( int k = 0; k < width; k++) { printer.print(" "); } printer.print(" "); // margin } for(int i = 0; i < rows.size(); i++) { SLRowColumnVector row = rows.get(i); printer.println(); printer.print(" *"); for(int j = 0; j < cols.size(); j++) { SLCell cell = row.get(j); if(cell != null) { SLBlock b = cell.getBlock(); printer.print(" "); if(b == null) { for( int k = 0; k < width; k++) { printer.print(" "); } } else { String s = b.getName(); if (s.length() < width) { printer.print(s); for( int k = 0; k < (width-s.length()); k++) { printer.print(" "); } } else { printer.print(s.substring(0,width)); } } } else { // if cell is null printer.print(" "); for( int k = 0; k < width; k++) { printer.print(" "); } } printer.print(" *"); } printer.print("\n" + row.cableTray.size()); } printer.println(); printer.println(); } /** * * Writes out Simulink model-building script to writer and necessary data statements to mWriter. * * @param writer SLFileWriter to output model diagram build script * @param mWriter MatFileWriter to output data * * @throws java.io.IOException * **/ public void createModel( SLFileWriter writer, MatFileWriter mWriter ) throws IOException { // update row & column info in blocks for( int i = 0; i < rows.size(); i++ ) { SLRowColumnVector row = rows.get(i); for( int j = 0; j < cols.size(); j++ ) { SLCell cell = row.get(j); if( cell != null) { SLBlock b = cell.getBlock(); int oldRow = b.getRow(); int oldCol = b.getCol(); if(oldRow != i+1) { System.err.println("WARNING: Had to update row number in block " + b.getName() + " to " + (i+1) + "; was " + oldRow); } if(oldCol != j+1) { System.err.println("WARNING: Had to update column number in block " + b.getName() + " to " + (j+1) + "; was " + oldCol); } b.setRowCol( i+1, j+1 ); // convert from offset to index } } } // write out blocks to model-building script and data to Mat file int rowOffset = xMargin; for(int rowIndex = 0; rowIndex < this.rows.size(); rowIndex++) { // adjust row offset for half row height int rowSize = this.getRow( rowIndex ).getSize(); // includes padding around block int y = rowOffset + rowSize/2; int colOffset = yMargin; for( int colIndex = 0; colIndex < this.cols.size(); colIndex++ ) { // adjust column offset for half column width int colSize = this.getCol( colIndex ).getSize(); // includes padding int x = colOffset + colSize/2; // probably is redundant SLCell theCell = this.getCell( rowIndex, colIndex ); if( theCell != null ) { SLBlock theBlock = theCell.getBlock(); if( theBlock != null ) { theBlock.createM( writer, x, y ); theBlock.writeMat( mWriter ); } } colOffset = colOffset + colSize; } rowOffset = rowOffset + rowSize; } // add lines // convert generic Signals to SLSignals SignalArrayList sigs = model.getSignals(); Iterator<Signal> isig = sigs.iterator(); while (isig.hasNext()) { Signal oldSig = isig.next(); SLSignal newSig = new SLSignal( oldSig, this ); // convert to SLSig newSig.createAddLine( writer ); // write add_line to .m file } } }
27.800766
103
0.519616
451781031e09c3ff95b372c1035c884012213508
2,752
/******************************************************************************* * Copyright 2015 InfinitiesSoft Solutions 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.infinities.skyport.ssh.handler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.MessageEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cloud.consoleproxy.ssh.Config; import com.infinities.skyport.ssh.handler.exception.KeyExchangeException; import com.jcraft.jsch.CustomBuffer; import com.jcraft.jsch.CustomKeyExchange; import com.jcraft.jsch.CustomSession; public class ReceiveKexHandler implements ChannelUpstreamHandler { private static final Logger logger = LoggerFactory.getLogger(ReceiveKexHandler.class); private CustomSession session; public ReceiveKexHandler(CustomSession session) { this.session = session; } @Override public void handleUpstream(ChannelHandlerContext context, ChannelEvent evt) throws Exception { logger.trace("handle up stream : {}, {}, {}", new Object[] { evt.getClass(), evt.toString(), context.getPipeline().getNames() }); if (!(evt instanceof MessageEvent)) { context.sendUpstream(evt); return; } MessageEvent e = (MessageEvent) evt; if (e.getMessage() instanceof CustomBuffer) { // ChannelBuffer buffer = try { CustomBuffer buf = (CustomBuffer) e.getMessage(); // buf = session.read(buf, buffer); logger.debug("command received: {}", buf.getCommand()); // Encode the message to base64 if (buf.getCommand() != Config.SSH_MSG_KEXINIT) { session.setIn_kex(false); throw new KeyExchangeException("invalid protocol: " + buf.getCommand()); } logger.info("SSH_MSG_KEXINIT received"); context.getPipeline().remove(this); CustomKeyExchange kex = session.receiveKexinit(buf, context, evt); session.setKex(kex); } catch (Exception ex) { session.close(context.getChannel(), ex.getMessage(), context, e.getMessage()); throw ex; } } else { context.sendUpstream(evt); } } }
36.210526
95
0.697311
24b205303bd1f6f84f62b3041e4614b1e4f4001e
4,311
/* * Copyright 2007 Outerthought bvba and Schaubroeck nv * * 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.outerj.daisy.doctaskrunner.serverimpl.actions; import java.util.regex.Pattern; import org.outerj.daisy.doctaskrunner.DocumentExecutionResult; import org.outerj.daisy.doctaskrunner.DocumentExecutionState; import org.outerj.daisy.doctaskrunner.DocumentSelection; import org.outerj.daisy.doctaskrunner.TaskContext; import org.outerj.daisy.doctaskrunner.TaskSpecification; import org.outerj.daisy.doctaskrunner.serverimpl.CaseHandling; import org.outerj.daisy.doctaskrunner.serverimpl.actions.serp.DocumentMatches; import org.outerj.daisy.doctaskrunner.spi.AbstractDocumentAction; import org.outerj.daisy.repository.Document; import org.outerj.daisy.repository.LockInfo; import org.outerj.daisy.repository.Repository; import org.outerj.daisy.repository.VariantKey; import org.outerx.daisy.x10DocumentActions.ReplaceParametersDocument; import org.outerx.daisy.x10DocumentActions.ReplaceParametersDocument.ReplaceParameters; public class ReplaceDocumentAction extends AbstractDocumentAction { private Pattern pattern; private CaseHandling caseHandling = CaseHandling.INSENSITIVE; // this is the default behaviour private String replacement; @Override public void setup(VariantKey[] variantKeys, TaskSpecification taskSpecifiation, TaskContext taskContext, Repository repository) throws Exception { super.setup(variantKeys, taskSpecifiation, taskContext, repository); ReplaceParameters paramsXml = ReplaceParametersDocument.Factory.parse(taskSpecifiation.getParameters()).getReplaceParameters(); String regexp = paramsXml.getRegexp(); if (paramsXml.isSetCaseHandling()) { caseHandling = CaseHandling.fromString(paramsXml.getCaseHandling().toString()); } // note: both CaseHandling.INSENSITIVE and CaseHandling.SENSIBLE need a case insensitive java.util.regexp.Pattern boolean caseSensitive = caseHandling.equals(CaseHandling.SENSITIVE); this.pattern = Pattern.compile(regexp, caseSensitive?0:Pattern.CASE_INSENSITIVE); replacement = paramsXml.getReplacement(); } public void execute(VariantKey variantKey, DocumentExecutionResult result) throws Exception { Document doc = repository.getDocument(variantKey, true); LockInfo lockInfo = doc.getLockInfo(true); if (lockInfo != null) { if (lockInfo.getUserId() == repository.getUserId()) { String message = new StringBuffer("skipped (document is currently locked by ") .append(repository.getUserManager().getPublicUserInfo(lockInfo.getUserId()).getDisplayName()) .append("(").append(lockInfo.getUserId()) .append("))").toString(); result.setMessage(message); result.setState(DocumentExecutionState.ERROR); return; } } DocumentMatches m = new DocumentMatches(repository, doc, pattern); int replacements = m.replaceMatches(replacement, caseHandling.equals(CaseHandling.SENSIBLE)); if (replacements > 0) { doc.save(false); } StringBuffer message = new StringBuffer("replaced ") .append(replacements) .append(" occurrence(s)."); if (m.isSkippedDocumentName() || m.isSkippedParts()) { message.append(" Some occurrences may have been skipped because you do not have full write access."); } result.setMessage(message.toString()); } @Override public boolean requiresAdministratorRole() { return false; } }
43.11
135
0.708188
44390e275b14d03d998113603c7389cf3e3529b4
288
package com.evliion.ev.repository; import com.evliion.ev.model.Address; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * */ @Repository public interface AddressRepository extends JpaRepository<Address, Long> { }
20.571429
73
0.798611
3de70a85a0659642c78ba5abc7466c76786a42f5
921
package com.cloudbees.jenkins; import hudson.Extension; import hudson.security.csrf.CrumbExclusion; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.logging.Logger; @Extension public class GitHubWebHookCrumbExclusion extends CrumbExclusion { private static final Logger LOGGER = Logger.getLogger("com.cloudbees.jenkins.GitHubWebHookCrumbExclusion"); @Override public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { String pathInfo = req.getPathInfo(); if (pathInfo != null && pathInfo.equals(getExclusionPath())) { chain.doFilter(req, resp); return true; } return false; } public String getExclusionPath() { return "/" + GitHubWebHook.URLNAME + "/"; } }
27.909091
131
0.788274
bc1d5d35dbc1035361637aee2e8653d4cac38487
6,466
/** * R Depot * * Copyright (C) 2012-2021 Open Analytics NV * * =========================================================================== * * This program is free software: you can redistribute it and/or modify * it under the terms of the Apache License as published by * The Apache Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Apache License for more details. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/> */ package eu.openanalytics.rdepot.authenticator; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import javax.annotation.Resource; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.env.Environment; import org.springframework.ldap.core.DirContextOperations; import org.springframework.ldap.core.support.BaseLdapPathContextSource; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.Authentication; import org.springframework.security.ldap.authentication.BindAuthenticator; import eu.openanalytics.rdepot.exception.UserCreateException; import eu.openanalytics.rdepot.exception.UserEditException; import eu.openanalytics.rdepot.model.Role; import eu.openanalytics.rdepot.model.User; import eu.openanalytics.rdepot.security.LDAPSecurityConfig; import eu.openanalytics.rdepot.service.EventService; import eu.openanalytics.rdepot.service.RoleService; import eu.openanalytics.rdepot.service.UserEventService; import eu.openanalytics.rdepot.service.UserService; @ConditionalOnProperty(value = "app.authentication", havingValue = "ldap") @Transactional public class LDAPCustomBindAuthenticator extends BindAuthenticator { @Resource private Environment environment; @Resource private UserService userService; @Resource private RoleService roleService; @Resource private EventService eventService; @Resource private UserEventService userEventService; @Resource private Environment env; @Value("${app.ldap.loginfield}") private String ldapLoginField; @Value("${app.ldap.emailfield}") private String ldapEmailField; private static final Logger log = LoggerFactory.getLogger(LDAPCustomBindAuthenticator.class); public LDAPCustomBindAuthenticator(BaseLdapPathContextSource contextSource) { super(contextSource); } @Override public DirContextOperations authenticate(Authentication authentication) { List<String> namefields = new ArrayList<>(); for (int i=0;;i++) { String namefield = environment.getProperty(String.format("app.ldap.namefield[%d]", i)); if (namefield == null) break; else namefields.add(namefield) ; } LDAPSecurityConfig.validateConfiguration(ldapLoginField, "ldap.loginfield"); LDAPSecurityConfig.validateConfiguration(namefields, "ldap.namefield"); LDAPSecurityConfig.validateConfiguration(ldapEmailField, "ldap.emailfield"); DirContextOperations userData; try { userData = super.authenticate(authentication); } catch (Exception e) { log.info("Got exception: " + e.toString()); throw e; } String login = userData.getStringAttribute(ldapLoginField); String name = ""; for(String namefield : namefields) name += userData.getStringAttribute(namefield) + " "; name = name.substring(0, name.length() - 1); String email = userData.getStringAttribute(ldapEmailField); if (email == null) { email = login + "@localhost"; } User user = userService.findByLoginEvenDeleted(login); List<String> defaultAdmins = new ArrayList<>(); for (int i=0;;i++) { String admin = environment.getProperty(String.format("app.ldap.default.admins[%d]", i)); if (admin == null) break; else defaultAdmins.add(admin); } if (defaultAdmins.isEmpty()) defaultAdmins.add("admin"); Role adminRole = roleService.getAdminRole(); try { if (user == null) { user = userService.findByEmailEvenDeleted(email); if (user == null) { user = new User(); user.setLogin(login); if (defaultAdmins.contains(login)) user.setRole(adminRole); else user.setRole(roleService.getUserRole()); user.setName(name); user.setEmail(email); user.setActive(true); try { userService.create(user); } catch (UserCreateException e) { throw new BadCredentialsException(messages.getMessage(e.getMessage(), e.getMessage())); } } else if(!user.isActive()) { throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "Account disabled")); } else if(user.isDeleted()) { throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "Account disabled")); } else { userService.updateLogin(user, null, login); if(!Objects.equals(name, user.getName())) userService.updateName(user, null, name); } } else if(!user.isActive()) { throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "Account disabled")); } else if(user.isDeleted()) { throw new BadCredentialsException( messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "Account disabled")); } else { if(!Objects.equals(name, user.getName())) userService.updateName(user, null, name); if(!Objects.equals(email, user.getEmail())) userService.updateEmail(user, null, email); if (defaultAdmins.contains(login) && !user.getRole().equals(adminRole)) userService.updateRole(user, null, adminRole); } userService.updateLastLoggedInOn(user, null, new Date()); } catch(UserEditException e) { throw new BadCredentialsException(messages.getMessage(e.getMessage(), e.getMessage())); } return userData; } }
30.64455
117
0.720229
941ac81b401ecbf2c42db9d2a0057de985930cee
2,691
/* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.common.block; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.particles.DustParticleOptions; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import org.jetbrains.annotations.Nullable; import vazkii.botania.common.block.tile.ModTiles; import vazkii.botania.common.block.tile.TileEnderEye; import javax.annotation.Nonnull; import java.util.Random; public class BlockEnderEye extends BlockMod implements EntityBlock { protected BlockEnderEye(Properties builder) { super(builder); registerDefaultState(defaultBlockState().setValue(BlockStateProperties.POWERED, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(BlockStateProperties.POWERED); } @Override public boolean isSignalSource(BlockState state) { return true; } @Override public int getSignal(BlockState state, BlockGetter world, BlockPos pos, Direction side) { return state.getValue(BlockStateProperties.POWERED) ? 15 : 0; } @Nonnull @Override public BlockEntity newBlockEntity(@Nonnull BlockPos pos, @Nonnull BlockState state) { return new TileEnderEye(pos, state); } @Nullable @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> type) { if (!level.isClientSide) { return createTickerHelper(type, ModTiles.ENDER_EYE, TileEnderEye::serverTick); } return null; } @Override public void animateTick(BlockState state, Level world, BlockPos pos, Random rand) { if (state.getValue(BlockStateProperties.POWERED)) { for (int i = 0; i < 20; i++) { double x = pos.getX() - 0.1 + Math.random() * 1.2; double y = pos.getY() - 0.1 + Math.random() * 1.2; double z = pos.getZ() - 0.1 + Math.random() * 1.2; world.addParticle(DustParticleOptions.REDSTONE, x, y, z, 0, 0, 0); } } } }
32.035714
120
0.767744
0a46f3d3abedaec611432aa8c180dbb5e192cfaf
2,080
package io.github.kimmking.gateway.outbound.netty4; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.util.concurrent.DefaultPromise; import org.apache.commons.codec.Charsets; import java.net.URI; import java.net.URL; public class NettyHttpClient { public void connect(String urlStr, DefaultPromise promise) throws Exception { URL url = new URL(urlStr); String host = url.getHost(); int port = url.getPort(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 ch.pipeline().addLast(new HttpResponseDecoder()); // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 ch.pipeline().addLast(new HttpRequestEncoder()); ch.pipeline().addLast(new InnerHandler(promise)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); URI uri = new URI(url.getPath()); String req = ""; DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString(), Unpooled.wrappedBuffer(req.getBytes(Charsets.UTF_8))); f.channel().write(request); f.channel().flush(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); } } }
37.142857
109
0.630288
4e5d4e9e5221e09e2054e3f7536996f6fc443676
307
package org.keviny.gallery.rdb.repository; import org.keviny.gallery.rdb.model.Account; /** * Created by Kevin YOUNG on 2015/5/8. */ public interface AccountRepository { void saveAccount(Account acc); Account getAccountById(Integer id); Account getAccountByUsername(String username); }
21.928571
48
0.742671
60eee113464d4a025d5496f72acc0a03e1de5caf
2,872
package cn.parzulpan.shopping.product.config; import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.cache.CacheProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @author parzulpan * @version 1.0 * @date 2021-04 * @project shopping * @package cn.parzulpan.shopping.product.config * @desc 自定义缓存配置类 * * 使用自定义缓存配置类后,缓存配置文件中设置的属性将会失效, * 比如:spring.cache.redis.time-to-live=3600000 # 设置缓存存活时间 * 所以需要另外在这里配置重新绑定。 * * 1. 原来和配置文件绑定的配置类是这样子的: * @ConfigurationProperties( * prefix = "spring.cache" * ) * public class CacheProperties {} * * 2. 现在要让它生效: * 加上 @EnableConfigurationProperties(CacheProperties.class) 让 CacheProperties 的绑定生效 * 注入 CacheProperties 或者在配置方法中加上 CacheProperties 参数 * */ @EnableConfigurationProperties(CacheProperties.class) @EnableCaching @Configuration public class MyCacheConfig { // @Autowired // CacheProperties cacheProperties; @Bean RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) { // 链式 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); // 设置 key 的序列化,使用 redis string config = config.serializeKeysWith(RedisSerializationContext .SerializationPair .fromSerializer(new StringRedisSerializer())); // 设置 value 的序列化,使用 fastjson // /*GenericFastJsonRedisSerializer()*/ config = config.serializeValuesWith(RedisSerializationContext .SerializationPair .fromSerializer(new GenericJackson2JsonRedisSerializer())); // 获取 redis 配置 CacheProperties.Redis redis = cacheProperties.getRedis(); // 使配置文件中的所有配置都生效 if (redis.getTimeToLive() != null) { config = config.entryTtl(redis.getTimeToLive()); } if (redis.getKeyPrefix() != null) { config = config.prefixKeysWith(redis.getKeyPrefix()); config = config.prefixCacheNameWith(redis.getKeyPrefix()); } if (!redis.isCacheNullValues()) { config = config.disableCachingNullValues(); } if (!redis.isUseKeyPrefix()) { config = config.disableKeyPrefix(); } return config; } }
33.395349
86
0.722493
a37e6be35436f6ecf415cf5178f45c1bc9bc48d4
8,480
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ipaas.ifw.jdbc.impl; import static org.junit.Assert.assertEquals; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.github.ipaas.ifw.jdbc.impl.FwDbAccessResponseRow; /** * by whx * * @author harry * */ public class FwDbAccessResponseRowTest { @BeforeClass public static void setUpOnce() { } @AfterClass public static void tearDownOnce() { } @Test public void testGetDateStringString() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "birth"); // test normal string convert row.put("birth", "1981-05-07"); assertEquals(new Date(81, 4, 7), rprow.getDate("birth", "yyyy-MM-dd")); // test normal date row.put("birth", new Date(81, 4, 7)); assertEquals(new Date(81, 4, 7), rprow.getDate("birth", "")); // test null row.put("birth", null); assertEquals(null, rprow.getDate("birth", "yyyy-MM-dd")); } @Test(expected = IllegalStateException.class) public void testGetDateStringStringException() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); // test no exist rprow.getDate("notexist", "yyyy-MM-dd"); } @Test public void testGetDateIntString() { Map<Integer, String> meta = new HashMap<Integer, String>(); meta.put(Integer.valueOf(1), "birth"); Map<String, Object> row = new HashMap<String, Object>(); row.put("birth", "1981-05-07"); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); assertEquals(new Date(81, 4, 7), rprow.getDate(1, "yyyy-MM-dd")); row.put("birth", new Date(81, 4, 7)); assertEquals(new Date(81, 4, 7), rprow.getDate(1, "")); row.put("birth", null); assertEquals(null, rprow.getDate(1, "yyyy-MM-dd")); } @Test(expected = IllegalStateException.class) public void testGetDateIntStringException() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "birth"); row.put("birth", "1981-05-07"); rprow.getDate(2, "yyyy-MM-dd"); } @Test public void testGetIntString() { Map<Integer, String> meta = new HashMap<Integer, String>(); meta.put(Integer.valueOf(1), "age"); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); // test normal row.put("age", 30); assertEquals(30, rprow.getInt("age")); // test string convert row.put("age", "30"); assertEquals(30, rprow.getInt("age")); // test null row.put("age", null); assertEquals(0, rprow.getInt("age")); } @Test(expected = IllegalStateException.class) public void testGetIntStringException() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "age"); row.put("age", 30); // test no exist rprow.getInt("notexist"); } @Test public void testGetIntInt() { Map<Integer, String> meta = new HashMap<Integer, String>(); meta.put(Integer.valueOf(1), "age"); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); // test normal row.put("age", 30); assertEquals(30, rprow.getInt(1)); // test string convert row.put("age", "30"); assertEquals(30, rprow.getInt(1)); // test null row.put("age", null); assertEquals(0, rprow.getInt(1)); } @Test(expected = IllegalStateException.class) public void testGetIntIntException() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "age"); row.put("age", 30); // test no exist rprow.getInt(2); } @Test public void testGetStringString() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "name"); // test normal row.put("name", "harry"); assertEquals("harry", rprow.getString("name")); } @Test(expected = IllegalStateException.class) public void testGetStringStringException() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "name"); // test normal row.put("name", "harry"); rprow.getString("notexist"); } @Test public void testGetStringInt() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "name"); // test normal row.put("name", "harry"); assertEquals("harry", rprow.getString(1)); } @Test(expected = IllegalStateException.class) public void testGetStringIntException() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "name"); // test normal row.put("name", "harry"); rprow.getString(2); } @Test public void testGetFloatString() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "cost"); // test normal row.put("cost", 15.6f); assertEquals(15.6f, rprow.getFloat("cost"), 0.1); // test string convert row.put("cost", "15.6"); assertEquals(15.6f, rprow.getFloat("cost"), 0.1); // test null row.put("cost", null); assertEquals(0f, rprow.getFloat("cost"), 0.1); } @Test(expected = IllegalStateException.class) public void testGetFloatStringException() { Map<Integer, String> meta = new HashMap<Integer, String>(); meta.put(Integer.valueOf(1), "age"); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); row.put("age", 30); rprow.getFloat("notexist"); } @Test public void testGetFloatInt() { Map<Integer, String> meta = new HashMap<Integer, String>(); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); meta.put(Integer.valueOf(1), "cost"); // test normal row.put("cost", 15.6f); assertEquals(15.6f, rprow.getFloat(1), 0.1); // test string convert row.put("cost", "15.6"); assertEquals(15.6f, rprow.getFloat(1), 0.1); // test null row.put("cost", null); assertEquals(0f, rprow.getFloat(1), 0.1); } @Test(expected = IllegalStateException.class) public void testGetFloatIntException() { Map<Integer, String> meta = new HashMap<Integer, String>(); meta.put(Integer.valueOf(1), "age"); Map<String, Object> row = new HashMap<String, Object>(); FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta); row.put("age", 30); rprow.getFloat(2); } }
33.784861
76
0.67559