hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0f9d20b06f6a6b903d890f60437bdfd4761ccb
1,645
java
Java
modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/shuffle/direct/HadoopDirectDataOutputState.java
FedorUporov/gridgain
883125f943743fa8198d88be98dfe61bde86ad96
[ "CC0-1.0" ]
null
null
null
modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/shuffle/direct/HadoopDirectDataOutputState.java
FedorUporov/gridgain
883125f943743fa8198d88be98dfe61bde86ad96
[ "CC0-1.0" ]
null
null
null
modules/hadoop/src/main/java/org/apache/ignite/internal/processors/hadoop/shuffle/direct/HadoopDirectDataOutputState.java
FedorUporov/gridgain
883125f943743fa8198d88be98dfe61bde86ad96
[ "CC0-1.0" ]
null
null
null
24.924242
102
0.644985
6,629
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.hadoop.shuffle.direct; /** * Hadoop data output state for direct communication. */ public class HadoopDirectDataOutputState { /** Buffer. */ private final byte[] buf; /** Buffer length. */ private final int bufLen; /** Data length. */ private final int dataLen; /** * Constructor. * * @param buf Buffer. * @param bufLen Buffer length. * @param dataLen Data length. */ public HadoopDirectDataOutputState(byte[] buf, int bufLen, int dataLen) { this.buf = buf; this.bufLen = bufLen; this.dataLen = dataLen; } /** * @return Buffer. */ public byte[] buffer() { return buf; } /** * @return Length. */ public int bufferLength() { return bufLen; } /** * @return Original data length. */ public int dataLength() { return dataLen; } }
3e0f9d3f6b1f9f71c113278e7e89491239d9839b
823
java
Java
src/main/java/vote/config/JsonDecDateSerializer.java
johnnico233/vote
127b212bbc0d859c4a40b8b76de8c4bbf46a1d8e
[ "Apache-2.0" ]
1
2021-12-07T11:13:28.000Z
2021-12-07T11:13:28.000Z
src/main/java/vote/config/JsonDecDateSerializer.java
johnnico233/vote
127b212bbc0d859c4a40b8b76de8c4bbf46a1d8e
[ "Apache-2.0" ]
null
null
null
src/main/java/vote/config/JsonDecDateSerializer.java
johnnico233/vote
127b212bbc0d859c4a40b8b76de8c4bbf46a1d8e
[ "Apache-2.0" ]
1
2021-12-07T11:13:37.000Z
2021-12-07T11:13:37.000Z
32.92
116
0.755772
6,630
package vote.config; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class JsonDecDateSerializer extends JsonDeserializer<Date> { public final static SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm"); @Override public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { try{ return format.parse(p.getText()); }catch (ParseException ex){ ex.printStackTrace(); } return null; } }
3e0f9d7ba074edd5113431fa44e2942d0577fe48
11,313
java
Java
src/main/java/edu/udel/cis/vsl/civl/semantics/common/CommonMemoryUnitEvaluator.java
byu-vv-lab/civl
f599229ff4830acc75c33149611c65ff4052d516
[ "BSD-3-Clause" ]
null
null
null
src/main/java/edu/udel/cis/vsl/civl/semantics/common/CommonMemoryUnitEvaluator.java
byu-vv-lab/civl
f599229ff4830acc75c33149611c65ff4052d516
[ "BSD-3-Clause" ]
null
null
null
src/main/java/edu/udel/cis/vsl/civl/semantics/common/CommonMemoryUnitEvaluator.java
byu-vv-lab/civl
f599229ff4830acc75c33149611c65ff4052d516
[ "BSD-3-Clause" ]
null
null
null
34.075301
103
0.723239
6,631
package edu.udel.cis.vsl.civl.semantics.common; import java.util.HashSet; import java.util.Set; import edu.udel.cis.vsl.civl.dynamic.IF.SymbolicUtility; import edu.udel.cis.vsl.civl.model.IF.CIVLSource; import edu.udel.cis.vsl.civl.model.IF.CIVLTypeFactory; import edu.udel.cis.vsl.civl.model.IF.CIVLUnimplementedFeatureException; import edu.udel.cis.vsl.civl.model.IF.ModelFactory; import edu.udel.cis.vsl.civl.model.IF.expression.Expression; import edu.udel.cis.vsl.civl.model.IF.expression.MemoryUnitExpression; import edu.udel.cis.vsl.civl.model.IF.expression.reference.ArraySliceReference; import edu.udel.cis.vsl.civl.model.IF.expression.reference.ArraySliceReference.ArraySliceKind; import edu.udel.cis.vsl.civl.model.IF.expression.reference.MemoryUnitReference; import edu.udel.cis.vsl.civl.model.IF.expression.reference.MemoryUnitReference.MemoryUnitReferenceKind; import edu.udel.cis.vsl.civl.model.IF.expression.reference.StructOrUnionFieldReference; import edu.udel.cis.vsl.civl.model.IF.type.CIVLCompleteArrayType; import edu.udel.cis.vsl.civl.model.IF.type.CIVLStructOrUnionType; import edu.udel.cis.vsl.civl.model.IF.type.CIVLType; import edu.udel.cis.vsl.civl.semantics.IF.Evaluation; import edu.udel.cis.vsl.civl.semantics.IF.Evaluator; import edu.udel.cis.vsl.civl.semantics.IF.MemoryUnitExpressionEvaluator; import edu.udel.cis.vsl.civl.state.IF.MemoryUnit; import edu.udel.cis.vsl.civl.state.IF.MemoryUnitFactory; import edu.udel.cis.vsl.civl.state.IF.MemoryUnitSet; import edu.udel.cis.vsl.civl.state.IF.State; import edu.udel.cis.vsl.civl.state.IF.UnsatisfiablePathConditionException; import edu.udel.cis.vsl.civl.util.IF.Pair; import edu.udel.cis.vsl.sarl.IF.Reasoner; import edu.udel.cis.vsl.sarl.IF.SymbolicUniverse; import edu.udel.cis.vsl.sarl.IF.expr.NumericExpression; import edu.udel.cis.vsl.sarl.IF.expr.ReferenceExpression; import edu.udel.cis.vsl.sarl.IF.expr.SymbolicExpression; import edu.udel.cis.vsl.sarl.IF.expr.SymbolicExpression.SymbolicOperator; import edu.udel.cis.vsl.sarl.IF.number.IntegerNumber; import edu.udel.cis.vsl.sarl.IF.object.SymbolicObject; import edu.udel.cis.vsl.sarl.IF.type.SymbolicType; import edu.udel.cis.vsl.sarl.collections.IF.SymbolicCollection; /** * This is responsible for evaluating memory unit expressions. (IN PROGRESS) * * @author Manchun Zheng * */ public class CommonMemoryUnitEvaluator implements MemoryUnitExpressionEvaluator { private ModelFactory modelFactory; private CIVLTypeFactory typeFactory; /** * The symbolic utility to be used. */ private SymbolicUtility symbolicUtil; /** * The evaluator to be used for evaluating parameters of memory unit * expressions, e.g, index of an array. */ private CommonEvaluator evaluator; /** * The symbolic universe to be used. */ private SymbolicUniverse universe; private MemoryUnitFactory muFactory; public CommonMemoryUnitEvaluator(SymbolicUtility symbolicUtil, Evaluator evaluator, MemoryUnitFactory muFactory, SymbolicUniverse universe) { this.symbolicUtil = symbolicUtil; this.evaluator = (CommonEvaluator) evaluator; this.universe = universe; this.muFactory = muFactory; this.modelFactory = evaluator.modelFactory(); this.typeFactory = this.modelFactory.typeFactory(); } /** * Evaluates a memory unit expression. * * @param state * @param pid * @param memUnit * @return * @throws UnsatisfiablePathConditionException */ public MemoryUnitSet evaluates(State state, int pid, MemoryUnitExpression memUnit, MemoryUnitSet muSet) throws UnsatisfiablePathConditionException { MemoryUnitSet result = muSet; int scopeID = memUnit.scopeId(); int dyscopeID = state.getDyscope(pid, scopeID); Set<ReferenceExpression> referenceValues; if (dyscopeID < 0) return result; referenceValues = this.evaluatesMemoryUnitReference( memUnit.getSource(), state, pid, memUnit.objectType(), memUnit.reference(), null).right; for (ReferenceExpression reference : referenceValues) { MemoryUnit newMemUnit = muFactory.newMemoryUnit(dyscopeID, memUnit.variableId(), reference); muFactory.add(result, newMemUnit); if (memUnit.deref()) { SymbolicExpression pointer = state.getVariableValue(dyscopeID, memUnit.variableId()); if (pointer.type().equals( this.typeFactory.pointerSymbolicType())) muFactory.add(result, this.muFactory.newMemoryUnit( this.symbolicUtil.getDyscopeId(null, pointer), this.symbolicUtil.getVariableId(null, pointer), symbolicUtil.getSymRef(pointer))); } // result.add(pointer); // this.findPointersInExpression( // this.symbolicUtil.makePointer(dyscopeID, // memUnit.variableId(), reference), result, // state, state.getProcessState(pid).name()); // result.add(symbolicUtil.makePointer(dyscopeID, // memUnit.variableId(), reference)); } return result; } /** * Evaluates reference of memory unit expressions. * * @param state * @param pid * @param reference * @param parent * @return * @throws UnsatisfiablePathConditionException */ private Pair<State, Set<ReferenceExpression>> evaluatesMemoryUnitReference( CIVLSource source, State state, int pid, CIVLType objType, MemoryUnitReference reference, Set<ReferenceExpression> parents) throws UnsatisfiablePathConditionException { MemoryUnitReferenceKind refKind = reference.memoryUnitKind(); MemoryUnitReference child = reference.child(); Set<ReferenceExpression> myRefValues = new HashSet<>(); CIVLType myObjType = objType; // ReferenceExpression myRefValue = null; switch (refKind) { case SELF: myRefValues.add(universe.identityReference()); break; case ARRAY_SLICE:// TODO to be finished { ArraySliceReference arraySlice = (ArraySliceReference) reference; ArraySliceKind sliceKind = arraySlice.sliceKind(); Expression indexExpression = arraySlice.index(); Evaluation eval = null; assert parents != null && parents.size() > 0; if (indexExpression != null) { eval = evaluator.evaluate(state, pid, indexExpression); state = eval.state; } switch (sliceKind) { case ELEMENT: for (ReferenceExpression parent : parents) myRefValues.add(universe.arrayElementReference(parent, (NumericExpression) eval.value)); break; case WILDCARD: { CIVLCompleteArrayType arrayType = (CIVLCompleteArrayType) objType; Expression extent = arrayType.extent(); int extentInt; Reasoner reasoner = universe.reasoner(state.getPathCondition()); IntegerNumber length_number; eval = evaluator.evaluate(state, pid, extent); state = eval.state; length_number = (IntegerNumber) reasoner .extractNumber((NumericExpression) eval.value); extentInt = length_number.intValue(); for (int i = 0; i < extentInt; i++) for (ReferenceExpression parent : parents) myRefValues.add(universe.arrayElementReference(parent, universe.integer(i))); break; } case REG_RANGE: // TODO to be finished break; default: throw new CIVLUnimplementedFeatureException( "evaluating array slice reference of " + sliceKind + " kind", source); } break; } case STRUCT_OR_UNION_FIELD: { StructOrUnionFieldReference fieldRef = (StructOrUnionFieldReference) reference; int fieldIndex = fieldRef.fieldIndex(); assert parents != null && parents.size() > 0; myObjType = ((CIVLStructOrUnionType) objType).getField(fieldIndex) .type(); for (ReferenceExpression parent : parents) myRefValues.add(universe.tupleComponentReference(parent, universe.intObject(fieldRef.fieldIndex()))); break; } default: throw new CIVLUnimplementedFeatureException( "evaluating memory unit reference of " + refKind + " kind", source); } assert myRefValues.size() > 0; if (child != null) return evaluatesMemoryUnitReference(source, state, pid, myObjType, child, myRefValues); else { // result.addAll(myRefValues); return new Pair<>(state, myRefValues); } } /** * Finds pointers contained in a given expression recursively. * * @param expr * @param set * @param state */ private void findPointersInExpression(SymbolicExpression expr, MemoryUnitSet set, State state, String process) { SymbolicType type = expr.type(); // TODO check comm type if (type != null && !type.equals(typeFactory.heapSymbolicType()) && !type.equals(typeFactory.bundleSymbolicType())) { // need to eliminate heap type as well. each proc has its own. if (typeFactory.pointerSymbolicType().equals(type)) { SymbolicExpression pointerValue; Evaluation eval; this.muFactory.add(set, this.muFactory.newMemoryUnit( this.symbolicUtil.getDyscopeId(null, expr), this.symbolicUtil.getVariableId(null, expr), symbolicUtil.getSymRef(expr))); // set.add(expr); try { if (expr.operator() == SymbolicOperator.CONCRETE && symbolicUtil.getDyscopeId(null, expr) >= 0) { /* * If the expression is an arrayElementReference * expression, and finally it turns that the array type * has length 0, return immediately. Because we can not * dereference it and the dereference exception * shouldn't report here. */ if (symbolicUtil.getSymRef(expr) .isArrayElementReference()) { SymbolicExpression arrayPointer = symbolicUtil .parentPointer(null, expr); eval = evaluator.dereference(null, state, process, null, arrayPointer, false, true); /* Check if it's length == 0 */ if (universe.length(eval.value).isZero()) return; } eval = evaluator.dereference(null, state, process, null, expr, false, true); pointerValue = eval.value; state = eval.state; if (pointerValue.operator() == SymbolicOperator.CONCRETE && pointerValue.type() != null && pointerValue.type().equals( typeFactory.pointerSymbolicType())) if (this.symbolicUtil.isNullPointer(pointerValue)) return; findPointersInExpression(pointerValue, set, state, process); } } catch (UnsatisfiablePathConditionException e) { // // TODO Auto-generated catch block // e.printStackTrace(); } } else { int numArgs = expr.numArguments(); for (int i = 0; i < numArgs; i++) { SymbolicObject arg = expr.argument(i); findPointersInObject(arg, set, state, process); } } } } /** * Finds all the pointers that can be dereferenced inside a symbolic object. * * @param object * a symbolic object * @param set * a set to which the pointer values will be added * @param heapType * the heap type, which will be ignored */ private void findPointersInObject(SymbolicObject object, MemoryUnitSet set, State state, String process) { switch (object.symbolicObjectKind()) { case EXPRESSION: findPointersInExpression((SymbolicExpression) object, set, state, process); break; case EXPRESSION_COLLECTION: for (SymbolicExpression expr : (SymbolicCollection<?>) object) findPointersInExpression(expr, set, state, process); break; default: // ignore types and primitives, they don't have any pointers // you can dereference. } } }
3e0f9f61e60d87862199f8839cfca45d278341a8
102
java
Java
src/creational/factorymethod/IFactory.java
xiaosanye/Design_Pattern
5944db647e9ad7967fae96db2209486d084bd604
[ "Apache-2.0" ]
null
null
null
src/creational/factorymethod/IFactory.java
xiaosanye/Design_Pattern
5944db647e9ad7967fae96db2209486d084bd604
[ "Apache-2.0" ]
null
null
null
src/creational/factorymethod/IFactory.java
xiaosanye/Design_Pattern
5944db647e9ad7967fae96db2209486d084bd604
[ "Apache-2.0" ]
null
null
null
17
36
0.784314
6,632
package creational.factorymethod; public interface IFactory { public IProduct createProduct(); }
3e0f9fcc1452e7e9e2a14a978fee2a1b6a136146
2,841
java
Java
evo-web-domain/src/main/java/com/glacier/evo/domain/sys/model/Menu.java
glacier0315/evo-admin
72c276b3ca4f206b634829cac2ce6180c6aa8e9f
[ "Apache-2.0" ]
null
null
null
evo-web-domain/src/main/java/com/glacier/evo/domain/sys/model/Menu.java
glacier0315/evo-admin
72c276b3ca4f206b634829cac2ce6180c6aa8e9f
[ "Apache-2.0" ]
null
null
null
evo-web-domain/src/main/java/com/glacier/evo/domain/sys/model/Menu.java
glacier0315/evo-admin
72c276b3ca4f206b634829cac2ce6180c6aa8e9f
[ "Apache-2.0" ]
null
null
null
20.586957
70
0.507216
6,633
package com.glacier.evo.domain.sys.model; import com.glacier.component.model.TreeEntity; /** * 菜单 * * @author glacier * @version 1.0 * date 2019-10-09 11:03 */ public class Menu extends TreeEntity<Menu> { private static final long serialVersionUID = 1207728347319595982L; /** * 端点相对路径 */ private String path; /** * 组件 */ private String component; /** * 图标 */ private String icon; /** * 权限标识 */ private String permission; /** * 类型 1 目录 2 端点 3 权限标识 */ private Integer type; /** * 状态 1 正常 2 禁用 */ private Integer status; /** * 是否显示 1 显示 2 隐藏 */ private Integer visible; /** * 是否外链 1 是 2 否 */ private Integer isFrame; public static long getSerialVersionUID() { return serialVersionUID; } public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public String getComponent() { return this.component; } public void setComponent(String component) { this.component = component; } public String getIcon() { return this.icon; } public void setIcon(String icon) { this.icon = icon; } public String getPermission() { return this.permission; } public void setPermission(String permission) { this.permission = permission; } public Integer getType() { return this.type; } public void setType(Integer type) { this.type = type; } public Integer getStatus() { return this.status; } public void setStatus(Integer status) { this.status = status; } public Integer getVisible() { return this.visible; } public void setVisible(Integer visible) { this.visible = visible; } public Integer getIsFrame() { return this.isFrame; } public void setIsFrame(Integer isFrame) { this.isFrame = isFrame; } @Override public String toString() { return "Menu{" + "path='" + this.path + '\'' + ", component='" + this.component + '\'' + ", icon='" + this.icon + '\'' + ", permission='" + this.permission + '\'' + ", type=" + this.type + ", status=" + this.status + ", visible=" + this.visible + ", isFrame=" + this.isFrame + ", name='" + this.name + '\'' + ", parentId='" + this.parentId + '\'' + ", orderNum=" + this.orderNum + ", grade=" + this.grade + ", children=" + this.children + ", id='" + this.id + '\'' + '}'; } }
3e0fa03124384b42d9e5ba90bc0d49b5295cf5ca
1,987
java
Java
app/src/main/java/com/lanshiqin/algorithm/leetcode/a297/Codec.java
lanshiqin/algorithm
259f0a19c7b21a94d655e295c116e75c2356c794
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/lanshiqin/algorithm/leetcode/a297/Codec.java
lanshiqin/algorithm
259f0a19c7b21a94d655e295c116e75c2356c794
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/lanshiqin/algorithm/leetcode/a297/Codec.java
lanshiqin/algorithm
259f0a19c7b21a94d655e295c116e75c2356c794
[ "Apache-2.0" ]
null
null
null
23.939759
92
0.625566
6,634
package com.lanshiqin.algorithm.leetcode.a297; import com.lanshiqin.algorithm.leetcode.TreeNode; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * 297. 二叉树的序列化与反序列化 * 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 * * 请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 * * 提示: 输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。 * * * 示例 1: * * * 输入:root = [1,2,3,null,null,4,5] * 输出:[1,2,3,null,null,4,5] * 示例 2: * * 输入:root = [] * 输出:[] * 示例 3: * * 输入:root = [1] * 输出:[1] * 示例 4: * * 输入:root = [1,2] * 输出:[1,2] * * 提示: * * 树中结点数在范围 [0, 104] 内 * -1000 <= Node.val <= 1000 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuffer str = new StringBuffer(); dfs(root,str); return str.toString(); } public void dfs(TreeNode root, StringBuffer str){ if(root==null){ str.append("null,"); return; } str.append(root.val).append(","); dfs(root.left,str); dfs(root.right,str); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { String[] dataArray = data.split(","); List<String> dataList = new LinkedList<>(Arrays.asList(dataArray)); return buildTree(dataList); } public TreeNode buildTree(List<String> dataList){ if ("null".equals(dataList.get(0))){ dataList.remove(0); return null; } TreeNode root = new TreeNode(Integer.parseInt(dataList.get(0))); dataList.remove(0); root.left = buildTree(dataList); root.right = buildTree(dataList); return root; } }
3e0fa191222b06431d6d0dd5abbbfb64c9b2091d
457
java
Java
src/main/java/org/swrlapi/exceptions/SWRLBuiltInLibraryException.java
RalphBln/swrlapi
a8df6e0a5a0ff5920d19d0fcda0517c32c13b68e
[ "BSD-2-Clause" ]
89
2015-04-20T07:49:38.000Z
2022-03-05T15:52:21.000Z
src/main/java/org/swrlapi/exceptions/SWRLBuiltInLibraryException.java
RalphBln/swrlapi
a8df6e0a5a0ff5920d19d0fcda0517c32c13b68e
[ "BSD-2-Clause" ]
76
2015-04-06T17:45:03.000Z
2022-03-17T17:51:03.000Z
src/main/java/org/swrlapi/exceptions/SWRLBuiltInLibraryException.java
RalphBln/swrlapi
a8df6e0a5a0ff5920d19d0fcda0517c32c13b68e
[ "BSD-2-Clause" ]
48
2015-01-31T18:21:51.000Z
2022-02-21T14:59:55.000Z
24.052632
88
0.754923
6,635
package org.swrlapi.exceptions; import org.checkerframework.checker.nullness.qual.NonNull; public class SWRLBuiltInLibraryException extends SWRLBuiltInBridgeException { private static final long serialVersionUID = 1L; public SWRLBuiltInLibraryException(@NonNull String message) { super(message); } public SWRLBuiltInLibraryException(@NonNull String message, @NonNull Throwable cause) { super(message, cause); } }
3e0fa1a8e3555a25268b484d203b38311ebb034b
922
java
Java
app/src/androidTest/java/es/albertopeam/apparchitecturelibs/notes/RecyclerViewItemCountAssertion.java
albertopeam/android-infrastructure
7e2e7e52ab1550b3acf44ec51a6c8d81c157f1f6
[ "MIT" ]
3
2017-05-23T05:52:08.000Z
2017-06-24T10:59:02.000Z
app/src/androidTest/java/es/albertopeam/apparchitecturelibs/notes/RecyclerViewItemCountAssertion.java
albertopeam/Android-Architecture-Components
7e2e7e52ab1550b3acf44ec51a6c8d81c157f1f6
[ "MIT" ]
8
2017-07-28T21:59:45.000Z
2017-12-19T17:48:01.000Z
app/src/androidTest/java/es/albertopeam/apparchitecturelibs/notes/RecyclerViewItemCountAssertion.java
albertopeam/Android-Infrastructure
7e2e7e52ab1550b3acf44ec51a6c8d81c157f1f6
[ "MIT" ]
null
null
null
31.793103
80
0.775488
6,636
package es.albertopeam.apparchitecturelibs.notes; import android.support.test.espresso.NoMatchingViewException; import android.support.test.espresso.ViewAssertion; import android.support.v7.widget.RecyclerView; import android.view.View; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class RecyclerViewItemCountAssertion implements ViewAssertion { private final int expectedCount; public RecyclerViewItemCountAssertion(int expectedCount) { this.expectedCount = expectedCount; } @Override public void check(View view, NoMatchingViewException noViewFoundException) { if (noViewFoundException != null) { throw noViewFoundException; } RecyclerView recyclerView = (RecyclerView) view; RecyclerView.Adapter adapter = recyclerView.getAdapter(); assertThat(adapter.getItemCount(), is(expectedCount)); } }
3e0fa1d04370b679cb9d86d9b3863b1a429da67a
1,132
java
Java
src/com/dio/loop/Tabuada.java
Daniel-Fonseca-da-Silva/Estruturas-de-Repeticao-e-Arrays-em-Java
be7acd0fbff04ebbff4b2478e0ce6a5811552469
[ "MIT" ]
1
2022-02-03T04:37:50.000Z
2022-02-03T04:37:50.000Z
src/com/dio/loop/Tabuada.java
Daniel-Fonseca-da-Silva/Estruturas-de-Repeticao-e-Arrays-em-Java
be7acd0fbff04ebbff4b2478e0ce6a5811552469
[ "MIT" ]
null
null
null
src/com/dio/loop/Tabuada.java
Daniel-Fonseca-da-Silva/Estruturas-de-Repeticao-e-Arrays-em-Java
be7acd0fbff04ebbff4b2478e0ce6a5811552469
[ "MIT" ]
null
null
null
24.608696
88
0.538869
6,637
package com.dio.loop; import java.util.Scanner; public class Tabuada { /* Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10. O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo: Tabuada de 5: 5 X 1 = 5 5 X 2 = 10 ... 5 X 10 = 50 */ public static void main(String[] args) { int qtdTabuada = 0; int count = 0; Scanner scanner = new Scanner(System.in); System.out.println("Entre com a tabuada desejada"); qtdTabuada = scanner.nextInt(); System.out.println(qtdTabuada); for(int i = 1; i <= 10; i++) { System.out.println(qtdTabuada + "X" + i + " = " + qtdTabuada * i); } // while(count <= 10) { // System.out.println(qtdTabuada + "X" + count + " = " + qtdTabuada * count); // count++; // } // do{ // System.out.println(qtdTabuada + "X" + count + " = " + qtdTabuada * count); // count = count + 1; // }while(count <= 10); } }
3e0fa1db22644c715cfe53993df58a52f1766950
1,726
java
Java
toolkits/discourse/src/main/java/com/ossez/toolkits/codebank/common/model/request/TopicRequest.java
cwiki-us/Java-Tutorial
61bb6834e6611f7a1ee271a4a804939cbc0385c0
[ "MIT" ]
1
2021-04-26T04:18:19.000Z
2021-04-26T04:18:19.000Z
toolkits/discourse/src/main/java/com/ossez/toolkits/codebank/common/model/request/TopicRequest.java
cwiki-us/Java-Tutorial
61bb6834e6611f7a1ee271a4a804939cbc0385c0
[ "MIT" ]
2
2021-04-13T15:08:46.000Z
2021-04-13T15:09:27.000Z
toolkits/discourse/src/main/java/com/ossez/toolkits/codebank/common/model/request/TopicRequest.java
cwiki-us/Java-Tutorial
61bb6834e6611f7a1ee271a4a804939cbc0385c0
[ "MIT" ]
1
2021-12-02T04:21:33.000Z
2021-12-02T04:21:33.000Z
20.795181
73
0.656431
6,638
package com.ossez.toolkits.codebank.common.model.request; import java.io.Serializable; /** * SearchRequest Object, UI can send search String and related pagination * * @author YuCheng Hu */ public class TopicRequest implements Serializable { private static final long serialVersionUID = 6474765081240948885L; private String title; private Integer topic_id; private String raw; private Integer category; private String target_recipients; private String archetype; private String created_at; public static long getSerialVersionUID() { return serialVersionUID; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getTopic_id() { return topic_id; } public void setTopic_id(Integer topic_id) { this.topic_id = topic_id; } public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw; } public Integer getCategory() { return category; } public void setCategory(Integer category) { this.category = category; } public String getTarget_recipients() { return target_recipients; } public void setTarget_recipients(String target_recipients) { this.target_recipients = target_recipients; } public String getArchetype() { return archetype; } public void setArchetype(String archetype) { this.archetype = archetype; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } }
3e0fa21ae28934af8e66156beac7a3e972293b11
31,793
java
Java
src/main/java/com/gargoylesoftware/htmlunit/util/EncodingSniffer.java
JLLeitschuh/htmlunit
040123c134173c2e6937f89c3b5e9998d4735582
[ "Apache-2.0" ]
6
2016-11-25T13:12:35.000Z
2021-05-13T03:06:57.000Z
src/main/java/com/gargoylesoftware/htmlunit/util/EncodingSniffer.java
JLLeitschuh/htmlunit
040123c134173c2e6937f89c3b5e9998d4735582
[ "Apache-2.0" ]
null
null
null
src/main/java/com/gargoylesoftware/htmlunit/util/EncodingSniffer.java
JLLeitschuh/htmlunit
040123c134173c2e6937f89c3b5e9998d4735582
[ "Apache-2.0" ]
6
2015-05-06T09:12:51.000Z
2020-02-11T01:35:15.000Z
39.991195
135
0.546976
6,639
/* * Copyright (c) 2002-2009 Gargoyle Software 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.gargoylesoftware.htmlunit.util; import static org.apache.commons.lang.ArrayUtils.contains; import static org.apache.commons.lang.ArrayUtils.indexOf; import static org.apache.commons.lang.ArrayUtils.isEquals; import static org.apache.commons.lang.ArrayUtils.subarray; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.util.List; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Sniffs encoding settings from HTML, XML or other content. The HTML encoding sniffing algorithm is based on the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#determining-the-character-encoding">HTML5 * encoding sniffing algorithm</a>. * * @version $Revision: 4578 $ * @author Daniel Gredler */ public final class EncodingSniffer { /** Logging support. */ private static final Log LOG = LogFactory.getLog(EncodingSniffer.class); /** UTF-16 (little endian) charset name. */ static final String UTF16_LE = "UTF-16LE"; /** UTF-16 (big endian) charset name. */ static final String UTF16_BE = "UTF-16BE"; /** UTF-8 charset name. */ static final String UTF8 = "UTF-8"; /** Sequence(s) of bytes indicating the beginning of a comment. */ private static final byte[][] COMMENT_START = new byte[][] { new byte[] {'<'}, new byte[] {'!'}, new byte[] {'-'}, new byte[] {'-'} }; /** Sequence(s) of bytes indicating the beginning of a <tt>meta</tt> HTML tag. */ private static final byte[][] META_START = new byte[][] { new byte[] {'<'}, new byte[] {'m', 'M'}, new byte[] {'e', 'E'}, new byte[] {'t', 'T'}, new byte[] {'a', 'A'}, new byte[] {0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x2F} }; /** Sequence(s) of bytes indicating the beginning of miscellaneous HTML content. */ private static final byte[][] OTHER_START = new byte[][] { new byte[] {'<'}, new byte[] {'!', '/', '?'} }; /** Sequence(s) of bytes indicating the beginning of a charset specification. */ private static final byte[][] CHARSET_START = new byte[][] { new byte[] {'c', 'C'}, new byte[] {'h', 'H'}, new byte[] {'a', 'A'}, new byte[] {'r', 'R'}, new byte[] {'s', 'S'}, new byte[] {'e', 'E'}, new byte[] {'t', 'T'} }; /** * The number of HTML bytes to sniff for encoding info embedded in <tt>meta</tt> tags; * relatively large because we don't have a fallback. */ private static final int SIZE_OF_HTML_CONTENT_SNIFFED = 4096; /** * The number of XML bytes to sniff for encoding info embedded in the XML declaration; * relatively small because it's always at the very beginning of the file. */ private static final int SIZE_OF_XML_CONTENT_SNIFFED = 512; /** * Disallow instantiation of this class. */ private EncodingSniffer() { // Empty. } /** * <p>If the specified content is HTML content, this method sniffs encoding settings * from the specified HTML content and/or the corresponding HTTP headers based on the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#determining-the-character-encoding">HTML5 * encoding sniffing algorithm</a>.</p> * * <p>If the specified content is XML content, this method sniffs encoding settings * from the specified XML content and/or the corresponding HTTP headers using a custom algorithm.</p> * * <p>Otherwise, this method sniffs encoding settings from the specified content of unknown type by looking for * <tt>Content-Type</tt> information in the HTTP headers and * <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte Order Mark</a> information in the content.</p> * * <p>Note that if an encoding is found but it is not supported on the current platform, this method returns * <tt>null</tt>, as if no encoding had been found.</p> * * @param headers the HTTP response headers sent back with the content to be sniffed * @param content the content to be sniffed * @return the encoding sniffed from the specified content and/or the corresponding HTTP headers, * or <tt>null</tt> if the encoding could not be determined * @throws IOException if an IO error occurs */ public static String sniffEncoding(final List<NameValuePair> headers, final InputStream content) throws IOException { if (isHtml(headers)) { return sniffHtmlEncoding(headers, content); } else if (isXml(headers)) { return sniffXmlEncoding(headers, content); } else { return sniffUnknownContentTypeEncoding(headers, content); } } /** * Returns <tt>true</tt> if the specified HTTP response headers indicate an HTML response. * * @param headers the HTTP response headers * @return <tt>true</tt> if the specified HTTP response headers indicate an HTML response */ static boolean isHtml(final List<NameValuePair> headers) { return contentTypeEndsWith(headers, "text/html"); } /** * Returns <tt>true</tt> if the specified HTTP response headers indicate an XML response. * * @param headers the HTTP response headers * @return <tt>true</tt> if the specified HTTP response headers indicate an XML response */ static boolean isXml(final List<NameValuePair> headers) { return contentTypeEndsWith(headers, "text/xml", "application/xml", "text/vnd.wap.wml", "+xml"); } /** * Returns <tt>true</tt> if the specified HTTP response headers contain a <tt>Content-Type</tt> that * ends with one of the specified strings. * * @param headers the HTTP response headers * @param contentTypeEndings the content type endings to search for * @return <tt>true</tt> if the specified HTTP response headers contain a <tt>Content-Type</tt> that * ends with one of the specified strings */ static boolean contentTypeEndsWith(final List<NameValuePair> headers, final String... contentTypeEndings) { for (final NameValuePair pair : headers) { final String name = pair.getName(); if ("content-type".equalsIgnoreCase(name)) { String value = pair.getValue(); final int i = value.indexOf(';'); if (i != -1) { value = value.substring(0, i); } value = value.trim(); boolean found = false; for (String ending : contentTypeEndings) { if (value.toLowerCase().endsWith(ending.toLowerCase())) { found = true; break; } } return found; } } return false; } /** * <p>Sniffs encoding settings from the specified HTML content and/or the corresponding HTTP headers based on the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#determining-the-character-encoding">HTML5 * encoding sniffing algorithm</a>.</p> * * <p>Note that if an encoding is found but it is not supported on the current platform, this method returns * <tt>null</tt>, as if no encoding had been found.</p> * * @param headers the HTTP response headers sent back with the HTML content to be sniffed * @param content the HTML content to be sniffed * @return the encoding sniffed from the specified HTML content and/or the corresponding HTTP headers, * or <tt>null</tt> if the encoding could not be determined * @throws IOException if an IO error occurs */ public static String sniffHtmlEncoding(final List<NameValuePair> headers, final InputStream content) throws IOException { String encoding = sniffEncodingFromHttpHeaders(headers); if (encoding != null || content == null) { return encoding; } byte[] bytes = read(content, 3); encoding = sniffEncodingFromUnicodeBom(bytes); if (encoding != null) { return encoding; } bytes = readAndPrepend(content, SIZE_OF_HTML_CONTENT_SNIFFED, bytes); encoding = sniffEncodingFromMetaTag(bytes); return encoding; } /** * <p>Sniffs encoding settings from the specified XML content and/or the corresponding HTTP headers using * a custom algorithm.</p> * * <p>Note that if an encoding is found but it is not supported on the current platform, this method returns * <tt>null</tt>, as if no encoding had been found.</p> * * @param headers the HTTP response headers sent back with the XML content to be sniffed * @param content the XML content to be sniffed * @return the encoding sniffed from the specified XML content and/or the corresponding HTTP headers, * or <tt>null</tt> if the encoding could not be determined * @throws IOException if an IO error occurs */ public static String sniffXmlEncoding(final List<NameValuePair> headers, final InputStream content) throws IOException { String encoding = sniffEncodingFromHttpHeaders(headers); if (encoding != null || content == null) { return encoding; } byte[] bytes = read(content, 3); encoding = sniffEncodingFromUnicodeBom(bytes); if (encoding != null) { return encoding; } bytes = readAndPrepend(content, SIZE_OF_XML_CONTENT_SNIFFED, bytes); encoding = sniffEncodingFromXmlDeclaration(bytes); return encoding; } /** * <p>Sniffs encoding settings from the specified content of unknown type by looking for <tt>Content-Type</tt> * information in the HTTP headers and <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte Order Mark</a> * information in the content.</p> * * <p>Note that if an encoding is found but it is not supported on the current platform, this method returns * <tt>null</tt>, as if no encoding had been found.</p> * * @param headers the HTTP response headers sent back with the content to be sniffed * @param content the content to be sniffed * @return the encoding sniffed from the specified content and/or the corresponding HTTP headers, * or <tt>null</tt> if the encoding could not be determined * @throws IOException if an IO error occurs */ public static String sniffUnknownContentTypeEncoding(final List<NameValuePair> headers, final InputStream content) throws IOException { String encoding = sniffEncodingFromHttpHeaders(headers); if (encoding != null || content == null) { return encoding; } final byte[] bytes = read(content, 3); encoding = sniffEncodingFromUnicodeBom(bytes); return encoding; } /** * Attempts to sniff an encoding from the specified HTTP headers. * * @param headers the HTTP headers to examine * @return the encoding sniffed from the specified HTTP headers, or <tt>null</tt> if the encoding * could not be determined */ static String sniffEncodingFromHttpHeaders(final List<NameValuePair> headers) { String encoding = null; for (final NameValuePair pair : headers) { final String name = pair.getName(); if ("content-type".equalsIgnoreCase(name)) { final String value = pair.getValue(); encoding = extractEncodingFromContentType(value); if (encoding != null) { break; } } } if (encoding != null && LOG.isDebugEnabled()) { LOG.debug("Encoding found in HTTP headers: '" + encoding + "'."); } return encoding; } /** * Attempts to sniff an encoding from a <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte Order Mark</a> * in the specified byte array. * * @param bytes the bytes to check for a Byte Order Mark * @return the encoding sniffed from the specified bytes, or <tt>null</tt> if the encoding * could not be determined */ static String sniffEncodingFromUnicodeBom(final byte[] bytes) { String encoding = null; final byte[] markerUTF8 = {(byte) 0xef, (byte) 0xbb, (byte) 0xbf}; final byte[] markerUTF16BE = {(byte) 0xfe, (byte) 0xff}; final byte[] markerUTF16LE = {(byte) 0xff, (byte) 0xfe}; if (bytes != null && isEquals(markerUTF8, subarray(bytes, 0, 3))) { encoding = UTF8; } else if (bytes != null && isEquals(markerUTF16BE, subarray(bytes, 0, 2))) { encoding = UTF16_BE; } else if (bytes != null && isEquals(markerUTF16LE, subarray(bytes, 0, 2))) { encoding = UTF16_LE; } if (encoding != null && LOG.isDebugEnabled()) { LOG.debug("Encoding found in Unicode Byte Order Mark: '" + encoding + "'."); } return encoding; } /** * Attempts to sniff an encoding from an HTML <tt>meta</tt> tag in the specified byte array. * * @param bytes the bytes to check for an HTML <tt>meta</tt> tag * @return the encoding sniffed from the specified bytes, or <tt>null</tt> if the encoding * could not be determined */ static String sniffEncodingFromMetaTag(final byte[] bytes) { for (int i = 0; i < bytes.length; i++) { if (matches(bytes, i, COMMENT_START)) { i = indexOfSubArray(bytes, new byte[] {'-', '-', '>'}, i); if (i == -1) { break; } i += 2; } else if (matches(bytes, i, META_START)) { i += META_START.length; for (Attribute att = getAttribute(bytes, i); att != null; att = getAttribute(bytes, i)) { i = att.getUpdatedIndex(); final String name = att.getName(); final String value = att.getValue(); if ("charset".equals(name) || "content".equals(name)) { String charset = null; if ("charset".equals(name)) { charset = value; } else if ("content".equals(name)) { charset = extractEncodingFromContentType(value); if (charset == null) { continue; } } if (UTF16_BE.equalsIgnoreCase(charset) || UTF16_LE.equalsIgnoreCase(charset)) { charset = UTF8; } if (isSupportedCharset(charset)) { if (LOG.isDebugEnabled()) { LOG.debug("Encoding found in meta tag: '" + charset + "'."); } return charset; } } } } else if (i + 1 < bytes.length && bytes[i] == '<' && Character.isLetter(bytes[i + 1])) { i = skipToAnyOf(bytes, i, new byte[] {0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3E}); if (i == -1) { break; } Attribute att; while ((att = getAttribute(bytes, i)) != null) { i = att.getUpdatedIndex(); } } else if (i + 2 < bytes.length && bytes[i] == '<' && bytes[i + 1] == '/' && Character.isLetter(bytes[i + 2])) { i = skipToAnyOf(bytes, i, new byte[] {0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3E}); if (i == -1) { break; } Attribute attribute; while ((attribute = getAttribute(bytes, i)) != null) { i = attribute.getUpdatedIndex(); } } else if (matches(bytes, i, OTHER_START)) { i = skipToAnyOf(bytes, i, new byte[] {0x3E}); if (i == -1) { break; } } } return null; } /** * Extracts an attribute from the specified byte array, starting at the specified index, using the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#concept-get-attributes-when-sniffing">HTML5 * attribute algorithm</a>. * * @param bytes the byte array to extract an attribute from * @param i the index to start searching from * @return the next attribute in the specified byte array, or <tt>null</tt> if one is not available */ static Attribute getAttribute(final byte[] bytes, int i) { if (i >= bytes.length) { return null; } while (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20 || bytes[i] == 0x2F) { i++; if (i >= bytes.length) { return null; } } if (bytes[i] == '>') { return null; } String name = ""; String value = ""; for ( ;; i++) { if (i >= bytes.length) { return new Attribute(name, value, i); } if (bytes[i] == '=' && name.length() > 0) { i++; break; } if (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20) { while (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20) { i++; if (i >= bytes.length) { return new Attribute(name, value, i); } } if (bytes[i] != '=') { return new Attribute(name, value, i); } i++; break; } if (bytes[i] == '/' || bytes[i] == '>') { return new Attribute(name, value, i); } name += (char) bytes[i]; } if (i >= bytes.length) { return new Attribute(name, value, i); } while (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20) { i++; if (i >= bytes.length) { return new Attribute(name, value, i); } } if (bytes[i] == '"' || bytes[i] == '\'') { final byte b = bytes[i]; for (i++; i < bytes.length; i++) { if (bytes[i] == b) { i++; return new Attribute(name, value, i); } else if (bytes[i] >= 'A' && bytes[i] <= 'Z') { final byte b2 = (byte) (bytes[i] + 0x20); value += (char) b2; } else { value += (char) bytes[i]; } } return new Attribute(name, value, i); } else if (bytes[i] == '>') { return new Attribute(name, value, i); } else if (bytes[i] >= 'A' && bytes[i] <= 'Z') { final byte b = (byte) (bytes[i] + 0x20); value += (char) b; i++; } else { value += (char) bytes[i]; i++; } for ( ; i < bytes.length; i++) { if (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20 || bytes[i] == 0x3E) { return new Attribute(name, value, i); } else if (bytes[i] >= 'A' && bytes[i] <= 'Z') { final byte b = (byte) (bytes[i] + 0x20); value += (char) b; } else { value += (char) bytes[i]; } } return new Attribute(name, value, i); } /** * Extracts an encoding from the specified <tt>Content-Type</tt> value using * <a href="http://ietfreport.isoc.org/idref/draft-abarth-mime-sniff/">the IETF algorithm</a>; if * no encoding is found, this method returns <tt>null</tt>. * * @param s the <tt>Content-Type</tt> value to search for an encoding * @return the encoding found in the specified <tt>Content-Type</tt> value, or <tt>null</tt> if no * encoding was found */ static String extractEncodingFromContentType(final String s) { if (s == null) { return null; } final byte[] bytes = s.getBytes(); int i; for (i = 0; i < bytes.length; i++) { if (matches(bytes, i, CHARSET_START)) { i += CHARSET_START.length; break; } } if (i == bytes.length) { return null; } while (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20) { i++; if (i == bytes.length) { return null; } } if (bytes[i] != '=') { return null; } i++; if (i == bytes.length) { return null; } while (bytes[i] == 0x09 || bytes[i] == 0x0A || bytes[i] == 0x0C || bytes[i] == 0x0D || bytes[i] == 0x20) { i++; if (i == bytes.length) { return null; } } if (bytes[i] == '"') { if (bytes.length <= i + 1) { return null; } final int index = indexOf(bytes, (byte) '"', i + 1); if (index == -1) { return null; } final String charset = new String(subarray(bytes, i + 1, index)); return isSupportedCharset(charset) ? charset : null; } if (bytes[i] == '\'') { if (bytes.length <= i + 1) { return null; } final int index = indexOf(bytes, (byte) '\'', i + 1); if (index == -1) { return null; } final String charset = new String(subarray(bytes, i + 1, index)); return isSupportedCharset(charset) ? charset : null; } int end = skipToAnyOf(bytes, i, new byte[] {0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x3B}); if (end == -1) { end = bytes.length; } final String charset = new String(subarray(bytes, i, end)); return isSupportedCharset(charset) ? charset : null; } /** * Searches the specified XML content for an XML declaration and returns the encoding if found, * otherwise returns <tt>null</tt>. * * @param bytes the XML content to sniff * @return the encoding of the specified XML content, or <tt>null</tt> if it could not be determined */ static String sniffEncodingFromXmlDeclaration(final byte[] bytes) { String encoding = null; final byte[] declarationPrefix = "<?xml ".getBytes(); if (isEquals(declarationPrefix, subarray(bytes, 0, declarationPrefix.length))) { final int index = ArrayUtils.indexOf(bytes, (byte) '?', 2); if (index + 1 < bytes.length && bytes[index + 1] == '>') { final String declaration = new String(bytes, 0, index + 2); int start = declaration.indexOf("encoding"); if (start != -1) { start += 8; char delimiter; outer: while (true) { switch (declaration.charAt(start)) { case '"': case '\'': delimiter = declaration.charAt(start); start = start + 1; break outer; default: start++; } } final int end = declaration.indexOf(delimiter, start); encoding = declaration.substring(start, end); } } } if (encoding != null && !isSupportedCharset(encoding)) { encoding = null; } if (encoding != null && LOG.isDebugEnabled()) { LOG.debug("Encoding found in XML declaration: '" + encoding + "'."); } return encoding; } /** * Returns <tt>true</tt> if the specified charset is supported on this platform. * * @param charset the charset to check * @return <tt>true</tt> if the specified charset is supported on this platform */ static boolean isSupportedCharset(final String charset) { try { return Charset.isSupported(charset); } catch (final IllegalCharsetNameException e) { return false; } } /** * Returns <tt>true</tt> if the byte in the specified byte array at the specified index matches one of the * specified byte array patterns. * * @param bytes the byte array to search in * @param i the index at which to search * @param sought the byte array patterns to search for * @return <tt>true</tt> if the byte in the specified byte array at the specified index matches one of the * specified byte array patterns */ static boolean matches(final byte[] bytes, final int i, final byte[][] sought) { if (i + sought.length > bytes.length) { return false; } for (int x = 0; x < sought.length; x++) { final byte[] possibilities = sought[x]; boolean match = false; for (int y = 0; y < possibilities.length; y++) { if (bytes[i + x] == possibilities[y]) { match = true; break; } } if (!match) { return false; } } return true; } /** * Skips ahead to the first occurrence of any of the specified targets within the specified array, * starting at the specified index. This method returns <tt>-1</tt> if none of the targets are found. * * @param bytes the array to search through * @param i the index to start looking at * @param targets the targets to search for * @return the index of the first occurrence of any of the specified targets within the specified array */ static int skipToAnyOf(final byte[] bytes, int i, final byte[] targets) { for ( ; i < bytes.length; i++) { if (contains(targets, bytes[i])) { break; } } if (i == bytes.length) { i = -1; } return i; } /** * Finds the first index of the specified sub-array inside the specified array, starting at the * specified index. This method returns <tt>-1</tt> if the specified sub-array cannot be found. * * @param array the array to traverse for looking for the sub-array * @param subarray the sub-array to find * @param startIndex the start index to traverse forwards from * @return the index of the sub-array within the array */ static int indexOfSubArray(final byte[] array, final byte[] subarray, final int startIndex) { for (int i = startIndex; i < array.length; i++) { boolean found = true; for (int j = 0; j < subarray.length; j++) { final byte a = array[i + j]; final byte b = subarray[j]; if (a != b) { found = false; break; } } if (found) { return i; } } return -1; } /** * Attempts to read <tt>size</tt> bytes from the specified input stream. Note that this method is not guaranteed * to be able to read <tt>size</tt> bytes; however, the returned byte array will always be the exact length of the * number of bytes read. * * @param content the input stream to read from * @param size the number of bytes to try to read * @return the bytes read from the specified input stream * @throws IOException if an IO error occurs */ static byte[] read(final InputStream content, final int size) throws IOException { byte[] bytes = new byte[size]; final int count = content.read(bytes); if (count == -1) { bytes = new byte[0]; } else if (count < size) { final byte[] smaller = new byte[count]; System.arraycopy(bytes, 0, smaller, 0, count); bytes = smaller; } return bytes; } /** * Attempts to read <tt>size</tt> bytes from the specified input stream and then prepends the specified prefix to * the bytes read, returning the resultant byte array. Note that this method is not guaranteed to be able to read * <tt>size</tt> bytes; however, the returned byte array will always be the exact length of the number of bytes * read plus the length of the prefix array. * * @param content the input stream to read from * @param size the number of bytes to try to read * @param prefix the byte array to prepend to the bytes read from the specified input stream * @return the bytes read from the specified input stream, prefixed by the specified prefix * @throws IOException if an IO error occurs */ static byte[] readAndPrepend(final InputStream content, final int size, final byte[] prefix) throws IOException { final byte[] bytes = read(content, size); final byte[] joined = new byte[prefix.length + bytes.length]; System.arraycopy(prefix, 0, joined, 0, prefix.length); System.arraycopy(bytes, 0, joined, prefix.length, bytes.length); return joined; } static class Attribute { private final String name_; private final String value_; private final int updatedIndex_; Attribute(final String name, final String value, final int updatedIndex) { name_ = name; value_ = value; updatedIndex_ = updatedIndex; } String getName() { return name_; } String getValue() { return value_; } int getUpdatedIndex() { return updatedIndex_; } } }
3e0fa2a05e7ff9e2190e846a6bcfa69ede9699b6
7,137
java
Java
library/src/main/java/com/yarolegovich/discretescrollview/DiscreteScrollView.java
intersimone999/DiscreteScrollView
e0c27d5dedede3838c8a66a8c551a40a699e9b19
[ "Apache-2.0" ]
null
null
null
library/src/main/java/com/yarolegovich/discretescrollview/DiscreteScrollView.java
intersimone999/DiscreteScrollView
e0c27d5dedede3838c8a66a8c551a40a699e9b19
[ "Apache-2.0" ]
null
null
null
library/src/main/java/com/yarolegovich/discretescrollview/DiscreteScrollView.java
intersimone999/DiscreteScrollView
e0c27d5dedede3838c8a66a8c551a40a699e9b19
[ "Apache-2.0" ]
null
null
null
34.814634
105
0.651814
6,640
package com.yarolegovich.discretescrollview; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import com.yarolegovich.discretescrollview.transform.DiscreteScrollItemTransformer; import com.yarolegovich.discretescrollview.util.ScrollListenerAdapter; /** * Created by yarolegovich on 18.02.2017. */ @SuppressWarnings("unchecked") public class DiscreteScrollView extends RecyclerView { private static final int DEFAULT_ORIENTATION = Orientation.HORIZONTAL.ordinal(); private DiscreteScrollLayoutManager layoutManager; private ScrollStateChangeListener scrollStateChangeListener; private OnItemChangedListener onItemChangedListener; public DiscreteScrollView(Context context) { super(context); init(null); } public DiscreteScrollView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public DiscreteScrollView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } private void init(AttributeSet attrs) { int orientation = DEFAULT_ORIENTATION; if (attrs != null) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DiscreteScrollView); orientation = ta.getInt(R.styleable.DiscreteScrollView_dsv_orientation, DEFAULT_ORIENTATION); ta.recycle(); } layoutManager = new DiscreteScrollLayoutManager( getContext(), new ScrollStateListener(), Orientation.values()[orientation]); setLayoutManager(layoutManager); } @Override public void setLayoutManager(LayoutManager layout) { if (layout instanceof DiscreteScrollLayoutManager) { super.setLayoutManager(layout); } else { throw new IllegalArgumentException(getContext().getString(R.string.dsv_ex_msg_dont_set_lm)); } } @Override public boolean fling(int velocityX, int velocityY) { boolean isFling = super.fling(velocityX, velocityY); if (isFling) { layoutManager.onFling(velocityX, velocityY); } else { layoutManager.returnToCurrentPosition(); } return isFling; } @Nullable public ViewHolder getViewHolder(int position) { View view = layoutManager.findViewByPosition(position); return view != null ? getChildViewHolder(view) : null; } /** * @return adapter position of the current item or -1 if nothing is selected */ public int getCurrentItem() { return layoutManager.getCurrentPosition(); } public void setItemTransformer(DiscreteScrollItemTransformer transformer) { layoutManager.setItemTransformer(transformer); } public void setItemTransitionTimeMillis(@IntRange(from = 10) int millis) { layoutManager.setTimeForItemSettle(millis); } public void setOrientation(Orientation orientation) { layoutManager.setOrientation(orientation); } public void setScrollStateChangeListener(ScrollStateChangeListener<?> scrollStateChangeListener) { this.scrollStateChangeListener = scrollStateChangeListener; } public void setScrollListener(ScrollListener<?> scrollListener) { setScrollStateChangeListener(new ScrollListenerAdapter(scrollListener)); } public void setOnItemChangedListener(OnItemChangedListener<?> onItemChangedListener) { this.onItemChangedListener = onItemChangedListener; } private class ScrollStateListener implements DiscreteScrollLayoutManager.ScrollStateListener { @Override public void onIsBoundReachedFlagChange(boolean isBoundReached) { setOverScrollMode(isBoundReached ? OVER_SCROLL_ALWAYS : OVER_SCROLL_NEVER); } @Override public void onScrollStart() { if (scrollStateChangeListener != null) { int current = layoutManager.getCurrentPosition(); ViewHolder holder = getViewHolder(current); if (holder != null) { scrollStateChangeListener.onScrollStart(holder, current); } } } @Override public void onScrollEnd() { ViewHolder currentHolder = null; int currentHolder = layoutManager.getCurrentPosition(); if (scrollStateChangeListener != null) { holder = getViewHolder(currentHolder); if (holder == null) { return; } scrollStateChangeListener.onScrollEnd(holder, currentHolder); } if (onItemChangedListener != null) { if (holder == null) { holder = getViewHolder(currentHolder); } if (holder != null) { onItemChangedListener.onCurrentItemChanged(holder, currentHolder); } } } @Override public void onScroll(float currentViewPosition) { if (scrollStateChangeListener != null) { int current = getCurrentItem(); ViewHolder currentHolder = getViewHolder(getCurrentItem()); int newCurrent = current + (currentViewPosition < 0 ? 1 : -1); ViewHolder newCurrentHolder = getViewHolder(newCurrent); if (currentHolder != null && newCurrentHolder != null) { scrollStateChangeListener.onScroll( currentViewPosition, currentHolder, newCurrentHolder); } } } @Override public void onCurrentViewFirstLayout() { if (onItemChangedListener != null) { int current = layoutManager.getCurrentPosition(); ViewHolder holder = getViewHolder(current); if (holder != null) { onItemChangedListener.onCurrentItemChanged(holder, current); } } } } public interface ScrollStateChangeListener<T extends ViewHolder> { void onScrollStart(@NonNull T currentItemHolder, int adapterPosition); void onScrollEnd(@NonNull T currentItemHolder, int adapterPosition); void onScroll(float scrollPosition, @NonNull T currentHolder, @NonNull T newCurrent); } public interface ScrollListener<T extends ViewHolder> { void onScroll(float scrollPosition, @NonNull T currentHolder, @NonNull T newCurrent); } public interface OnItemChangedListener<T extends ViewHolder> { /* * This method will be also triggered when view appears on the screen for the first time. */ void onCurrentItemChanged(@NonNull T viewHolder, int adapterPosition); } }
3e0fa2a339a26b000c1d9a761e6d2d316de74cc1
7,561
java
Java
src/ucar/unidata/util/MidiProperties.java
oxelson/IDV
06ea41150e6a303c5c59d5aa59b1907a5a6e488b
[ "CNRI-Jython" ]
48
2015-02-22T05:05:01.000Z
2022-03-14T14:23:41.000Z
src/ucar/unidata/util/MidiProperties.java
oxelson/IDV
06ea41150e6a303c5c59d5aa59b1907a5a6e488b
[ "CNRI-Jython" ]
40
2015-02-09T19:25:29.000Z
2022-02-16T00:21:08.000Z
src/ucar/unidata/util/MidiProperties.java
oxelson/IDV
06ea41150e6a303c5c59d5aa59b1907a5a6e488b
[ "CNRI-Jython" ]
28
2015-04-03T05:43:00.000Z
2022-01-31T23:41:20.000Z
26.742049
78
0.573071
6,641
/* * $Id: MidiProperties.java,v 1.5 2006/12/03 17:15:15 dmurray Exp $ * * Copyright 1997-2022 Unidata Program Center/University Corporation for * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307, * upchh@example.com. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * * This library 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package ucar.unidata.util; import java.awt.Insets; import java.awt.Window; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.sound.midi.*; import javax.swing.*; /** * A class to hold properties for a MidiManager * * * @author IDV Development Team * @version $Revision: 1.5 $ */ public class MidiProperties { /** Are we playing sound */ private boolean muted = true; /** The lowest note */ private int lowNote = 0; /** The highest note */ private int highNote = 127; /** The current instrument */ private String instrumentName = null; /** For properties */ private JTextField spanFld; /** For properties */ private JComboBox instrumentBox; /** For properties */ JCheckBox mutedCbx; /** For properties */ private JTextField lowNoteFld; /** For properties */ private JTextField highNoteFld; /** * Default ctor. */ public MidiProperties() {} /** * Create a new MidiProperties * * @param instrumentName name of the instrument * @param lowNote low note value * @param highNote high note value * @param muted true if muted */ public MidiProperties(String instrumentName, int lowNote, int highNote, boolean muted) { this.instrumentName = instrumentName; this.lowNote = lowNote; this.highNote = highNote; this.muted = muted; } /** * Copy constructor * * @param that the other properties object */ public MidiProperties(MidiProperties that) { this.instrumentName = that.instrumentName; this.lowNote = that.lowNote; this.highNote = that.highNote; this.muted = that.muted; } /** * Set the InstrumentIndex property. * * @param value The new value for InstrumentIndex */ public void setInstrumentName(String value) { instrumentName = value; } /** * Get the Instrument property. * * @return The Instrument */ public String getInstrumentName() { return instrumentName; } /** * Set the Muted property. * * @param value The new value for Muted */ public void setMuted(boolean value) { muted = value; } /** * Get the Muted property. * * @return The Muted */ public boolean getMuted() { return muted; } /** * Set the LowNote property. * * @param value The new value for LowNote */ public void setLowNote(int value) { lowNote = value; } /** * Get the LowNote property. * * @return The LowNote */ public int getLowNote() { return lowNote; } /** * Set the HighNote property. * * @param value The new value for HighNote */ public void setHighNote(int value) { highNote = value; } /** * Get the HighNote property. * * @return The HighNote */ public int getHighNote() { return highNote; } /** * Set the properties from another. * * @param that the other */ public void setProperties(MidiProperties that) { this.instrumentName = that.instrumentName; this.lowNote = that.lowNote; this.highNote = that.highNote; this.muted = that.muted; } /** * Show a Dialog for setting the properties. * @param w Window for anchor * @return true if properties changed */ public boolean showPropertyDialog(Window w) { List comps = getPropertiesComponents(new ArrayList()); GuiUtils.tmpInsets = new Insets(5, 5, 5, 5); JComponent contents = GuiUtils.doLayout(comps, 2, GuiUtils.WT_NY, GuiUtils.WT_N); if ( !GuiUtils.showOkCancelDialog(w, "MidiManager Properties", contents, null)) { return false; } return applyProperties(); } /** * Apply properties * * @return success */ public boolean applyProperties() { TwoFacedObject tfo = (TwoFacedObject) instrumentBox.getSelectedItem(); instrumentName = tfo.toString(); muted = mutedCbx.isSelected(); lowNote = new Integer(lowNoteFld.getText().trim()).intValue(); highNote = new Integer(highNoteFld.getText().trim()).intValue(); // allow for inverted range if (highNote < lowNote) { lowNote = Math.max(lowNote, 0); highNote = Math.min(highNote, 127); } else { lowNote = Math.min(lowNote, 127); highNote = Math.max(highNote, 0); } return true; } /** * Get the Components for setting the properties * * @param comps compnents to add to * * @return the list for this. */ public List getPropertiesComponents(List comps) { comps.add(GuiUtils.filler()); comps.add(GuiUtils.left(mutedCbx = new JCheckBox("Muted", getMuted()))); comps.add(GuiUtils.rLabel("Instrument: ")); Vector v = new Vector(); Instrument[] instruments = MidiManager.getInstrumentList(); TwoFacedObject selected = new TwoFacedObject("None", new Integer(-1)); if(instruments!=null) { for (int i = 0; (i < instruments.length) && (i < 128); i++) { if(instruments[i]==null) continue; String name = instruments[i].getName(); if(name==null) continue; TwoFacedObject tfo = new TwoFacedObject(name, new Integer(i)); if (name.equals(instrumentName)) { selected = tfo; } v.add(tfo); } } comps.add(GuiUtils.left(instrumentBox = new JComboBox(v))); instrumentBox.setSelectedItem(selected); lowNoteFld = new JTextField("" + getLowNote(), 5); highNoteFld = new JTextField("" + getHighNote(), 5); comps.add(GuiUtils.rLabel("Note Range:")); comps.add( GuiUtils.left( GuiUtils.hbox( Misc.newList( new JLabel("Low: "), lowNoteFld, new JLabel("High: "), highNoteFld)))); return comps; } }
3e0fa2b49c38492ba6ab4326d1b1145985a13f56
16,160
java
Java
src/test/java/fi/riista/feature/permit/application/dogevent/unleash/DogEventUnleashFeatureTest.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
14
2017-01-11T23:22:36.000Z
2022-02-09T06:49:46.000Z
src/test/java/fi/riista/feature/permit/application/dogevent/unleash/DogEventUnleashFeatureTest.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
4
2018-04-16T13:00:49.000Z
2021-02-15T11:56:06.000Z
src/test/java/fi/riista/feature/permit/application/dogevent/unleash/DogEventUnleashFeatureTest.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
4
2017-01-20T10:34:24.000Z
2021-02-09T14:41:46.000Z
39.318735
121
0.657116
6,642
package fi.riista.feature.permit.application.dogevent.unleash; import com.google.common.base.Strings; import fi.riista.feature.account.user.SystemUser; import fi.riista.feature.harvestpermit.HarvestPermitCategory; import fi.riista.feature.organization.person.Person; import fi.riista.feature.organization.rhy.Riistanhoitoyhdistys; import fi.riista.feature.permit.application.HarvestPermitApplication; import fi.riista.feature.permit.application.PermitHolder; import fi.riista.feature.permit.application.dogevent.DogEventUnleash; import fi.riista.feature.permit.application.dogevent.DogEventUnleashRepository; import fi.riista.test.EmbeddedDatabaseTest; import fi.riista.util.DateUtil; import org.junit.Before; import org.junit.Test; import org.springframework.security.access.AccessDeniedException; import javax.annotation.Resource; import javax.validation.ConstraintViolationException; import java.util.Arrays; import java.util.List; import java.util.Optional; import static fi.riista.feature.permit.application.dogevent.DogEventType.DOG_TRAINING; import static fi.riista.test.Asserts.assertThat; import static java.util.Collections.emptyList; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; public class DogEventUnleashFeatureTest extends EmbeddedDatabaseTest { @Resource private DogEventUnleashRepository repository; @Resource private DogEventUnleashFeature feature; private Person applicant; private Riistanhoitoyhdistys rhy; private HarvestPermitApplication application; private SystemUser user; @Before public void setUp() { applicant = model().newPerson(); rhy = model().newRiistanhoitoyhdistys(); application = model().newHarvestPermitApplication(rhy, null, HarvestPermitCategory.DOG_UNLEASH); model().newHuntingDogEventPermitApplication(application); application.setStatus(HarvestPermitApplication.Status.DRAFT); application.setPermitHolder(PermitHolder.createHolderForPerson(applicant)); application.setContactPerson(applicant); user = createNewUser("applicant", applicant); persistInNewTransaction(); } @Test(expected = AccessDeniedException.class) public void getEvents_unauthorized() { onSavedAndAuthenticated(createNewUser(), () -> { feature.getEvents(application.getId()); }); } @Test public void getEvents_noDetailsStored() { onAuthenticated(user, () -> { final List<DogEventUnleashDTO> events = feature.getEvents(application.getId()); assertEquals(emptyList(), events); }); } @Test public void getEvents_detailsFound() { final List<DogEventUnleash> expected = Arrays.asList(model().newDogEventUnleash(application), model().newDogEventUnleash(application)); onSavedAndAuthenticated(user, () -> { final List<DogEventUnleashDTO> actual = feature.getEvents(application.getId()); assertDTOsEqualsToEntities(actual, expected); }); } @Test(expected = AccessDeniedException.class) public void updateEvent_unauthorized() { onSavedAndAuthenticated(createNewUser(), () -> { feature.updateEvent(application.getId(), newEventDto(1)); }); } @Test public void updateEvent_addNewEvents() { onAuthenticated(user, () -> { final List<DogEventUnleashDTO> expected = Arrays.asList(newEventDto(1), newEventDto(2)); expected.stream().forEach(e -> feature.updateEvent(application.getId(), e)); final List<DogEventUnleash> actual = repository.findAllByHarvestPermitApplication(application); assertDTOsEqualsToEntities(expected, actual); }); } @Test public void updateEvent_updateExistingEvent() { model().newDogEventUnleash(application); onSavedAndAuthenticated(user, () -> { final List<DogEventUnleashDTO> expected = feature.getEvents(application.getId()); expected.get(0).setDogsAmount(1); feature.updateEvent(application.getId(), expected.get(0)); final List<DogEventUnleash> actual = repository.findAllByHarvestPermitApplication(application); assertThat(actual.size(), equalTo(1)); assertDTOsEqualsToEntities(expected, actual); }); } @Test public void deleteEvent() { final List<DogEventUnleash> expected = Arrays.asList(model().newDogEventUnleash(application), model().newDogEventUnleash(application)); final DogEventUnleash eventToBeRemoved = model().newDogEventUnleash(application); onSavedAndAuthenticated(user, () -> { feature.deleteEvent(application.getId(), eventToBeRemoved.getId()); final List<DogEventUnleash> actual = repository.findAllByHarvestPermitApplication(application); assertThat(actual.size(), equalTo(2)); assertEntitiesEquals(expected, actual); }); } @Test(expected = AccessDeniedException.class) public void deleteEvent_unauthorized() { final DogEventUnleash event = model().newDogEventUnleash(application); onSavedAndAuthenticated(createNewUser(), () -> { feature.deleteEvent(application.getId(), event.getId()); }); } /** * * Data validation tests * */ @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_beginDateNotSet() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setBeginDate(null); feature.updateEvent(application.getId(), event); }); } @Test public void updateEvents_validate_beginDateInPast() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setBeginDate(DateUtil.today().minusDays(1)); feature.updateEvent(application.getId(), event); }); } @Test public void updateEvents_validate_beginDateToday() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setBeginDate(DateUtil.today()); feature.updateEvent(application.getId(), event); }); } @Test public void updateEvents_validate_endDateNotSet() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setEndDate(null); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_endDateInPast() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setEndDate(DateUtil.today().minusDays(1)); feature.updateEvent(application.getId(), event); }); } @Test public void updateEvents_validate_endDateToday() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setBeginDate(DateUtil.today()); event.setEndDate(DateUtil.today()); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_endDateBeforeStartDay() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setBeginDate(DateUtil.today().plusDays(1)); event.setEndDate(DateUtil.today()); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_dogsAmountTooSmall() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(0); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_dogsAmountTooBig() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(10000); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_naturaAreaTooLong() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setNaturaArea(Strings.repeat("x", 256)); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_naturaAreaContainsHtml() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setNaturaArea("Area <b>code</b>"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_eventDescriptionIsEmpty() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setEventDescription(""); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_eventDescriptionContainsHtml() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setEventDescription("Event <b>description</b>"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_locationDescriptionIsEmpty() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setLocationDescription(""); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_locationDescriptionContainsHtml() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setLocationDescription("Location <b>description</b>"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_contactNameIsEmpty() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setContactName(""); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_contactNameContainsHtml() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setContactName("Contact <b>name</b>"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_contactMailHasNoAtChar() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setContactMail("contact.mail"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_contactPhoneIsEmpty() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setContactPhone(""); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_contactPhoneContainsCharacter() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setContactPhone("+123x"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_additionalInfoContainsHtml() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setAdditionalInfo("Additional <pre>info</pre>"); feature.updateEvent(application.getId(), event); }); } @Test(expected = ConstraintViolationException.class) public void updateEvents_validate_geoLocationIsNull() { onAuthenticated(user, () -> { final DogEventUnleashDTO event = newEventDto(1); event.setGeoLocation(null); feature.updateEvent(application.getId(), event); }); } /** * * Helper functions * */ private DogEventUnleashDTO newEventDto(final int dogsAmount) { final DogEventUnleashDTO event = new DogEventUnleashDTO(); event.setId(null); event.setEventType(DOG_TRAINING); event.setBeginDate(DateUtil.today().plusDays(1)); event.setEndDate(DateUtil.today().plusDays(2)); event.setDogsAmount(dogsAmount); event.setNaturaArea("Natura area code"); event.setEventDescription("Event description"); event.setLocationDescription("Location description"); event.setContactName("Contact name"); event.setContactMail("contact@mail"); event.setContactPhone("1234567890"); event.setAdditionalInfo("Additional info"); event.setGeoLocation(geoLocation()); return event; } private void assertDTOsEqualsToEntities( final List<DogEventUnleashDTO> dto, final List<DogEventUnleash> entity) { assertThat(entity.size(), equalTo(dto.size())); for (int i = 0; i < dto.size(); i++) { if (dto.get(i).getId() == null) { assertThat(entity.get(i).getId(), is(not(nullValue()))); } else { assertThat(dto.get(i).getId(), equalTo(entity.get(i).getId())); } final DogEventUnleashDTO aDTO = dto.get(i); final DogEventUnleash anEvent = entity.get(i); assertThat(aDTO.getEventType(), equalTo(anEvent.getEventType())); assertThat(aDTO.getBeginDate(), equalTo(anEvent.getBeginDate())); assertThat(aDTO.getEndDate(), equalTo(anEvent.getEndDate())); assertThat(aDTO.getDogsAmount(), equalTo(Optional.ofNullable(anEvent.getDogsAmount()).orElse(0).intValue())); assertThat(aDTO.getNaturaArea(), equalTo(anEvent.getNaturaArea())); assertThat(aDTO.getEventDescription(), equalTo(anEvent.getEventDescription())); assertThat(aDTO.getLocationDescription(), equalTo(anEvent.getLocationDescription())); assertThat(aDTO.getLocationDescription(), equalTo(anEvent.getLocationDescription())); assertThat(aDTO.getContactName(), equalTo(anEvent.getContactName())); assertThat(aDTO.getContactMail(), equalTo(anEvent.getContactMail())); assertThat(aDTO.getContactPhone(), equalTo(anEvent.getContactPhone())); assertThat(aDTO.getAdditionalInfo(), equalTo(anEvent.getAdditionalInfo())); assertThat(aDTO.getGeoLocation(), equalTo(anEvent.getGeoLocation())); } } private void assertEntitiesEquals(final List<DogEventUnleash> expected, final List<DogEventUnleash> actual) { assertThat(actual.size(), equalTo(expected.size())); for (int i = 0; i < expected.size(); i++) { assertThat(expected.get(i).isEqualTo(actual.get(i)), is(true)); } } }
3e0fa38e639323b534b67fdc4fc266a6acd89ea8
363
java
Java
JDND-master/demos/c1/spring-boot-validation/src/test/java/com/example/springbootvalidation/SpringBootValidationApplicationTests.java
wuhao4u/udacity-java-developer
3123019294ecaa2ccafa7b70e65d6bba7b34e4d9
[ "MIT" ]
null
null
null
JDND-master/demos/c1/spring-boot-validation/src/test/java/com/example/springbootvalidation/SpringBootValidationApplicationTests.java
wuhao4u/udacity-java-developer
3123019294ecaa2ccafa7b70e65d6bba7b34e4d9
[ "MIT" ]
null
null
null
JDND-master/demos/c1/spring-boot-validation/src/test/java/com/example/springbootvalidation/SpringBootValidationApplicationTests.java
wuhao4u/udacity-java-developer
3123019294ecaa2ccafa7b70e65d6bba7b34e4d9
[ "MIT" ]
null
null
null
21.352941
60
0.823691
6,643
package com.example.springbootvalidation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootValidationApplicationTests { @Test public void contextLoads() { } }
3e0fa39e97ecb071d0d30b5bfb4f51135b7df537
257
java
Java
src/test/java/com/algorithms/sorting/HeapSortTest.java
myronrotter/recap-java-algorithms
8824533fba03497f140eaed5de2226ce8c6d3db9
[ "MIT" ]
null
null
null
src/test/java/com/algorithms/sorting/HeapSortTest.java
myronrotter/recap-java-algorithms
8824533fba03497f140eaed5de2226ce8c6d3db9
[ "MIT" ]
3
2020-01-15T09:31:50.000Z
2020-01-22T13:13:47.000Z
src/test/java/com/algorithms/sorting/HeapSortTest.java
myronrotter/recap-java-algorithms
8824533fba03497f140eaed5de2226ce8c6d3db9
[ "MIT" ]
null
null
null
19.769231
52
0.77821
6,644
package com.algorithms.sorting; import com.algorithms.interfaces.Sorting; import com.algorithms.interfaces.SortingTest; class HeapSortTest implements SortingTest<Sorting> { @Override public Sorting createInstance() { return new HeapSort(); } }
3e0fa4c962fc47b926b9648d8be500207153f916
279
java
Java
src/main/java/com/solarexsoft/leetcode/editor/cn/Node.java
flyfire/LeetCodeSolutions
91da8a6176a6fe07d6174674cb8427956d432b09
[ "MIT" ]
null
null
null
src/main/java/com/solarexsoft/leetcode/editor/cn/Node.java
flyfire/LeetCodeSolutions
91da8a6176a6fe07d6174674cb8427956d432b09
[ "MIT" ]
null
null
null
src/main/java/com/solarexsoft/leetcode/editor/cn/Node.java
flyfire/LeetCodeSolutions
91da8a6176a6fe07d6174674cb8427956d432b09
[ "MIT" ]
null
null
null
14.684211
43
0.566308
6,645
package com.solarexsoft.leetcode.editor.cn; /** * Created by houruhou on 2020/1/10. * Desc: */ public class Node { int val; Node next; Node random; public Node(int val) { this.val = val; this.next = null; this.random = null; } }
3e0fa5a8547c8ea0a066781b823992c28c4693af
287
java
Java
api/src/main/java/br/com/labestudo/api/model/dto/HashDto.java
bjbienemann/lab-estudo
f1095e29edb7fec6f81694f8c5427e573e2e27a7
[ "MIT" ]
null
null
null
api/src/main/java/br/com/labestudo/api/model/dto/HashDto.java
bjbienemann/lab-estudo
f1095e29edb7fec6f81694f8c5427e573e2e27a7
[ "MIT" ]
8
2021-05-15T17:14:09.000Z
2021-12-06T22:27:06.000Z
api/src/main/java/br/com/labestudo/api/model/dto/HashDto.java
bjbienemann/lab-estudo
f1095e29edb7fec6f81694f8c5427e573e2e27a7
[ "MIT" ]
2
2021-05-01T11:53:16.000Z
2021-05-10T01:04:38.000Z
15.944444
45
0.797909
6,646
package br.com.labestudo.api.model.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotEmpty; @Data @AllArgsConstructor @NoArgsConstructor public class HashDto { @NotEmpty private String hash; }
3e0fa61680b6102ae036f344633c6458942398ec
3,187
java
Java
java/shrine/app/src/main/java/com/google/codelabs/mdc/java/shrine/ProductPageFragment.java
voidMuyTofu/Fire-App
5022e84d9702c2a6663b0d71327b59cd8065b31c
[ "Apache-2.0" ]
1
2019-04-25T09:56:52.000Z
2019-04-25T09:56:52.000Z
java/shrine/app/src/main/java/com/google/codelabs/mdc/java/shrine/ProductPageFragment.java
voidMuyTofu/Fire-App
5022e84d9702c2a6663b0d71327b59cd8065b31c
[ "Apache-2.0" ]
null
null
null
java/shrine/app/src/main/java/com/google/codelabs/mdc/java/shrine/ProductPageFragment.java
voidMuyTofu/Fire-App
5022e84d9702c2a6663b0d71327b59cd8065b31c
[ "Apache-2.0" ]
null
null
null
37.940476
95
0.7016
6,647
package com.google.codelabs.mdc.java.shrine; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.button.MaterialButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.toolbox.NetworkImageView; import com.bumptech.glide.Glide; import com.google.codelabs.mdc.java.shrine.network.ImageRequester; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class ProductPageFragment extends Fragment { private TextView tvTitle; private TextView tvDescription; private TextView tvSize; private TextView tvPrice; private MaterialButton btMessage; private ImageView ivImage; private String [] images; public String iduser; private ImageRequester imageRequester; private FirebaseUser firebaseUser; @Override public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fir_product_page_fragment, container, false); initComponent(view); firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); displayInfo(); btMessage.setOnClickListener(v -> { Bundle bundle1 = new Bundle(); bundle1.putString("title", getArguments().get("title").toString()); bundle1.putString("url", getArguments().get("url").toString()); bundle1.putString("userId", getArguments().get("userId").toString()); ((NavigationHost)getContext()).navigateTo(new ChatFragment(), true, bundle1); }); return view; } private void displayInfo(){ Bundle bundle; bundle = this.getArguments(); if(bundle != null){ tvTitle.setText((CharSequence) bundle.get("title")); //tvSize.setText((CharSequence) bundle.get("size")); tvDescription.setText((CharSequence) bundle.get("description")); tvPrice.setText((CharSequence) bundle.get("price")); Glide.with(getContext()).load(bundle.get("url")).into(ivImage); if(bundle.get("userId").equals(firebaseUser.getUid())) btMessage.setVisibility(View.GONE); images = (String[]) bundle.get("imagesurl"); } } private void initComponent(View view){ tvTitle = view.findViewById(R.id.fir_product_title); tvDescription = view.findViewById(R.id.fir_product_descripction); tvPrice = view.findViewById(R.id.fir_product_price); tvSize = view.findViewById(R.id.fir_product_size); ivImage = view.findViewById(R.id.fir_product_image); btMessage = view.findViewById(R.id.fir_bt_message); } }
3e0fa71b66f7080dd33d2c1e4d76dd696426325f
1,042
java
Java
app/src/test/java/com/nexus/nsnik/randomno/RandomNumberGenerationUnitTest.java
nsnikhil/RandomNo
f3f8e2385839a1563196c2295d556e00f6c1c785
[ "Apache-2.0" ]
null
null
null
app/src/test/java/com/nexus/nsnik/randomno/RandomNumberGenerationUnitTest.java
nsnikhil/RandomNo
f3f8e2385839a1563196c2295d556e00f6c1c785
[ "Apache-2.0" ]
1
2018-07-29T08:35:58.000Z
2018-07-29T08:35:58.000Z
app/src/test/java/com/nexus/nsnik/randomno/RandomNumberGenerationUnitTest.java
nsnikhil/RandomNo
f3f8e2385839a1563196c2295d556e00f6c1c785
[ "Apache-2.0" ]
null
null
null
28.944444
78
0.707294
6,648
/* * Copyright 2017 nsnikhil * * 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.nexus.nsnik.randomno; import org.junit.Test; import java.util.concurrent.ThreadLocalRandom; public class RandomNumberGenerationUnitTest { @Test public void generateOneOrZero() { ThreadLocalRandom.current().nextInt(0, 1 + 1); } @Test public void generateRandomNumberInRange(int minimum, int maximum) { ThreadLocalRandom.current().nextInt(minimum, maximum + 1); } }
3e0fa78de375ae98cc2af89193ef8496488fc248
1,112
java
Java
app-dto/src/main/java/com/wondernect/stars/app/dto/auth/SaveAppAuthRequestDTO.java
wondernect/wondernect-stars
a3b52d52fab9430d170b3818ee980bde18bd273f
[ "MIT" ]
null
null
null
app-dto/src/main/java/com/wondernect/stars/app/dto/auth/SaveAppAuthRequestDTO.java
wondernect/wondernect-stars
a3b52d52fab9430d170b3818ee980bde18bd273f
[ "MIT" ]
3
2020-11-06T06:54:53.000Z
2021-01-05T11:51:09.000Z
app-dto/src/main/java/com/wondernect/stars/app/dto/auth/SaveAppAuthRequestDTO.java
wondernect/wondernect-stars
a3b52d52fab9430d170b3818ee980bde18bd273f
[ "MIT" ]
1
2020-08-10T08:54:08.000Z
2020-08-10T08:54:08.000Z
25.860465
53
0.740108
6,649
package com.wondernect.stars.app.dto.auth; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 应用访问认证请求DTO * * @author chenxun 2020-12-29 16:28:22 **/ @Data @NoArgsConstructor @AllArgsConstructor @ApiModel(value = "应用访问认证请求对象") public class SaveAppAuthRequestDTO { @NotBlank(message = "应用id不能为空") @JsonProperty("app_id") @ApiModelProperty(notes = "应用id") private String appId; @NotBlank(message = "应用访问密钥不能为空") @JsonProperty("secret") @ApiModelProperty(notes = "应用访问密钥") private String secret; @NotBlank(message = "应用访问密钥绑定用户id不能为空") @JsonProperty("user_id") @ApiModelProperty(notes = "应用访问密钥绑定用户id") private String userId; @NotNull(message = "应用访问类型不能为空") @JsonProperty("access_type") @ApiModelProperty(notes = "应用访问类型(1-只读;2-读写;)") private Integer accessType; }
3e0fa7c0bd98410b1733283c775e978e0b9dadca
32,119
java
Java
evaluation/themis_openmrs-core_unsafe/src/test/java/org/openmrs/ObsTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
32
2019-02-21T21:10:05.000Z
2022-02-03T20:04:11.000Z
evaluation/themis_openmrs-core_unsafe/src/test/java/org/openmrs/ObsTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
null
null
null
evaluation/themis_openmrs-core_unsafe/src/test/java/org/openmrs/ObsTest.java
RuiDTLima/diffuzz
8a6e9603fa3bdb155f15211b8fc90e57e958c000
[ "Apache-2.0" ]
6
2019-02-17T07:02:43.000Z
2021-08-24T09:02:31.000Z
30.502374
125
0.728883
6,650
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Field; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.commons.beanutils.BeanUtils; import org.junit.Assert; import org.junit.Test; import org.openmrs.api.APIException; import org.openmrs.obs.ComplexData; import org.openmrs.util.Reflect; /** * This class tests all methods that are not getter or setters in the Obs java object TODO: finish * this test class for Obs * * @see Obs */ public class ObsTest { private static final String VERO = "Vero"; private static final String FORM_NAMESPACE_PATH_SEPARATOR = "^"; //ignore these fields, groupMembers and formNamespaceAndPath field are taken care of by other tests private static final List<String> IGNORED_FIELDS = Arrays.asList("dirty", "log", "serialVersionUID", "DATE_TIME_PATTERN", "TIME_PATTERN", "DATE_PATTERN", "FORM_NAMESPACE_PATH_SEPARATOR", "FORM_NAMESPACE_PATH_MAX_LENGTH", "obsId", "groupMembers", "uuid", "changedBy", "dateChanged", "voided", "voidedBy", "voidReason", "dateVoided", "formNamespaceAndPath", "$jacocoData"); private void resetObs(Obs obs) throws Exception { Field field = Obs.class.getDeclaredField("dirty"); field.setAccessible(true); try { field.set(obs, false); } finally { field.setAccessible(false); } assertFalse(obs.isDirty()); } private Obs createObs(Integer id) throws Exception { Obs obs = new Obs(id); List<Field> fields = Reflect.getAllFields(Obs.class); for (Field field : fields) { if (IGNORED_FIELDS.contains(field.getName())) { continue; } setFieldValue(obs, field, false); } assertFalse(obs.isDirty()); return obs; } private void setFieldValue(Obs obs, Field field, boolean setAlternateValue) throws Exception { final boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } try { Object oldFieldValue = field.get(obs); Object newFieldValue = generateValue(field, setAlternateValue); //sanity check if (setAlternateValue) { assertNotEquals("The old and new values should be different for field: Obs." + field.getName(), oldFieldValue, newFieldValue); } field.set(obs, newFieldValue); } finally { field.setAccessible(accessible); } } private Object generateValue(Field field, boolean setAlternateValue) throws Exception { Object fieldValue; if (field.getType().equals(Boolean.class)) { fieldValue = setAlternateValue; } else if (field.getType().equals(Integer.class)) { fieldValue = setAlternateValue ? 10 : 17; } else if (field.getType().equals(Double.class)) { fieldValue = setAlternateValue ? 5.0 : 7.0; } else if (field.getType().equals(Date.class)) { fieldValue = new Date(); if (setAlternateValue) { Calendar c = Calendar.getInstance(); c.add(Calendar.MINUTE, 2); fieldValue = c.getTime(); } } else if (field.getType().equals(String.class)) { fieldValue = setAlternateValue ? "old" : "new"; } else if (field.getType().equals(Person.class)) { //setPerson updates the personId, so we want the personIds to match for the tests to be valid fieldValue = new Person(setAlternateValue ? 10 : 17); } else if (field.getType().equals(ComplexData.class)) { fieldValue = new ComplexData(setAlternateValue ? "some complex data" : "Some other value", new Object()); } else if (field.getType().equals(Obs.Interpretation.class)) { fieldValue = setAlternateValue ? Obs.Interpretation.ABNORMAL : Obs.Interpretation.CRITICALLY_ABNORMAL; } else if (field.getType().equals(Obs.Status.class)) { fieldValue = setAlternateValue ? Obs.Status.AMENDED : Obs.Status.PRELIMINARY; } else { fieldValue = field.getType().newInstance(); } assertNotNull("Failed to generate a value for field: Obs." + field.getName()); return fieldValue; } /** * Tests the addToGroup method in ObsGroup * * @throws Exception */ @Test public void shouldAddandRemoveObsToGroup() throws Exception { Obs obs = new Obs(1); Obs obsGroup = new Obs(755); // These methods should not fail even with null attributes on the obs assertFalse(obsGroup.isObsGrouping()); assertFalse(obsGroup.hasGroupMembers(false)); assertFalse(obsGroup.hasGroupMembers(true)); // Check both flags for false // adding an obs when the obs group has no other obs // should not throw an error obsGroup.addGroupMember(obs); assertEquals(1, obsGroup.getGroupMembers().size()); // check duplicate add. should only be one obsGroup.addGroupMember(obs); assertTrue(obsGroup.hasGroupMembers(false)); assertEquals("Duplicate add should not increase the grouped obs size", 1, obsGroup.getGroupMembers().size()); Obs obs2 = new Obs(2); obsGroup.removeGroupMember(obs2); assertTrue(obsGroup.hasGroupMembers(false)); assertEquals("Removing a non existent obs should not decrease the number of grouped obs", 1, obsGroup .getGroupMembers().size()); // testing removing an obs from a group that has a null obs list new Obs().removeGroupMember(obs2); obsGroup.removeGroupMember(obs); assertEquals(0, obsGroup.getGroupMembers().size()); // try to add an obs group to itself try { obsGroup.addGroupMember(obsGroup); fail("An APIException about adding an obsGroup should have been thrown"); } catch (APIException e) { // this exception is expected } } /** * tests the getRelatedObservations method: */ @Test public void shouldGetRelatedObservations() throws Exception { // create a child Obs Obs o = new Obs(); o.setDateCreated(new Date()); o.setLocation(new Location(1)); o.setObsDatetime(new Date()); o.setPerson(new Patient(2)); o.setValueText("childObs"); // create its sibling Obs oSibling = new Obs(); oSibling.setDateCreated(new Date()); oSibling.setLocation(new Location(1)); oSibling.setObsDatetime(new Date()); oSibling.setValueText("childObs2"); oSibling.setPerson(new Patient(2)); // create a parent Obs Obs oParent = new Obs(); oParent.setDateCreated(new Date()); oParent.setLocation(new Location(1)); oParent.setObsDatetime(new Date()); oSibling.setValueText("parentObs"); oParent.setPerson(new Patient(2)); // create a grandparent obs Obs oGrandparent = new Obs(); oGrandparent.setDateCreated(new Date()); oGrandparent.setLocation(new Location(1)); oGrandparent.setObsDatetime(new Date()); oGrandparent.setPerson(new Patient(2)); oSibling.setValueText("grandParentObs"); oParent.addGroupMember(o); oParent.addGroupMember(oSibling); oGrandparent.addGroupMember(oParent); // create a leaf observation at the grandparent level Obs o2 = new Obs(); o2.setDateCreated(new Date()); o2.setLocation(new Location(1)); o2.setObsDatetime(new Date()); o2.setPerson(new Patient(2)); o2.setValueText("grandparentLeafObs"); oGrandparent.addGroupMember(o2); /** * test to make sure that if the original child obs calls getRelatedObservations, it returns * itself and its siblings: original obs is one of two groupMembers, so relatedObservations * should return a size of set 2 then, make sure that if oParent calls * getRelatedObservations, it returns its own children as well as the leaf obs attached to * the grandparentObs oParent has two members, and one leaf ancestor -- so a set of size 3 * should be returned. */ assertEquals(o.getRelatedObservations().size(), 2); assertEquals(oParent.getRelatedObservations().size(), 3); // create a great-grandparent obs Obs oGGP = new Obs(); oGGP.setDateCreated(new Date()); oGGP.setLocation(new Location(1)); oGGP.setObsDatetime(new Date()); oGGP.setPerson(new Patient(2)); oGGP.setValueText("grandParentObs"); oGGP.addGroupMember(oGrandparent); // create a leaf great-grandparent obs Obs oGGPleaf = new Obs(); oGGPleaf.setDateCreated(new Date()); oGGPleaf.setLocation(new Location(1)); oGGPleaf.setObsDatetime(new Date()); oGGPleaf.setPerson(new Patient(2)); oGGPleaf.setValueText("grandParentObs"); oGGP.addGroupMember(oGGPleaf); /** * now run the previous assertions again. this time there are two ancestor leaf obs, so the * first assertion should still return a set of size 2, but the second assertion sould * return a set of size 4. */ assertEquals(o.getRelatedObservations().size(), 2); assertEquals(oParent.getRelatedObservations().size(), 4); // remove the grandparent leaf observation: oGrandparent.removeGroupMember(o2); // now the there is only one ancestor leaf obs: assertEquals(o.getRelatedObservations().size(), 2); assertEquals(oParent.getRelatedObservations().size(), 3); /** * finally, test a non-obsGroup and non-member Obs to the function Obs o2 is now not * connected to our heirarchy: an empty set should be returned: */ assertNotNull(o2.getRelatedObservations()); assertEquals(o2.getRelatedObservations().size(), 0); } /** * @see Obs#isComplex() */ @Test public void isComplex_shouldReturnTrueIfTheConceptIsComplex() throws Exception { ConceptDatatype cd = new ConceptDatatype(); cd.setName("Complex"); cd.setHl7Abbreviation("ED"); ConceptComplex complexConcept = new ConceptComplex(); complexConcept.setDatatype(cd); Obs obs = new Obs(); obs.setConcept(complexConcept); Assert.assertTrue(obs.isComplex()); } /** * @see Obs#setValueAsString(String) */ @Test(expected = RuntimeException.class) public void setValueAsString_shouldFailIfTheValueOfTheStringIsEmpty() throws Exception { Obs obs = new Obs(); obs.setValueAsString(""); } /** * @see Obs#setValueAsString(String) */ @Test(expected = RuntimeException.class) public void setValueAsString_shouldFailIfTheValueOfTheStringIsNull() throws Exception { Obs obs = new Obs(); obs.setValueAsString(null); } /** * @see Obs#getValueAsBoolean() */ @Test public void getValueAsBoolean_shouldReturnFalseForValue_numericConceptsIfValueIs0() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(0.0); Assert.assertEquals(false, obs.getValueAsBoolean()); } /** * @see Obs#getValueAsBoolean() */ @Test public void getValueAsBoolean_shouldReturnNullForValue_numericConceptsIfValueIsNeither1Nor0() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(24.8); Assert.assertNull(obs.getValueAsBoolean()); } @Test public void getValueAsString_shouldReturnNonPreciseValuesForNumericConcepts() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(25.125); ConceptNumeric cn = new ConceptNumeric(); ConceptDatatype cdt = new ConceptDatatype(); cdt.setHl7Abbreviation("NM"); cn.setDatatype(cdt); cn.setAllowDecimal(false); obs.setConcept(cn); String str = "25"; Assert.assertEquals(str, obs.getValueAsString(Locale.US)); } @Test public void getValueAsString_shouldNotReturnLongDecimalNumbersAsScientificNotation() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(123456789.0); String str = "123456789.0"; Assert.assertEquals(str, obs.getValueAsString(Locale.US)); } @Test public void getValueAsString_shouldReturnDateInCorrectFormat() throws Exception { Obs obs = new Obs(); obs.setValueDatetime(new Date()); Concept cn = new Concept(); ConceptDatatype cdt = new ConceptDatatype(); cdt.setHl7Abbreviation("DT"); cn.setDatatype(cdt); obs.setConcept(cn); Date utilDate = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String dateString = dateFormat.format(utilDate); Assert.assertEquals(dateString, obs.getValueAsString(Locale.US)); } /** * @see Obs#getValueAsBoolean() */ @Test public void getValueAsBoolean_shouldReturnTrueForValue_numericConceptsIfValueIs1() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(1.0); Assert.assertEquals(true, obs.getValueAsBoolean()); } /** * @see Obs#getGroupMembers(boolean) */ @Test public void getGroupMembers_shouldGetAllGroupMembersIfPassedTrueAndNonvoidedIfPassedFalse() throws Exception { Obs parent = new Obs(1); Set<Obs> members = new HashSet<>(); members.add(new Obs(101)); members.add(new Obs(103)); Obs voided = new Obs(99); voided.setVoided(true); members.add(voided); parent.setGroupMembers(members); members = parent.getGroupMembers(true); assertEquals("set of all members should have length of 3", 3, members.size()); members = parent.getGroupMembers(false); assertEquals("set of non-voided should have length of 2", 2, members.size()); members = parent.getGroupMembers(); // should be same as false assertEquals("default should return non-voided with length of 2", 2, members.size()); } /** * @see Obs#hasGroupMembers(boolean) */ @Test public void hasGroupMembers_shouldReturnTrueIfThisObsHasGroupMembersBasedOnParameter() throws Exception { Obs parent = new Obs(5); Obs child = new Obs(33); child.setVoided(true); parent.addGroupMember(child); // Only contains 1 voided child assertTrue("When checking for all members, should return true", parent.hasGroupMembers(true)); assertFalse("When checking for non-voided, should return false", parent.hasGroupMembers(false)); assertFalse("Default should check for non-voided", parent.hasGroupMembers()); } /** * @see Obs#isObsGrouping() */ @Test public void isObsGrouping_shouldIncludeVoidedObs() throws Exception { Obs parent = new Obs(5); Obs child = new Obs(33); child.setVoided(true); parent.addGroupMember(child); assertTrue("When checking for Obs grouping, should include voided Obs", parent.isObsGrouping()); } /** * @see Obs#getValueAsString(Locale) */ @Test public void getValueAsString_shouldUseCommasOrDecimalPlacesDependingOnLocale() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(123456789.3); String str = "123456789,3"; Assert.assertEquals(str, obs.getValueAsString(Locale.GERMAN)); } /** * @see Obs#getValueAsString(Locale) */ @Test public void getValueAsString_shouldNotUseThousandSeparator() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(123456789.0); String str = "123456789.0"; Assert.assertEquals(str, obs.getValueAsString(Locale.ENGLISH)); } /** * @see Obs#getValueAsString(Locale) */ @Test public void getValueAsString_shouldReturnRegularNumberForSizeOfZeroToOrGreaterThanTenDigits() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(1234567890.0); String str = "1234567890.0"; Assert.assertEquals(str, obs.getValueAsString(Locale.ENGLISH)); } /** * @see Obs#getValueAsString(Locale) */ @Test public void getValueAsString_shouldReturnRegularNumberIfDecimalPlacesAreAsHighAsSix() throws Exception { Obs obs = new Obs(); obs.setValueNumeric(123456789.012345); String str = "123456789.012345"; Assert.assertEquals(str, obs.getValueAsString(Locale.ENGLISH)); } @Test public void getValueAsString_shouldReturnLocalizedCodedConcept() throws Exception { ConceptDatatype cdt = new ConceptDatatype(); cdt.setHl7Abbreviation("CWE"); Concept cn = new Concept(); cn.setDatatype(cdt); cn.addName(new ConceptName(VERO, Locale.ITALIAN)); Obs obs = new Obs(); obs.setValueCoded(cn); obs.setConcept(cn); obs.setValueCodedName(new ConceptName("True", Locale.US)); Assert.assertEquals(VERO, obs.getValueAsString(Locale.ITALIAN)); } /** * @see Obs#setFormField(String,String) */ @Test public void setFormField_shouldSetTheUnderlyingFormNamespaceAndPathInTheCorrectPattern() throws Exception { final String ns = "my ns"; final String path = "my path"; Obs obs = new Obs(); obs.setFormField(ns, path); java.lang.reflect.Field formNamespaceAndPathProperty = Obs.class.getDeclaredField("formNamespaceAndPath"); formNamespaceAndPathProperty.setAccessible(true); Assert.assertEquals(ns + FORM_NAMESPACE_PATH_SEPARATOR + path, formNamespaceAndPathProperty.get(obs)); } /** * @see Obs#getFormFieldNamespace() */ @Test public void getFormFieldNamespace_shouldReturnNullIfTheNamespaceIsNotSpecified() throws Exception { Obs obs = new Obs(); obs.setFormField("", "my path"); Assert.assertNull(obs.getFormFieldNamespace()); } /** * @see Obs#getFormFieldNamespace() */ @Test public void getFormFieldNamespace_shouldReturnTheCorrectNamespaceForAFormFieldWithAPath() throws Exception { final String ns = "my ns"; final String path = "my path"; Obs obs = new Obs(); obs.setFormField(ns, path); Assert.assertEquals(ns, obs.getFormFieldNamespace()); } /** * @see Obs#getFormFieldNamespace() */ @Test public void getFormFieldNamespace_shouldReturnTheNamespaceForAFormFieldThatHasNoPath() throws Exception { final String ns = "my ns"; Obs obs = new Obs(); obs.setFormField(ns, null); Assert.assertEquals(ns, obs.getFormFieldNamespace()); } /** * @see Obs#getFormFieldPath() */ @Test public void getFormFieldPath_shouldReturnNullIfThePathIsNotSpecified() throws Exception { Obs obs = new Obs(); obs.setFormField("my ns", ""); Assert.assertNull(obs.getFormFieldPath()); } /** * @see Obs#getFormFieldPath() */ @Test public void getFormFieldPath_shouldReturnTheCorrectPathForAFormFieldWithANamespace() throws Exception { final String ns = "my ns"; final String path = "my path"; Obs obs = new Obs(); obs.setFormField(ns, path); Assert.assertEquals(path, obs.getFormFieldPath()); } /** * @see Obs#getFormFieldPath() */ @Test public void getFormFieldPath_shouldReturnThePathForAFormFieldThatHasNoNamespace() throws Exception { final String path = "my path"; Obs obs = new Obs(); obs.setFormField("", path); Assert.assertEquals(path, obs.getFormFieldPath()); } /** * @see Obs#setFormField(String,String) */ @Test(expected = APIException.class) public void setFormField_shouldRejectANamepaceAndPathCombinationLongerThanTheMaxLength() throws Exception { StringBuilder nsBuffer = new StringBuilder(125); for (int i = 0; i < 125; i++) { nsBuffer.append("n"); } for (int i = 0; i < 130; i++) { nsBuffer.append("p"); } final String ns = nsBuffer.toString(); final String path = ""; Obs obs = new Obs(); obs.setFormField(ns, path); } /** * @see Obs#setFormField(String,String) */ @Test(expected = APIException.class) public void setFormField_shouldRejectANamepaceContainingTheSeparator() throws Exception { final String ns = "my ns" + FORM_NAMESPACE_PATH_SEPARATOR; Obs obs = new Obs(); obs.setFormField(ns, ""); } /** * @see Obs#setFormField(String,String) */ @Test(expected = APIException.class) public void setFormField_shouldRejectAPathContainingTheSeparator() throws Exception { final String path = FORM_NAMESPACE_PATH_SEPARATOR + "my path"; Obs obs = new Obs(); obs.setFormField("", path); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnFalseWhenNoChangeHasBeenMade() throws Exception { assertFalse(new Obs().isDirty()); //Should also work if setters are called with same values as the original Obs obs = createObs(2); obs.setGroupMembers(new LinkedHashSet<>()); obs.getConcept().setDatatype(new ConceptDatatype()); assertFalse(obs.isDirty()); BeanUtils.copyProperties(obs, BeanUtils.cloneBean(obs)); assertFalse(obs.isDirty()); obs = createObs(null); obs.setGroupMembers(new LinkedHashSet<>()); obs.getConcept().setDatatype(new ConceptDatatype()); assertFalse(obs.isDirty()); BeanUtils.copyProperties(obs, BeanUtils.cloneBean(obs)); assertFalse(obs.isDirty()); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnTrueWhenAnyImmutableFieldHasBeenChangedForEditedObs() throws Exception { Obs obs = createObs(2); assertFalse(obs.isDirty()); updateImmutableFieldsAndAssert(obs, true); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnFalseWhenAnyImmutableFieldHasBeenChangedForNewObs() throws Exception { Obs obs = createObs(null); assertFalse(obs.isDirty()); updateImmutableFieldsAndAssert(obs, false); } private void updateImmutableFieldsAndAssert(Obs obs, boolean assertion) throws Exception { //Set all fields to some random values via reflection List<Field> fields = Reflect.getAllFields(Obs.class); final Integer originalPersonId = obs.getPersonId(); //call each setter and check that dirty has been set to true for each for (Field field : fields) { String fieldName = field.getName(); if (IGNORED_FIELDS.contains(fieldName)) { continue; } if ("personId".equals(fieldName)) { //call setPersonId because it is protected so BeanUtils.setProperty won't work obs.setPersonId((Integer) generateValue(field, true)); } else { BeanUtils.setProperty(obs, fieldName, generateValue(field, true)); } assertEquals("Obs was not marked as dirty after changing: " + fieldName, obs.isDirty(), assertion); if ("person".equals(fieldName)) { //Because setPerson updates the personId we need to reset personId to its original value //that matches that of person otherwise the test will fail for the personId field obs.setPersonId(originalPersonId); } //reset for next field resetObs(obs); } } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnFalseWhenOnlyMutableFieldsAreChanged() throws Exception { Obs obs = new Obs(); obs.setVoided(true); obs.setVoidedBy(new User(1000)); obs.setVoidReason("some other reason"); obs.setDateVoided(new Date()); assertFalse(obs.isDirty()); Obs obsEdited = new Obs(5); obsEdited.setVoided(true); obsEdited.setVoidedBy(new User(1000)); obsEdited.setVoidReason("some other reason"); obsEdited.setDateVoided(new Date()); assertFalse(obsEdited.isDirty()); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnTrueWhenAnImmutableFieldIsChangedFromANonNullToANullValueForEditedObs() throws Exception { Obs obs = createObs(2); assertNotNull(obs.getComment()); obs.setComment(null); assertTrue(obs.isDirty()); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnFalsWhenAnImmutableFieldIsChangedFromANonNullToANullValueForNewObs() throws Exception { Obs obs = createObs(null); assertNotNull(obs.getComment()); obs.setComment(null); assertFalse(obs.isDirty()); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnTrueWhenAnImmutableFieldIsChangedFromANullToANonNullValueInExistingObs() throws Exception { Obs obs = new Obs(5); assertNull(obs.getComment()); obs.setComment("some non null value"); assertTrue(obs.isDirty()); } /** * @see Obs#isDirty() */ @Test public void isDirty_shouldReturnFalseWhenAnImmutableFieldIsChangedFromANullToANonNullValueInNewObs() throws Exception { Obs obs = new Obs(); assertNull(obs.getComment()); obs.setComment("some non null value"); assertFalse(obs.isDirty()); } /** * @see Obs#setFormField(String,String) */ @Test public void setFormField_shouldNotMarkTheObsAsDirtyWhenTheValueHasNotBeenChanged() throws Exception { Obs obs = createObs(3); obs.setFormField(obs.getFormFieldNamespace(), obs.getFormFieldPath()); assertFalse(obs.isDirty()); } /** * @see Obs#setFormField(String,String) */ @Test public void setFormField_shouldMarkTheObsAsDirtyWhenTheValueHasBeenChanged() throws Exception { Obs obs = createObs(5); final String newNameSpace = "someNameSpace"; final String newPath = "somePath"; assertNotEquals(newPath, obs.getFormFieldNamespace()); assertNotEquals(newNameSpace, obs.getFormFieldPath()); obs.setFormField(newNameSpace, newPath); assertTrue(obs.isDirty()); } /** * @see Obs#setFormField(String,String) */ @Test public void setFormField_shouldMarkTheObsAsDirtyWhenTheValueIsChangedFromANonNullToANullValue() throws Exception { Obs obs = new Obs(2); obs.setFormField("someNameSpace", "somePath"); resetObs(obs); assertFalse(obs.isDirty()); assertNotNull(obs.getFormFieldNamespace()); assertNotNull(obs.getFormFieldPath()); obs.setFormField(null, null); assertTrue(obs.isDirty()); } /** * @see Obs#setFormField(String,String) */ @Test public void setFormField_shouldMarkTheObsAsDirtyWhenTheValueIsChangedFromANullToANonNullValue() throws Exception { Obs obs = new Obs(5); assertNull(obs.getFormFieldNamespace()); assertNull(obs.getFormFieldPath()); obs.setFormField("someNameSpace", "somePath"); assertTrue(obs.isDirty()); } /** * @see Obs#addGroupMember(Obs) */ @Test public void addGroupMember_shouldReturnFalseWhenADuplicateObsIsAddedAsAMember() throws Exception { Obs obs = new Obs(2); Obs member = new Obs(); obs.addGroupMember(member); assertFalse(obs.isDirty()); resetObs(obs); obs.addGroupMember(member); assertFalse(obs.isDirty()); } /** * @see Obs#addGroupMember(Obs) */ @Test public void addGroupMember_shouldReturnFalseWhenADuplicateObsIsAddedAsAMemberToNewObs() throws Exception { Obs obs = new Obs(); Obs member = new Obs(); obs.addGroupMember(member); assertFalse(obs.isDirty()); resetObs(obs); obs.addGroupMember(member); assertFalse(obs.isDirty()); } /** * @see Obs#addGroupMember(Obs) */ @Test public void addGroupMember_shouldReturnFalseWhenANewObsIsAddedAsAMember() throws Exception { Obs obs = new Obs(2); Obs member1 = new Obs(); obs.addGroupMember(member1); assertFalse(obs.isDirty()); resetObs(obs); Obs member2 = new Obs(); obs.addGroupMember(member2); assertFalse(obs.isDirty()); } /** * @see Obs#removeGroupMember(Obs) */ @Test public void removeGroupMember_shouldReturnFalseWhenANonExistentObsIsRemoved() throws Exception { Obs obs = new Obs(); obs.removeGroupMember(new Obs()); assertFalse(obs.isDirty()); } /** * @see Obs#removeGroupMember(Obs) */ @Test public void removeGroupMember_shouldReturnDirtyFalseWhenAnObsIsRemoved() throws Exception { Obs obs = new Obs(2); Obs member = new Obs(); obs.addGroupMember(member); assertFalse(obs.isDirty()); resetObs(obs); obs.removeGroupMember(member); assertFalse(obs.isDirty()); } /** * @see Obs#removeGroupMember(Obs) */ @Test public void removeGroupMember_shouldReturnFalseForDirtyFlagWhenAnObsIsRemovedFromGroup() throws Exception { Obs obs = new Obs(); Obs member = new Obs(); obs.addGroupMember(member); assertFalse(obs.isDirty()); resetObs(obs); obs.removeGroupMember(member); assertFalse(obs.isDirty()); } /** * @see Obs#setGroupMembers(Set) */ @Test public void setGroupMembers_shouldNotMarkTheExistingObsAsDirtyWhenTheSetIsChangedFromNullToANonEmptyOne() throws Exception { Obs obs = new Obs(5); assertNull(Obs.class.getDeclaredField("groupMembers").get(obs)); Set<Obs> members = new HashSet<>(); members.add(new Obs()); obs.setGroupMembers(members); assertFalse(obs.isDirty()); } /** * @see Obs#setGroupMembers(Set) */ @Test public void setGroupMembers_shouldNotMarkNewObsAsDirtyWhenTheSetIsChangedFromNullToANonEmptyOne() throws Exception { Obs obs = new Obs(); assertNull(Obs.class.getDeclaredField("groupMembers").get(obs)); Set<Obs> members = new HashSet<>(); members.add(new Obs()); obs.setGroupMembers(members); assertFalse(obs.isDirty()); } /** * @see Obs#setGroupMembers(Set) */ @Test public void setGroupMembers_shouldNotMarkTheExistingObsAsDirtyWhenTheSetIsReplacedWithAnotherWithDifferentMembers() throws Exception { Obs obs = new Obs(2); Set<Obs> members1 = new HashSet<>(); members1.add(new Obs()); obs.setGroupMembers(members1); resetObs(obs); Set<Obs> members2 = new HashSet<>(); members2.add(new Obs()); obs.setGroupMembers(members2); assertFalse(obs.isDirty()); } /** * @see Obs#setGroupMembers(Set) */ @Test public void setGroupMembers_shouldNotMarkTheNewObsAsDirtyWhenTheSetIsReplacedWithAnotherWithDifferentMembers() throws Exception { Obs obs = new Obs(); Set<Obs> members1 = new HashSet<>(); members1.add(new Obs()); obs.setGroupMembers(members1); assertFalse(obs.isDirty()); Set<Obs> members2 = new HashSet<>(); members2.add(new Obs()); obs.setGroupMembers(members2); assertFalse(obs.isDirty()); } /** * @see Obs#setGroupMembers(Set) */ @Test public void setGroupMembers_shouldNotMarkTheObsAsDirtyWhenTheSetIsChangedFromNullToAnEmptyOne() throws Exception { Obs obs = new Obs(); assertNull(Obs.class.getDeclaredField("groupMembers").get(obs)); obs.setGroupMembers(new HashSet<>()); assertFalse(obs.isDirty()); } /** * @see Obs#setGroupMembers(Set) */ @Test public void setGroupMembers_shouldNotMarkTheObsAsDirtyWhenTheSetIsReplacedWithAnotherWithSameMembers() throws Exception { Obs obs = new Obs(); Obs o = new Obs(); Set<Obs> members1 = new HashSet<>(); members1.add(o); obs.setGroupMembers(members1); resetObs(obs); Set<Obs> members2 = new HashSet<>(); members2.add(o); obs.setGroupMembers(members2); assertFalse(obs.isDirty()); } /** * @see Obs#setObsDatetime(Date) */ @Test public void setObsDateTime_shouldNotMarkTheObsAsDirtyWhenDateIsNotChangedAndExistingValueIsOfTimeStampType(){ Obs obs = new Obs(); Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime()); obs.setObsDatetime(timestamp); obs.setId(1); assertFalse(obs.isDirty()); obs.setObsDatetime(date); assertFalse(obs.isDirty()); } @Test public void shouldSetFinalStatusOnNewObsByDefault() throws Exception { Obs obs = new Obs(); assertThat(obs.getStatus(), is(Obs.Status.FINAL)); } @Test public void newInstance_shouldCopyMostFields() throws Exception { Obs obs = new Obs(); obs.setStatus(Obs.Status.PRELIMINARY); obs.setInterpretation(Obs.Interpretation.LOW); obs.setConcept(new Concept()); obs.setValueNumeric(1.2); Obs copy = Obs.newInstance(obs); // these fields are not copied assertThat(copy.getObsId(), nullValue()); assertThat(copy.getUuid(), not(obs.getUuid())); // other fields are copied assertThat(copy.getConcept(), is(obs.getConcept())); assertThat(copy.getValueNumeric(), is(obs.getValueNumeric())); assertThat(copy.getStatus(), is(obs.getStatus())); assertThat(copy.getInterpretation(), is(obs.getInterpretation())); // TODO test that the rest of the fields are set } @Test public void shouldSupportInterpretationProperty() throws Exception { Obs obs = new Obs(); assertThat(obs.getInterpretation(), nullValue()); obs.setInterpretation(Obs.Interpretation.NORMAL); assertThat(obs.getInterpretation(), is(Obs.Interpretation.NORMAL)); } @Test public void setValueBoolean_shouldNotSetValueForNonBooleanConcept() throws Exception { Obs obs = createObs(2); ConceptDatatype dataType = new ConceptDatatype(); dataType.setUuid(ConceptDatatype.CODED_UUID); obs.getConcept().setDatatype(dataType); assertNotNull(obs.getValueCoded()); obs.setValueBoolean(null); assertNotNull(obs.getValueCoded()); } }
3e0fa91638645283fdd106fa1d173a45f1db66bf
4,972
java
Java
HealingBudz/app/src/main/java/com/codingpixel/healingbudz/DataModel/Budz.java
HEALINGBUDZ/healingbudzandroid
99e7c9a322e5caf5d94f6d79d406675bba2ed310
[ "Apache-2.0" ]
null
null
null
HealingBudz/app/src/main/java/com/codingpixel/healingbudz/DataModel/Budz.java
HEALINGBUDZ/healingbudzandroid
99e7c9a322e5caf5d94f6d79d406675bba2ed310
[ "Apache-2.0" ]
null
null
null
HealingBudz/app/src/main/java/com/codingpixel/healingbudz/DataModel/Budz.java
HEALINGBUDZ/healingbudzandroid
99e7c9a322e5caf5d94f6d79d406675bba2ed310
[ "Apache-2.0" ]
null
null
null
19.346304
58
0.604586
6,651
package com.codingpixel.healingbudz.DataModel; /** * Created by macmini on 12/04/2018. */ import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Budz { @SerializedName("id") @Expose private Integer id; @SerializedName("sub_user_id") @Expose private Integer subUserId; @SerializedName("strain_id") @Expose private Integer strainId; @SerializedName("type_id") @Expose private Integer typeId; @SerializedName("name") @Expose private String name; @SerializedName("thc") @Expose private Double thc; @SerializedName("cbd") @Expose private Double cbd; @SerializedName("created_at") @Expose private String createdAt; @SerializedName("updated_at") @Expose private String updatedAt; @SerializedName("user_id") @Expose private Integer userId; @SerializedName("title") @Expose private String title; @SerializedName("logo") @Expose private Object logo; @SerializedName("lat") @Expose private Double lat; @SerializedName("lng") @Expose private Double lng; @SerializedName("tag_id") @Expose private Integer tagId; @SerializedName("state") @Expose private String state; @SerializedName("price") @Expose private Integer price; @SerializedName("tag_title") @Expose private String tagTitle; @SerializedName("distance") @Expose private Double distance; @SerializedName("strain_type") @Expose private StrainType strainType; @SerializedName("images") @Expose private List<ImageModelStrain> images = null; @SerializedName("pricing") @Expose private List<Pricing> pricing = null; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSubUserId() { return subUserId; } public void setSubUserId(Integer subUserId) { this.subUserId = subUserId; } public Integer getStrainId() { return strainId; } public void setStrainId(Integer strainId) { this.strainId = strainId; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getThc() { return thc; } public void setThc(Double thc) { this.thc = thc; } public Double getCbd() { return cbd; } public void setCbd(Double cbd) { this.cbd = cbd; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Object getLogo() { return logo; } public void setLogo(Object logo) { this.logo = logo; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLng() { return lng; } public void setLng(Double lng) { this.lng = lng; } public Integer getTagId() { return tagId; } public void setTagId(Integer tagId) { this.tagId = tagId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public String getTagTitle() { return tagTitle; } public void setTagTitle(String tagTitle) { this.tagTitle = tagTitle; } public Double getDistance() { return distance; } public void setDistance(Double distance) { this.distance = distance; } public StrainType getStrainType() { return strainType; } public void setStrainType(StrainType strainType) { this.strainType = strainType; } public List<ImageModelStrain> getImages() { return images; } public void setImages(List<ImageModelStrain> images) { this.images = images; } public List<Pricing> getPricing() { return pricing; } public void setPricing(List<Pricing> pricing) { this.pricing = pricing; } }
3e0fa9949e6e3dc8a1ed55d52d82ac3529d9f29e
2,396
java
Java
java-impl/src/main/java/com/siyeh/ig/style/ChainedEqualityInspection.java
consulo/consulo-java
e016b25321f49547a57e97132c013468c2a50316
[ "Apache-2.0" ]
5
2015-12-19T15:27:30.000Z
2019-08-17T10:07:23.000Z
java-impl/src/main/java/com/siyeh/ig/style/ChainedEqualityInspection.java
consulo/consulo-java
e016b25321f49547a57e97132c013468c2a50316
[ "Apache-2.0" ]
47
2015-02-28T12:45:13.000Z
2021-12-15T15:42:34.000Z
java-impl/src/main/java/com/siyeh/ig/style/ChainedEqualityInspection.java
consulo/consulo-java
e016b25321f49547a57e97132c013468c2a50316
[ "Apache-2.0" ]
2
2018-03-08T16:17:47.000Z
2019-08-17T18:20:38.000Z
31.116883
94
0.721202
6,652
/* * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ig.style; import javax.annotation.Nonnull; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiPolyadicExpression; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.psiutils.ComparisonUtils; public class ChainedEqualityInspection extends BaseInspection { @Nonnull public String getID() { return "ChainedEqualityComparisons"; } @Nonnull public String getDisplayName() { return InspectionGadgetsBundle.message("chained.equality.comparisons.display.name"); } @Nonnull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("chained.equality.comparisons.problem.descriptor"); } public BaseInspectionVisitor buildVisitor() { return new ChainedEqualityVisitor(); } private static class ChainedEqualityVisitor extends BaseInspectionVisitor { @Override public void visitPolyadicExpression(PsiPolyadicExpression expression) { super.visitPolyadicExpression(expression); if (!ComparisonUtils.isEqualityComparison(expression)) { return; } final PsiElement parent = expression.getParent(); if (parent instanceof PsiExpression) { if (ComparisonUtils.isEqualityComparison((PsiExpression)parent)) { return; } } final PsiExpression[] operands = expression.getOperands(); if (operands.length >= 3) { registerError(expression); } else { for (PsiExpression operand : operands) { if (ComparisonUtils.isEqualityComparison(operand)) { registerError(expression); break; } } } } } }
3e0faa26dffe9d34dc45acb13f3510b46ed345ee
1,215
java
Java
src/main/java/ross/palmer/interstellar/gui/old/SimpleLayout.java
rosspalmer/Interstellar-Empire-Toolkit
56ce573d133ed0a72e40f71581eb4ca66c46b088
[ "MIT" ]
null
null
null
src/main/java/ross/palmer/interstellar/gui/old/SimpleLayout.java
rosspalmer/Interstellar-Empire-Toolkit
56ce573d133ed0a72e40f71581eb4ca66c46b088
[ "MIT" ]
null
null
null
src/main/java/ross/palmer/interstellar/gui/old/SimpleLayout.java
rosspalmer/Interstellar-Empire-Toolkit
56ce573d133ed0a72e40f71581eb4ca66c46b088
[ "MIT" ]
null
null
null
27
87
0.692181
6,653
package ross.palmer.interstellar.gui.old; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import ross.palmer.interstellar.gui.old.explorer.SystemExplorer; public class SimpleLayout extends GridPane { private VBox verticalSelectionRibbon; private Node mainNode; private Label home; private SystemExplorer systemExplorer; public SimpleLayout() { super(); generateHome(); generateVerticalSelectionRibbon(); add(verticalSelectionRibbon, 0, 0); systemExplorer = new SystemExplorer(); } public void generateHome() { home = new Label("WelcomeEE Home Space Travel mate"); add(home, 1, 0); } public void generateVerticalSelectionRibbon() { verticalSelectionRibbon = new VBox(); Button homeButton = new Button("Home"); Button systemExplorerButton = new Button("System Explorer"); systemExplorerButton.setOnAction(event -> { add(systemExplorer, 1, 0); }); verticalSelectionRibbon.getChildren().addAll(homeButton, systemExplorerButton); } }
3e0faa38767b717dd04fc2a3c5ad17297ffd2cfa
1,561
java
Java
Lab 11/src/DataTester.java
pigion138138/IST210-Labs
3d85ede79897522303287ead9e4394cdd0d87440
[ "MIT" ]
null
null
null
Lab 11/src/DataTester.java
pigion138138/IST210-Labs
3d85ede79897522303287ead9e4394cdd0d87440
[ "MIT" ]
null
null
null
Lab 11/src/DataTester.java
pigion138138/IST210-Labs
3d85ede79897522303287ead9e4394cdd0d87440
[ "MIT" ]
null
null
null
24.777778
90
0.639334
6,654
public class DataTester { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = new int[100]; arr[0] = 77; // insert 10 items arr[1] = 99; arr[2] = 44; arr[3] = 55; arr[4] = 22; arr[5] = 88; arr[6] = 11; arr[7] = 3; arr[8] = 66; arr[9] = 33; int nElems = 10; // now 10 items in array IntegerData arrayObj= new IntegerData(arr, nElems); System.out.format("\nDisplaying all members of the array\n"); arrayObj.DisplayAll(); System.out.format("\nDisplaying element at index 6 of the array\n"); arrayObj.DisplayAt(6); System.out.format("\nFind 55 in the array\n"); if (arrayObj.Find(55) != -1) { System.out.format("Number 55 was found at index %d of the array\n", arrayObj.Find(55)); } else { System.out.format("Number 55 was NOT found.\n"); } System.out.format("\nDelete 55 from the array\n"); arrayObj.Delete(55); System.out.format("\nFind 55 in the array\n"); if (arrayObj.Find(55) != -1) { System.out.format("Number 55 was found at index %d of the array\n", arrayObj.Find(55)); } else { System.out.format("Number 55 was NOT found.\n"); } System.out.format("\nDisplaying all members of the array\n"); arrayObj.DisplayAll(); System.out.format("\nSorting the array\n"); arrayObj.bubbleSort(); System.out.format("\nDisplaying all members of the array\n"); arrayObj.DisplayAll(); System.out.format("\nInset 49 into the array and then display array\n"); arrayObj.insert(49); arrayObj.DisplayAll(); } }
3e0faaca66c7bbcf070591944766a9a78dd8965c
4,996
java
Java
src/main/java/de/nevini/modules/osu/services/OsuUserService.java
geotim90/Nevini
d97067af522224eb631d64ef347cf9b4627897c1
[ "Apache-2.0" ]
4
2019-04-25T18:35:01.000Z
2020-11-20T05:03:47.000Z
src/main/java/de/nevini/modules/osu/services/OsuUserService.java
geotim90/Nevini
d97067af522224eb631d64ef347cf9b4627897c1
[ "Apache-2.0" ]
42
2019-05-11T19:34:46.000Z
2021-04-17T11:55:16.000Z
src/main/java/de/nevini/modules/osu/services/OsuUserService.java
geotim90/Nevini
d97067af522224eb631d64ef347cf9b4627897c1
[ "Apache-2.0" ]
null
null
null
39.650794
104
0.660328
6,655
package de.nevini.modules.osu.services; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import de.nevini.core.api.ApiResponse; import de.nevini.modules.osu.api.OsuApi; import de.nevini.modules.osu.api.OsuApiProvider; import de.nevini.modules.osu.api.requests.OsuApiGetUserRequest; import de.nevini.modules.osu.api.requests.OsuUserType; import de.nevini.modules.osu.data.OsuUserData; import de.nevini.modules.osu.data.OsuUserId; import de.nevini.modules.osu.data.OsuUserRepository; import de.nevini.modules.osu.mappers.OsuUserMapper; import de.nevini.modules.osu.model.OsuMode; import de.nevini.modules.osu.model.OsuUser; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import java.time.Duration; import java.util.List; import java.util.stream.Collectors; @Slf4j @Service public class OsuUserService { private final Cache<OsuApiGetUserRequest, List<OsuUser>> requestCache; private final Cache<OsuUserId, OsuUser> cache; private final OsuApi api; private final OsuUserRepository repository; private final OsuAsyncService asyncService; public OsuUserService( @Autowired OsuApiProvider apiProvider, @Autowired OsuUserRepository repository, @Autowired OsuAsyncService asyncService ) { this.requestCache = CacheBuilder.newBuilder().expireAfterWrite(Duration.ofMinutes(1)).build(); this.cache = CacheBuilder.newBuilder().expireAfterWrite(Duration.ofMinutes(1)).build(); this.api = apiProvider.getApi(); this.repository = repository; this.asyncService = asyncService; } public @NonNull ApiResponse<List<OsuUser>> get(@NonNull OsuApiGetUserRequest request) { return getFromCache(request).orElse(() -> getFromApi(request) ); } private @NonNull ApiResponse<List<OsuUser>> getFromCache(@NonNull OsuApiGetUserRequest request) { return ApiResponse.ok(requestCache.getIfPresent(request)); } private @NonNull ApiResponse<List<OsuUser>> getFromApi(@NonNull OsuApiGetUserRequest request) { ApiResponse<List<OsuUserData>> response = api.getUser(request).map(list -> list.stream().map(user -> OsuUserMapper.map(user, request)).collect(Collectors.toList()) ); ApiResponse<List<OsuUser>> result = response.map(list -> list.stream().map(OsuUserMapper::map).collect(Collectors.toList()) ); if (!result.isEmpty()) { requestCache.put(request, result.getResult()); result.getResult().forEach(user -> cache.put(new OsuUserId(user.getUserId(), ObjectUtils.defaultIfNull(request.getMode(), OsuMode.STANDARD.getId())), user)); log.debug("Save data: {}", response.getResult()); try { repository.saveAll(response.getResult()); } catch (DataAccessException e) { // new users may have one or more null values log.debug("Save data failed", e); return ApiResponse.error(e); } } return result; } public ApiResponse<OsuUser> get(int userId, int mode) { OsuUserId id = new OsuUserId(userId, mode); return getFromCache(id).orElse(() -> getFromApi(id).orElse(apiResponse -> getFromDatabase(id).orElse(apiResponse) ) ); } public ApiResponse<OsuUser> getCached(int userId, int mode) { OsuUserId id = new OsuUserId(userId, mode); return getFromCache(id).orElse(() -> getFromDatabase(id).orElse(() -> getFromApi(id) ) ); } private @NonNull ApiResponse<OsuUser> getFromCache(@NonNull OsuUserId id) { return ApiResponse.ok(cache.getIfPresent(id)); } private @NonNull ApiResponse<OsuUser> getFromApi(@NonNull OsuUserId id) { OsuApiGetUserRequest request = OsuApiGetUserRequest.builder() .user(Integer.toString(id.getUserId())) .userType(OsuUserType.ID) .mode(id.getMode()) .build(); return get(request).map(list -> list.stream().findFirst().orElse(null)); } private @NonNull ApiResponse<OsuUser> getFromDatabase(@NonNull OsuUserId id) { // queue update OsuApiGetUserRequest request = OsuApiGetUserRequest.builder() .user(Integer.toString(id.getUserId())) .userType(OsuUserType.ID) .mode(id.getMode()) .build(); asyncService.addTask(request, () -> get(request)); // get from database return ApiResponse.ok(repository.findById(id).map(OsuUserMapper::map).orElse(null)); } }
3e0fab3a2836d4fbb694eac76fb309806d2cb8dd
929
java
Java
Verbs/src/main/java/org/sj/noun/trilateral/unaugmented/modifier/passiveparticiple/hamza/EinMahmouz.java
salahja/Arabic-Verb-Conjugation
5b38d319d36b2fab02b8f5c83ab200f4b2bedc3d
[ "MIT" ]
null
null
null
Verbs/src/main/java/org/sj/noun/trilateral/unaugmented/modifier/passiveparticiple/hamza/EinMahmouz.java
salahja/Arabic-Verb-Conjugation
5b38d319d36b2fab02b8f5c83ab200f4b2bedc3d
[ "MIT" ]
null
null
null
Verbs/src/main/java/org/sj/noun/trilateral/unaugmented/modifier/passiveparticiple/hamza/EinMahmouz.java
salahja/Arabic-Verb-Conjugation
5b38d319d36b2fab02b8f5c83ab200f4b2bedc3d
[ "MIT" ]
null
null
null
26.542857
83
0.634015
6,656
package org.sj.noun.trilateral.unaugmented.modifier.passiveparticiple.hamza; import java.util.*; import org.sj.verb.trilateral.Substitution.*; import org.sj.noun.trilateral.unaugmented.modifier.*; /** * <p>Title: Sarf Program</p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: ALEXO</p> * * @author Haytham Mohtasseb Billah * @version 1.0 */ public class EinMahmouz extends AbstractEinMahmouz { List substitutions = new LinkedList(); public EinMahmouz() { substitutions.add(new InfixSubstitution("وْءُ", "وْءُ")); // EX: (مَوْءُود) substitutions.add(new InfixSubstitution("يْءُ", "يْئُ")); // EX: (مَيْئُوس) substitutions.add(new InfixSubstitution("ْءُ", "ْؤُ")); // EX: (مَسْؤُول) substitutions.add(new InfixSubstitution("ْءِ", "ْئِ")); // EX: (مَرْئِيّ) } public List getSubstitutions() { return substitutions; } }
3e0fab499f48b0a7f2578bda2f88a16d21f52d4f
1,038
java
Java
PartVIIII/lesson6/src/main/java/ru/szhernovoy/controllers/RoleCreate.java
SergeyZhernovoy/Java-education
2fcb28d25a83266aeed537417d748c973d1ab918
[ "Apache-2.0" ]
20
2016-07-09T10:47:37.000Z
2018-08-02T10:32:56.000Z
PartVIIII/lesson6/src/main/java/ru/szhernovoy/controllers/RoleCreate.java
SergeyZhernovoy/Java-education
2fcb28d25a83266aeed537417d748c973d1ab918
[ "Apache-2.0" ]
null
null
null
PartVIIII/lesson6/src/main/java/ru/szhernovoy/controllers/RoleCreate.java
SergeyZhernovoy/Java-education
2fcb28d25a83266aeed537417d748c973d1ab918
[ "Apache-2.0" ]
3
2016-10-22T02:46:06.000Z
2020-11-05T13:08:55.000Z
31.454545
114
0.710983
6,657
/** * Created by szhernovoy on 02.12.2016. */ package ru.szhernovoy.controllers; import ru.szhernovoy.model.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RoleCreate extends javax.servlet.http.HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Role role = new Role(req.getParameter("name")); String root = req.getParameter("root"); if(root!=null){ role.setRoot(root.equals("1")? true : false); } DBManager.newInstance().addRole(role); doGet(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("roles",DBManager.newInstance().getRoles()); req.getRequestDispatcher("/WEB-INF/views/CreateRole.jsp").forward(req,resp); } }
3e0fab9ca7a7e564ee3b61b8f5ce9e1bf5f69c69
1,185
java
Java
yatl-kmf/src/test/java/ws/wsdl/BindingOperationFactory$Class.java
opatrascoiu/jmf
be597da51fa5964f07ee74213640894af8fff535
[ "Apache-2.0" ]
null
null
null
yatl-kmf/src/test/java/ws/wsdl/BindingOperationFactory$Class.java
opatrascoiu/jmf
be597da51fa5964f07ee74213640894af8fff535
[ "Apache-2.0" ]
null
null
null
yatl-kmf/src/test/java/ws/wsdl/BindingOperationFactory$Class.java
opatrascoiu/jmf
be597da51fa5964f07ee74213640894af8fff535
[ "Apache-2.0" ]
null
null
null
24.6875
78
0.729958
6,658
/** * * Class BindingOperationFactory$Class.java * * Generated by KMFStudio at 09 March 2004 13:29:40 * Visit http://www.cs.ukc.ac.uk/kmf * */ package ws.wsdl; public class BindingOperationFactory$Class extends ws.WsFactory$Class implements BindingOperationFactory { /** Default factory constructor */ public BindingOperationFactory$Class() { } public BindingOperationFactory$Class(ws.repository.WsRepository repository) { this.repository = repository; } /** Default build method */ public Object build() { BindingOperation obj = new BindingOperation$Class(); obj.setId(ws.WsFactory$Class.newId()); repository.addElement("ws.wsdl.BindingOperation", obj); return obj; } /** Specialized build method */ public Object build(String name) { BindingOperation obj = new BindingOperation$Class(name); obj.setId(ws.WsFactory$Class.newId()); repository.addElement("ws.wsdl.BindingOperation", obj); return obj; } /** Override toString method */ public String toString() { return "BindingOperationFactory"; } /** Accept 'ws.wsdl.BindingOperationVisitor' */ public Object accept(ws.WsVisitor v, Object data) { return v.visit(this, data); } }
3e0fabd52fbd911a8edce64497f8d9d07c2a8ada
1,256
java
Java
repast.simphony.distributed.batch/src/repast/simphony/batch/ProcessOutputWriter.java
Repast/repast.simphony
b9baedb73cabe8c05c76b9fa2fb616b7fe3ee7d6
[ "Apache-2.0" ]
73
2016-09-30T18:45:25.000Z
2022-03-29T02:07:17.000Z
repast.simphony.distributed.batch/src/repast/simphony/batch/ProcessOutputWriter.java
jonas-andersen/repast.simphony
b9baedb73cabe8c05c76b9fa2fb616b7fe3ee7d6
[ "Apache-2.0" ]
47
2016-12-15T22:05:37.000Z
2022-03-14T09:29:57.000Z
repast.simphony.distributed.batch/src/repast/simphony/batch/ProcessOutputWriter.java
jonas-andersen/repast.simphony
b9baedb73cabe8c05c76b9fa2fb616b7fe3ee7d6
[ "Apache-2.0" ]
22
2017-01-13T10:46:51.000Z
2022-03-17T02:47:00.000Z
24.153846
81
0.681529
6,659
/** * */ package repast.simphony.batch; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; /** * Writes the output of a Process to a log file. * * @author Nick Collier */ public class ProcessOutputWriter { private File file; private boolean showInConsole = false; public ProcessOutputWriter(File file, boolean showInConsole) { this.file = file; this.showInConsole = showInConsole; } public ProcessOutputWriter(File file) { this(file, false); } public void captureOutput(Process process) throws IOException { InputStreamReader tempReader = new InputStreamReader(new BufferedInputStream( process.getInputStream())); BufferedReader reader = new BufferedReader(tempReader); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); String line = ""; while ((line = reader.readLine()) != null) { writer.write(line); writer.write("\n"); if (showInConsole) System.out.println(line); } } finally { if (writer != null) writer.close(); } } }
3e0fabf4f3df3b7f25defa365debaf03fdfdf90d
171
java
Java
app/src/main/java/com/birdcopy/BirdCopyApp/Component/UI/tagview/OnTagClickListener.java
birdcopy/birdcopy
9b93bf2b7c0fba2cdb8ab844cae515f2b105f665
[ "MIT" ]
null
null
null
app/src/main/java/com/birdcopy/BirdCopyApp/Component/UI/tagview/OnTagClickListener.java
birdcopy/birdcopy
9b93bf2b7c0fba2cdb8ab844cae515f2b105f665
[ "MIT" ]
null
null
null
app/src/main/java/com/birdcopy/BirdCopyApp/Component/UI/tagview/OnTagClickListener.java
birdcopy/birdcopy
9b93bf2b7c0fba2cdb8ab844cae515f2b105f665
[ "MIT" ]
null
null
null
21.375
54
0.766082
6,660
package com.birdcopy.BirdCopyApp.Component.UI.tagview; /** * listener for tag delete */ public interface OnTagClickListener { void onTagClick(Tag tag, int position); }
3e0fad4b28a139cb3b1c679a0542c66cfb9f5130
2,392
java
Java
catmall-coupon/src/main/java/com/hongchai/catmall/coupon/controller/HomeSubjectSpuController.java
brucewoods/Catmall
909e3925c24e8977aa9cec06d1eacfcc2b084389
[ "Apache-2.0" ]
null
null
null
catmall-coupon/src/main/java/com/hongchai/catmall/coupon/controller/HomeSubjectSpuController.java
brucewoods/Catmall
909e3925c24e8977aa9cec06d1eacfcc2b084389
[ "Apache-2.0" ]
3
2021-01-06T03:46:03.000Z
2021-09-20T20:59:23.000Z
catmall-coupon/src/main/java/com/hongchai/catmall/coupon/controller/HomeSubjectSpuController.java
brucewoods/Catmall
909e3925c24e8977aa9cec06d1eacfcc2b084389
[ "Apache-2.0" ]
null
null
null
26.351648
74
0.715179
6,661
package com.hongchai.catmall.coupon.controller; import java.util.Arrays; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.hongchai.catmall.coupon.entity.HomeSubjectSpuEntity; import com.hongchai.catmall.coupon.service.HomeSubjectSpuService; import com.hongchai.common.utils.PageUtils; import com.hongchai.common.utils.R; /** * 专题商品 * * @author brucewoods * @email efpyi@example.com * @date 2020-04-24 13:03:31 */ @RestController @RequestMapping("coupon/homesubjectspu") public class HomeSubjectSpuController { @Autowired private HomeSubjectSpuService homeSubjectSpuService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("coupon:homesubjectspu:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = homeSubjectSpuService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("coupon:homesubjectspu:info") public R info(@PathVariable("id") Long id){ HomeSubjectSpuEntity homeSubjectSpu = homeSubjectSpuService.getById(id); return R.ok().put("homeSubjectSpu", homeSubjectSpu); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("coupon:homesubjectspu:save") public R save(@RequestBody HomeSubjectSpuEntity homeSubjectSpu){ homeSubjectSpuService.save(homeSubjectSpu); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("coupon:homesubjectspu:update") public R update(@RequestBody HomeSubjectSpuEntity homeSubjectSpu){ homeSubjectSpuService.updateById(homeSubjectSpu); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("coupon:homesubjectspu:delete") public R delete(@RequestBody Long[] ids){ homeSubjectSpuService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
3e0fad554687ab24bbec43bffdad48eb42ded1de
1,435
java
Java
DAA-Java/code/src/main/java/com/me/Recursion/Hanoi.java
zzzzzzzs/DataStructureAndAlgorithms
362f47eda6193217d01acd28e2c239e0c98ac4fb
[ "MIT" ]
null
null
null
DAA-Java/code/src/main/java/com/me/Recursion/Hanoi.java
zzzzzzzs/DataStructureAndAlgorithms
362f47eda6193217d01acd28e2c239e0c98ac4fb
[ "MIT" ]
null
null
null
DAA-Java/code/src/main/java/com/me/Recursion/Hanoi.java
zzzzzzzs/DataStructureAndAlgorithms
362f47eda6193217d01acd28e2c239e0c98ac4fb
[ "MIT" ]
null
null
null
22.421875
76
0.486411
6,662
package com.me.Recursion; /** * @author zs * @date 2021/10/25 * 汉诺塔 */ public class Hanoi { public static void hanoi(int n) { if (n > 0) { func(n, "左", "右", "中"); } } // 1~i 圆盘 目标是from -> to, other是另外一个 public static void func(int N, String from, String to, String other) { if (N == 1) { // base System.out.println("Move 1 from " + from + " to " + to); } else { func(N - 1, from, other, to); System.out.println("Move " + N + " from " + from + " to " + to); func(N - 1, other, to, from); } } public static void printAllWays(int n) { leftToRight(n); } public static void leftToRight(int n) { if(n== 1) { System.out.println("Move 1 from left to right"); return ; } leftToMid(n-1); System.out.println("Move " +n + " from left to right"); midToRight(n-1); } public static void leftToMid(int n) { if(n== 1) { System.out.println("Move 1 from left to mid"); return ; } leftToRight(n-1); System.out.println("Move " +n + " from left to mid"); rightToMid(n-1); } public static void midToRight(int n) { } public static void rightToMid(int n) { } public static void main(String[] args) { int n = 3; hanoi(n); } }
3e0fada18359c4b5a964678c0a3b9c768aa054b8
6,040
java
Java
tests/src/test/java/com/orientechnologies/orient/test/database/auto/ConcurrentUpdatesTest.java
kowalot/orientdb
25d95a6d10ab90cb492440fc0c4fe67d49eec053
[ "Apache-2.0" ]
null
null
null
tests/src/test/java/com/orientechnologies/orient/test/database/auto/ConcurrentUpdatesTest.java
kowalot/orientdb
25d95a6d10ab90cb492440fc0c4fe67d49eec053
[ "Apache-2.0" ]
null
null
null
tests/src/test/java/com/orientechnologies/orient/test/database/auto/ConcurrentUpdatesTest.java
kowalot/orientdb
25d95a6d10ab90cb492440fc0c4fe67d49eec053
[ "Apache-2.0" ]
null
null
null
35.739645
100
0.674172
6,663
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.test.database.auto; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.orientechnologies.common.concur.ONeedRetryException; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; @Test public class ConcurrentUpdatesTest { protected String url; private boolean level1CacheEnabled; private boolean level2CacheEnabled; private boolean mvccEnabled; static class UpdateField implements Runnable { ODatabaseDocumentTx db; ORID rid1; ORID rid2; String fieldValue = null; String threadName; public UpdateField(ODatabaseDocumentTx iDb, ORID iRid1, ORID iRid2, String iThreadName) { super(); db = iDb; rid1 = iRid1; rid2 = iRid2; threadName = iThreadName; } public void run() { try { for (int i = 0; i < 50; i++) { while (true) { try { db.begin(TXTYPE.OPTIMISTIC); ODocument vDoc1 = db.load(rid1, null, true); vDoc1.field(threadName, vDoc1.field(threadName) + ";" + i); vDoc1.save(); ODocument vDoc2 = db.load(rid2, null, true); vDoc2.field(threadName, vDoc2.field(threadName) + ";" + i); vDoc2.save(); db.commit(); break; } catch (ONeedRetryException e) { System.out.println("Retry... " + Thread.currentThread().getName() + " " + i); } } fieldValue += ";" + i; } } catch (Throwable e) { e.printStackTrace(); } } } @Parameters(value = "url") public ConcurrentUpdatesTest(@Optional(value = "memory:test") String iURL) { url = iURL; } @BeforeClass public void init() { level1CacheEnabled = OGlobalConfiguration.CACHE_LEVEL1_ENABLED.getValueAsBoolean(); level2CacheEnabled = OGlobalConfiguration.CACHE_LEVEL2_ENABLED.getValueAsBoolean(); mvccEnabled = OGlobalConfiguration.DB_MVCC.getValueAsBoolean(); if (level1CacheEnabled) OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false); if (level2CacheEnabled) OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false); if (!mvccEnabled) OGlobalConfiguration.DB_MVCC.setValue(true); if ("memory:test".equals(url)) new ODatabaseDocumentTx(url).create().close(); } @AfterClass public void deinit() { OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(level1CacheEnabled); OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(level2CacheEnabled); OGlobalConfiguration.DB_MVCC.setValue(mvccEnabled); } @Test public void concurrentUpdates() throws Exception { if (url.startsWith("plocal:")) return; ODatabaseDocumentTx database1 = new ODatabaseDocumentTx(url).open("admin", "admin"); ODatabaseDocumentTx database2 = new ODatabaseDocumentTx(url).open("admin", "admin"); ODatabaseDocumentTx database3 = new ODatabaseDocumentTx(url).open("admin", "admin"); ODocument doc1 = database1.newInstance(); doc1.field("INIT", "ok"); database1.save(doc1); ORID rid1 = doc1.getIdentity(); ODocument doc2 = database1.newInstance(); doc2.field("INIT", "ok"); database1.save(doc2); ORID rid2 = doc2.getIdentity(); UpdateField vUpdate1 = new UpdateField(database1, rid1, rid2, "thread1"); UpdateField vUpdate2 = new UpdateField(database2, rid2, rid1, "thread2"); UpdateField vUpdate3 = new UpdateField(database3, rid2, rid1, "thread3"); Thread vThread1 = new Thread(vUpdate1, "ConcurrentTest1"); Thread vThread2 = new Thread(vUpdate2, "ConcurrentTest2"); Thread vThread3 = new Thread(vUpdate3, "ConcurrentTest3"); vThread1.start(); vThread2.start(); vThread3.start(); vThread1.join(); vThread2.join(); vThread3.join(); doc1 = database1.load(rid1, null, true); Assert.assertEquals(doc1.field(vUpdate1.threadName), vUpdate1.fieldValue, vUpdate1.threadName); Assert.assertEquals(doc1.field(vUpdate2.threadName), vUpdate2.fieldValue, vUpdate2.threadName); Assert.assertEquals(doc1.field(vUpdate3.threadName), vUpdate3.fieldValue, vUpdate3.threadName); System.out.println("RESULT doc 1:"); System.out.println(doc1.toJSON()); doc2 = database1.load(rid2, null, true); Assert.assertEquals(doc2.field(vUpdate1.threadName), vUpdate1.fieldValue, vUpdate1.threadName); Assert.assertEquals(doc2.field(vUpdate2.threadName), vUpdate2.fieldValue, vUpdate2.threadName); Assert.assertEquals(doc2.field(vUpdate3.threadName), vUpdate3.fieldValue, vUpdate3.threadName); System.out.println("RESULT doc 2:"); System.out.println(doc2.toJSON()); database1.close(); database2.close(); } }
3e0fadbfbe599222f8c2f41926a0b39cff832eed
3,719
java
Java
webapp/src/main/java/uk/ac/ebi/arrayexpress/components/DbConnectionPool.java
arrayexpress/ae-interface
a471a6a9c0517f50e052d8413e082d919bdad74e
[ "Apache-2.0" ]
3
2016-10-08T15:14:44.000Z
2019-10-01T09:54:49.000Z
webapp/src/main/java/uk/ac/ebi/arrayexpress/components/DbConnectionPool.java
arrayexpress/ae-interface
a471a6a9c0517f50e052d8413e082d919bdad74e
[ "Apache-2.0" ]
null
null
null
webapp/src/main/java/uk/ac/ebi/arrayexpress/components/DbConnectionPool.java
arrayexpress/ae-interface
a471a6a9c0517f50e052d8413e082d919bdad74e
[ "Apache-2.0" ]
3
2015-02-17T17:12:34.000Z
2019-05-08T05:52:31.000Z
38.739583
125
0.623286
6,664
package uk.ac.ebi.arrayexpress.components; import com.zaxxer.hikari.HikariConfig; import org.apache.commons.configuration.HierarchicalConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.arrayexpress.app.ApplicationComponent; import uk.ac.ebi.arrayexpress.utils.db.ConnectionSource; import uk.ac.ebi.arrayexpress.utils.db.IConnectionSource; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Copyright 2009-2014 European Molecular Biology Laboratory * * 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. * */ public class DbConnectionPool extends ApplicationComponent { // logging machinery private final Logger logger = LoggerFactory.getLogger(getClass()); private Map<String, HikariConfig> configs = new HashMap<>(); @Override public void initialize() throws Exception { HierarchicalConfiguration connsConf = (HierarchicalConfiguration)getPreferences().getConfSubset("ae.db.connections"); if (null != connsConf) { List conns = connsConf.configurationsAt("connection"); for (Object conn : conns) { HierarchicalConfiguration connConf = (HierarchicalConfiguration)conn; String connName = connConf.getString("name"); logger.debug("Configuring pool for connection [{}]", connName); try { Class.forName(connConf.getString("driver")); } catch (ClassNotFoundException x) { logger.error("Unable to load driver [{}] for connection [{}]", connConf.getString("driver"), connName); } HikariConfig cpConf = new HikariConfig(); cpConf.setJdbcUrl(connConf.getString("url")); cpConf.setUsername(connConf.getString("username")); cpConf.setPassword(connConf.getString("password")); cpConf.setConnectionTestQuery(connConf.getString("testStatement")); cpConf.setMaximumPoolSize(connConf.getInt("maxConnections")); this.configs.put(connName, cpConf); } } } @Override public void terminate() throws Exception { } public IConnectionSource getConnectionSource( String connectionNames ) { if (null != connectionNames) { String[] conns = connectionNames.trim().split("\\s*,\\s*"); for ( String conn : conns ) { logger.info("Checking connection [{}]", conn); if (!configs.containsKey(conn)) { logger.error("Connection [{}] is not configured", conn); } else { try { IConnectionSource source = new ConnectionSource(conn, configs.get(conn)); logger.info("Will use available connection [{}]", conn); return source; } catch (SQLException x) { logger.warn("Connection [{}] is unavailable", conn); logger.debug("Exception was:", x); } } } } return null; } }
3e0fade5e80a35124460426260b7047b4bdf0ebd
423
java
Java
samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java
blackbaud/swagger-codegen
ee955d2e12ea44987b8f987ae238d8f8ab10ab44
[ "Apache-2.0" ]
null
null
null
samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java
blackbaud/swagger-codegen
ee955d2e12ea44987b8f987ae238d8f8ab10ab44
[ "Apache-2.0" ]
5
2015-10-22T19:18:35.000Z
2016-03-10T16:52:14.000Z
samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java
blackbaud/swagger-codegen
ee955d2e12ea44987b8f987ae238d8f8ab10ab44
[ "Apache-2.0" ]
null
null
null
28.2
131
0.758865
6,665
package io.swagger.client.auth; import io.swagger.client.Pair; import java.util.Map; import java.util.List; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") public class OAuth implements Authentication { @Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { // TODO: support oauth } }
3e0fafc03a05bec8243d7bb1e01ae7f677ed1483
21,110
java
Java
jcf-data/jcf-query/src/main/java/jcf/query/core/QueryExecutorWrapper.java
wall72/JavaCoreFramework
91d9fa9966d058ed8bc7dc5a8bc5d8ec0f621d8b
[ "MIT" ]
null
null
null
jcf-data/jcf-query/src/main/java/jcf/query/core/QueryExecutorWrapper.java
wall72/JavaCoreFramework
91d9fa9966d058ed8bc7dc5a8bc5d8ec0f621d8b
[ "MIT" ]
null
null
null
jcf-data/jcf-query/src/main/java/jcf/query/core/QueryExecutorWrapper.java
wall72/JavaCoreFramework
91d9fa9966d058ed8bc7dc5a8bc5d8ec0f621d8b
[ "MIT" ]
null
null
null
24.893868
159
0.72288
6,666
package jcf.query.core; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jcf.data.handler.StreamHandler; import jcf.query.core.decorator.QueryDecorator; import jcf.query.web.CommonVariableHolder; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.core.RowMapper; import org.springframework.util.StringUtils; import com.googlecode.ehcache.annotations.key.CacheKeyGenerator; import com.googlecode.ehcache.annotations.key.HashCodeCacheKeyGenerator; /** * * @author nolang * */ public class QueryExecutorWrapper { private static final Logger logger = LoggerFactory.getLogger(QueryExecutorWrapper.class); @Autowired private QueryExecutor queryExecutor; private QueryDecorator decorator = new QueryDecorator() { public void beforeExecution(Object... args) { } public void afterExecution(Object... args) { CommonVariableHolder.clear(); } }; private CacheManager cacheManager; private String defaultCacheName = "testCache"; private CacheKeyGenerator<?> cacheKeyGenerator = new HashCodeCacheKeyGenerator(); private long keepAliveTime = 30000; private Map<String, List<Object>> cacheKeyHolder = new LinkedHashMap<String, List<Object>>(); private boolean usePropertyName = true; public void setQueryExecutor(QueryExecutor queryExecutor) { this.queryExecutor = queryExecutor; } public void setDecorator(QueryDecorator decorator) { this.decorator = decorator; } public void setCacheManager(CacheManager cacheManager) { this.cacheManager = cacheManager; } public void setDefaultCacheName(String defaultCacheName) { this.defaultCacheName = defaultCacheName; } public void setCacheKeyGenerator(CacheKeyGenerator<?> cacheKeyGenerator) { this.cacheKeyGenerator = cacheKeyGenerator; } public void setKeepAliveTime(long keepAliveTime) { this.keepAliveTime = keepAliveTime; } public QueryExecutorWrapper() { ((HashCodeCacheKeyGenerator) cacheKeyGenerator).setUseReflection(true); } /** * * @param statementTemplate * @param parameter */ public void queryForStream(Object statementTemplate, Object parameter) { decorator.beforeExecution(statementTemplate, parameter); try { queryExecutor.queryForStream(statementTemplate, parameter); } finally { decorator.afterExecution(); } } /** * * @param statementTemplate * @param parameter * @param streamHandler */ public void queryForStream(Object statementTemplate, Object parameter, @SuppressWarnings("rawtypes") final StreamHandler streamHandler) { decorator.beforeExecution(statementTemplate, parameter, streamHandler); try { queryExecutor.queryForStream(statementTemplate, parameter, streamHandler); } finally { decorator.afterExecution(); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param clazz * @return */ @SuppressWarnings("unchecked") public <T> List<T> queryForList(Object statementTemplate, Object parameter, Class<T> clazz) { decorator.beforeExecution(statementTemplate, parameter, clazz); List<T> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(statementTemplate, parameter, clazz); list = (List<T>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForList(statementTemplate, parameter, clazz); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForList(statementTemplate, parameter, clazz); } return list; } finally { decorator.afterExecution(list); } } /** * * @param statementTemplate * @param parameter * @return */ @Deprecated public List<Object> queryForList(Object statementTemplate, Object parameter) { decorator.beforeExecution(statementTemplate, parameter); List<Object> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(statementTemplate, parameter); list = (List<Object>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForList(statementTemplate, parameter); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForList(statementTemplate, parameter); } return list; } finally { decorator.afterExecution(list); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param skipRows * @param maxRows * @param clazz * @return */ @SuppressWarnings("unchecked") public <T> List<T> queryForList(Object statementTemplate, Object parameter, final int skipRows, final int maxRows, Class<T> clazz) { decorator.beforeExecution(statementTemplate, parameter, skipRows, maxRows, clazz); List<T> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, skipRows, maxRows, clazz); list = (List<T>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForList(statementTemplate, parameter, skipRows, maxRows, clazz); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForList(statementTemplate, parameter, skipRows, maxRows, clazz); } return list; } finally { decorator.afterExecution(list); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param skipRows * @param maxRows * @return */ @SuppressWarnings("unchecked") @Deprecated public List<Object> queryForList(Object statementTemplate, Object parameter, final int skipRows, final int maxRows) { decorator.beforeExecution(statementTemplate, parameter, skipRows, maxRows); List<Object> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, skipRows, maxRows); list = (List<Object>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForList(statementTemplate, parameter, skipRows, maxRows); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForList(statementTemplate, parameter, skipRows, maxRows); } return list; } finally { decorator.afterExecution(list); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param rowMapper * @return */ @SuppressWarnings("unchecked") public <T> List<T> queryForList(Object statementTemplate, Object parameter, RowMapper<T> rowMapper){ decorator.beforeExecution(statementTemplate, parameter, rowMapper); List<T> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, rowMapper); list = (List<T>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForList(statementTemplate, parameter, rowMapper); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForList(statementTemplate, parameter, rowMapper); } return list; } finally { decorator.afterExecution(list); } } /** * * @param statementTemplate * @param parameter * @return */ public List<Map<String, Object>> queryForMapList(Object statementTemplate, Object parameter) { return queryForMapList(statementTemplate, parameter, usePropertyName); } /** * * @param statementTemplate * @param parameter * @param usePropertyName * @return */ @SuppressWarnings("unchecked") @Deprecated public List<Map<String, Object>> queryForMapList(Object statementTemplate, Object parameter, boolean usePropertyName) { decorator.beforeExecution(statementTemplate, parameter, usePropertyName); List<Map<String, Object>> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, usePropertyName); list = (List<Map<String, Object>>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForMapList(statementTemplate, parameter, usePropertyName); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForMapList(statementTemplate, parameter, usePropertyName); } return list; } finally { decorator.afterExecution(list); } } /** * * @param statementTemplate * @param parameter * @param skipRows * @param maxRows * @param usePropertyName * @return */ @SuppressWarnings("unchecked") public List<Map<String, Object>> queryForMapList(Object statementTemplate, Object parameter, final int skipRows, final int maxRows, boolean usePropertyName) { decorator.beforeExecution(statementTemplate, parameter, skipRows, maxRows, usePropertyName); List<Map<String, Object>> list = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, skipRows, maxRows, usePropertyName); list = (List<Map<String, Object>>) getCachedObject(cacheKey); if (list == null) { list = queryExecutor.queryForMapList(statementTemplate, parameter, skipRows, maxRows, usePropertyName); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, list)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { list = queryExecutor.queryForMapList(statementTemplate, parameter, skipRows, maxRows, usePropertyName); } return list; } finally { decorator.afterExecution(list); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param clazz * @return */ @SuppressWarnings("unchecked") public <T> T queryForObject(Object statementTemplate, Object parameter, Class<T> clazz) { decorator.beforeExecution(statementTemplate, parameter, clazz); T result = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, clazz); result = (T) getCachedObject(cacheKey); if (result == null) { result = queryExecutor.queryForObject(statementTemplate, parameter, clazz); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, result)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { result = queryExecutor.queryForObject(statementTemplate, parameter, clazz); } return result; } finally { decorator.afterExecution(result); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param rowMapper * @return */ public <T> T queryForObject(Object statementTemplate, Object parameter, RowMapper<T> rowMapper) { decorator.beforeExecution(statementTemplate, parameter); T result = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, rowMapper); result = (T) getCachedObject(cacheKey); if (result == null) { result = queryExecutor.queryForObject(statementTemplate, parameter, rowMapper); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, result)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { result = queryExecutor.queryForObject(statementTemplate, parameter, rowMapper); } return result; } finally { decorator.afterExecution(result); } } /** * * @param statementTemplate * @param parameter * @return */ @Deprecated public Object queryForObject(Object statementTemplate, Object parameter) { decorator.beforeExecution(statementTemplate, parameter); Object result = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter); result = getCachedObject(cacheKey); if (result == null) { result = queryExecutor.queryForObject(statementTemplate, parameter); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, result)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { result = queryExecutor.queryForObject(statementTemplate, parameter); } return result; } finally { decorator.afterExecution(result); } } /** * * @param statementTemplate * @param parameter * @return */ public Map<String, Object> queryForMap(Object statementTemplate, Object parameter) { return queryForMap(statementTemplate, parameter, usePropertyName); } /** * * @param statementTemplate * @param parameter * @param usePropertyName * @return */ @SuppressWarnings("unchecked") @Deprecated public Map<String, Object> queryForMap(Object statementTemplate, Object parameter, boolean usePropertyName) { decorator.beforeExecution(statementTemplate, parameter, usePropertyName); Map<String, Object> result = null; try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { Object cacheKey = generateKey(CommonVariableHolder.getCacheKey(), statementTemplate, parameter, usePropertyName); result = (Map<String, Object>) getCachedObject(cacheKey); if (result == null) { result = queryExecutor.queryForMap(statementTemplate, parameter, usePropertyName); cacheManager.getCache(defaultCacheName).put(new Element(cacheKey, result)); } addCacheKey(CommonVariableHolder.getCacheKey(), cacheKey); } else { result = queryExecutor.queryForMap(statementTemplate, parameter, usePropertyName); } return result; } finally { decorator.afterExecution(result); } } /** * * @param statementTemplate * @param parameter * @return */ public Integer queryForInt(Object statementTemplate, Object parameter){ decorator.beforeExecution(); try { return queryExecutor.queryForInt(statementTemplate, parameter); } finally { decorator.afterExecution(); } } /** * * @param statementTemplate * @param parameter * @return */ public Long queryForLong(Object statementTemplate, Object parameter){ decorator.beforeExecution(); try { return queryExecutor.queryForLong(statementTemplate, parameter); } finally { decorator.afterExecution(); } } /** * * @param statementTemplate * @param parameter * @return */ public Integer update(Object statementTemplate, Object parameter) { decorator.beforeExecution(); try { if(StringUtils.hasText(CommonVariableHolder.getCacheKey())) { removeCacheKey(CommonVariableHolder.getCacheKey()); } return queryExecutor.update(statementTemplate, parameter); } finally { decorator.afterExecution(); } } /** * * @param statementTemplate * @param parameters * @return */ public int[] batchUpdate(Object statementTemplate, Object[] parameters){ decorator.beforeExecution(); try { return queryExecutor.batchUpdate(statementTemplate, parameters); } finally { decorator.afterExecution(); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param action * @return * @throws DataAccessException */ @Deprecated public <T> T execute(Object statementTemplate, Object parameter, PreparedStatementCallback<T> action) throws DataAccessException { decorator.beforeExecution(); try { return queryExecutor.execute(statementTemplate, parameter, action); } finally { decorator.afterExecution(); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param clazz * @return */ @Deprecated public <T> T executeProcedure(Object statementTemplate,Object parameter, Class<T> clazz) { decorator.beforeExecution(); try { return queryExecutor.executeProcedure(null, null,statementTemplate.toString(), parameter, clazz); } finally { decorator.afterExecution(); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param clazz * @return */ public <T> T executeProcedure(String schema, String packageName, String procedureName,Object parameter, Class<T> clazz) { decorator.beforeExecution(); try { return queryExecutor.executeProcedure(schema, packageName,procedureName, parameter, clazz); } finally { decorator.afterExecution(); } } /** * * @param statementTemplate * @param parameter * @return */ @Deprecated public Map<String, Object> executeProcedure(Object statementTemplate, Object parameter) { decorator.beforeExecution(); try { return queryExecutor.executeProcedure(null, null,statementTemplate.toString(), parameter); } finally { decorator.afterExecution(); } } /** * * @param schema * @param packageName * @param procedureName * @param parameter * @return */ public Map<String, Object> executeProcedure(String schema, String packageName, String procedureName, Object parameter) { decorator.beforeExecution(); try { return queryExecutor.executeProcedure(schema, packageName,procedureName, parameter); } finally { decorator.afterExecution(); } } /** * * @param <T> * @param statementTemplate * @param parameter * @param clazz * @return */ @Deprecated public <T> T executeFunction(Object statementTemplate, Object parameter, Class<T> clazz) { decorator.beforeExecution(); try { return queryExecutor.executeFunction(null, null,statementTemplate.toString(), parameter, clazz); } finally { decorator.afterExecution(); } } /** * * @param schema * @param packageName * @param functionName * @param parameter * @param clazz * @return */ public <T> T executeFunction(String schema, String packageName, String functionName, Object parameter, Class<T> clazz) { decorator.beforeExecution(); try { return queryExecutor.executeFunction(schema, packageName,functionName, parameter, clazz); } finally { decorator.afterExecution(); } } /** * * @param schema * @param packageName * @param functionName * @param parameter * @return */ public Map<String, Object> executeFunction(String schema, String packageName, String functionName, Object parameter) { decorator.beforeExecution(); try { return queryExecutor.executeFunction(schema, packageName, functionName, parameter); } finally { decorator.afterExecution(); } } /** * * @param statementTemplate * @param parameter * @return */ @Deprecated public Map<String, Object> executeFunction(Object statementTemplate, Object parameter) { decorator.beforeExecution(); try { return queryExecutor.executeFunction(null, null, statementTemplate.toString(), parameter); } finally { decorator.afterExecution(); } } private Object getCachedObject(Object cacheKey) { Object cachedObject = null; if(cacheManager != null){ Element element = cacheManager.getCache(defaultCacheName).get(cacheKey); if (element != null) { if ((System.currentTimeMillis() - element.getCreationTime() > keepAliveTime) || System.currentTimeMillis() > element.getExpirationTime()) { cacheManager.getCache(defaultCacheName).remove(cacheKey); } else { cachedObject = element.getObjectValue(); if(logger.isDebugEnabled()){ logger.debug("Cache된 결과를 반환합니다. - CacheKey={}", cacheKey); } } } } return cachedObject; } public Object generateKey(Object... elements) { return cacheKeyGenerator.generateKey(elements); } private void addCacheKey(String baseKey, Object cacheKey){ List<Object> keys = cacheKeyHolder.get(baseKey); if(keys == null){ keys = new ArrayList<Object>(); cacheKeyHolder.put(baseKey, keys); } keys.add(cacheKey); } private void removeCacheKey(String baseKey) { List<Object> keys = cacheKeyHolder.get(baseKey); for(Object key : keys){ if(cacheManager.getCache(defaultCacheName).isKeyInCache(key)) { cacheManager.getCache(defaultCacheName).remove(key); } } cacheKeyHolder.remove(baseKey); } }
3e0fb121310e125352a481149110dcff5f23c5a9
756
java
Java
L15-msg/src/main/java/ru/otus/l15/db/DBService.java
IgorLevin/otus-java-2018-01-ilevin
8a784ccf7ba8f1bc62a16ec9da63414953f902f1
[ "MIT" ]
null
null
null
L15-msg/src/main/java/ru/otus/l15/db/DBService.java
IgorLevin/otus-java-2018-01-ilevin
8a784ccf7ba8f1bc62a16ec9da63414953f902f1
[ "MIT" ]
null
null
null
L15-msg/src/main/java/ru/otus/l15/db/DBService.java
IgorLevin/otus-java-2018-01-ilevin
8a784ccf7ba8f1bc62a16ec9da63414953f902f1
[ "MIT" ]
null
null
null
23.625
64
0.76455
6,667
package ru.otus.l15.db; import ru.otus.l15.dataset.UserDataSet; import ru.otus.l15.messageSystem.Addressee; import java.sql.SQLException; import java.util.List; public interface DBService extends AutoCloseable, Addressee { String getMetaData(); void prepareTables() throws SQLException; void addUsers(UserDataSet... users) throws SQLException; String getUserName(long id) throws SQLException; List<String> getAllNames() throws SQLException; void setUser(long id, UserDataSet user) throws SQLException; UserDataSet getUser(long id) throws SQLException; UserDataSet getUser(String name) throws SQLException; List<UserDataSet> getAllUsers() throws SQLException; void deleteTables() throws SQLException; }
3e0fb140e345ae9df1d9a12a089aee1392371587
659
java
Java
app/src/androidTest/java/husaynhakeem/io/popularmovies/network/MoviesUrlBuilderTest.java
Husaynhakeem/PopularMovies_MVP
8fdbf9e47e400fa6c32661233e82f741aea088c7
[ "Apache-2.0" ]
1
2019-02-08T07:31:20.000Z
2019-02-08T07:31:20.000Z
app/src/androidTest/java/husaynhakeem/io/popularmovies/network/MoviesUrlBuilderTest.java
apodaca1992/PopularMovies_MVP-master
e0753859fdffce6630cae76655b16d4c42c5acec
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/java/husaynhakeem/io/popularmovies/network/MoviesUrlBuilderTest.java
apodaca1992/PopularMovies_MVP-master
e0753859fdffce6630cae76655b16d4c42c5acec
[ "Apache-2.0" ]
null
null
null
25.346154
138
0.760243
6,668
package husaynhakeem.io.popularmovies.network; import android.content.Context; import android.support.test.InstrumentationRegistry; import org.junit.Assert; import org.junit.Test; /** * Created by husaynhakeem on 6/26/17. */ public class MoviesUrlBuilderTest { private static final String MOVIES_URL = "https://api.themoviedb.org/3/movie/popular?page=1&api_key=d9cfa9b786b4f434116f6bc47d8ddcff"; @Test public void built_movies_url_is_correct() { Context context = InstrumentationRegistry.getTargetContext(); Assert.assertEquals(MOVIES_URL, MoviesNetworkUtils.buildMoviesUrl(context, "popular", "1").toString()); } }
3e0fb1733c8b50529badd4a0f233046bd5476e99
1,267
java
Java
src/main/java/mods/railcraft/common/blocks/tracks/TrackElectricWye.java
DrParadox7/Railcraft
38efad6abd0370c0d0e69d2753d04dc31af6a02e
[ "FTL" ]
2
2022-01-04T20:45:19.000Z
2022-02-07T04:39:57.000Z
src/main/java/mods/railcraft/common/blocks/tracks/TrackElectricWye.java
DrParadox7/Railcraft
38efad6abd0370c0d0e69d2753d04dc31af6a02e
[ "FTL" ]
5
2021-11-13T20:33:42.000Z
2021-12-24T00:23:50.000Z
src/main/java/mods/railcraft/common/blocks/tracks/TrackElectricWye.java
DrParadox7/Railcraft
38efad6abd0370c0d0e69d2753d04dc31af6a02e
[ "FTL" ]
9
2021-11-07T18:32:14.000Z
2022-02-22T19:43:13.000Z
24.365385
105
0.696922
6,669
/* * Copyright (c) CovertJaguar, 2014 http://railcraft.info * * This code is the property of CovertJaguar * and may only be used with explicit written * permission unless otherwise specified on the * license page at http://railcraft.info/wiki/info:license. */ package mods.railcraft.common.blocks.tracks; import mods.railcraft.api.electricity.IElectricGrid; import net.minecraft.nbt.NBTTagCompound; public class TrackElectricWye extends TrackWye implements IElectricGrid { private final ChargeHandler chargeHandler = new ChargeHandler(this, ChargeHandler.ConnectType.TRACK); @Override public EnumTrack getTrackType() { return EnumTrack.ELECTRIC_WYE; } @Override public ChargeHandler getChargeHandler() { return chargeHandler; } @Override public boolean canUpdate() { return true; } @Override public void updateEntity() { super.updateEntity(); chargeHandler.tick(); } @Override public void writeToNBT(NBTTagCompound data) { super.writeToNBT(data); chargeHandler.writeToNBT(data); } @Override public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); chargeHandler.readFromNBT(data); } }
3e0fb23c34aae517f49d047cc4279f90b76de158
105
java
Java
Java_String_1/nTwice.java
kbbp/CodingBat
166efe313955e0a3ecfe832f89bb45ce28fec6aa
[ "MIT" ]
null
null
null
Java_String_1/nTwice.java
kbbp/CodingBat
166efe313955e0a3ecfe832f89bb45ce28fec6aa
[ "MIT" ]
null
null
null
Java_String_1/nTwice.java
kbbp/CodingBat
166efe313955e0a3ecfe832f89bb45ce28fec6aa
[ "MIT" ]
null
null
null
26.25
60
0.695238
6,670
public String nTwice(String str, int n) { return str.substring(0,n) + str.substring(str.length()-n); }
3e0fb2b8b24e8b3d1927fd134ddbcb786d3e6365
860
java
Java
Competitive Programming/problem_solving/PutSpaceBetweenCharacters.java
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
Competitive Programming/problem_solving/PutSpaceBetweenCharacters.java
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
Competitive Programming/problem_solving/PutSpaceBetweenCharacters.java
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
27.741935
85
0.688372
6,671
/* URL: https://www.geeksforgeeks.org/put-spaces-words-starting-capital-letters/ * */ package problem_solving; import java.util.Scanner; public class PutSpaceBetweenCharacters { /* recursive solution to the question. * */ private static void putSpaceBetweenChars(String characters, int idx) { if (characters == null || characters.length() == 0 || idx >= characters.length()) { return; } if (characters.charAt(idx) >= 65 && characters.charAt(idx) <= 90) { System.out.print(" " + (char)(characters.charAt(idx) + 32)); } else { System.out.print(characters.charAt(idx)); } putSpaceBetweenChars(characters, idx + 1); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the character string: "); String characters = sc.next(); putSpaceBetweenChars(characters, 0); } }
3e0fb5563dc27faf283d8ebe6783e42880c27600
6,066
java
Java
java/KinesisDeaggregatorV2/src/main/java/com/amazonaws/kinesis/deagg/RecordDeaggregator.java
airmonitor/kinesis-aggregation
398fbd4b430d4bf590431b301d03cbbc94279cef
[ "Apache-2.0" ]
349
2016-05-02T19:59:19.000Z
2022-03-27T18:58:14.000Z
java/KinesisDeaggregatorV2/src/main/java/com/amazonaws/kinesis/deagg/RecordDeaggregator.java
airmonitor/kinesis-aggregation
398fbd4b430d4bf590431b301d03cbbc94279cef
[ "Apache-2.0" ]
90
2016-08-16T16:57:17.000Z
2022-03-21T11:50:40.000Z
java/KinesisDeaggregatorV2/src/main/java/com/amazonaws/kinesis/deagg/RecordDeaggregator.java
airmonitor/kinesis-aggregation
398fbd4b430d4bf590431b301d03cbbc94279cef
[ "Apache-2.0" ]
178
2016-05-03T20:04:20.000Z
2022-01-26T13:29:46.000Z
37.677019
108
0.75849
6,672
/** * Kinesis Aggregation/Deaggregation Libraries for Java * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.kinesis.deagg; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; import com.amazonaws.services.lambda.runtime.events.KinesisEvent.KinesisEventRecord; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.kinesis.retrieval.AggregatorUtil; import software.amazon.kinesis.retrieval.KinesisClientRecord; /** * A Kinesis deaggregator convenience class. This class contains a number of * static methods that provide different interfaces for deaggregating user * records from an existing aggregated Kinesis record. This class is oriented * towards deaggregating Kinesis records as provided by AWS Lambda, or through * the Kinesis SDK. Parameterise the instance with the required types * (supporting * com.amazonaws.services.lambda.runtime.events.KinesisEvent.KinesisEventRecord * or com.amazonaws.services.kinesis.model.Record only) * * NOTE: Any non-aggregated records passed to any deaggregation methods will be * returned unchanged. * */ public class RecordDeaggregator<T> { /** * Interface used by a calling method to call the process function * */ public interface KinesisUserRecordProcessor { public Void process(List<KinesisClientRecord> userRecords); } private Record convertOne(KinesisEventRecord record) { KinesisEvent.Record r = record.getKinesis(); Record out = Record.builder().partitionKey(r.getPartitionKey()).encryptionType(r.getEncryptionType()) .approximateArrivalTimestamp(r.getApproximateArrivalTimestamp().toInstant()) .sequenceNumber(r.getSequenceNumber()).data(SdkBytes.fromByteBuffer(r.getData())).build(); return out; } private List<KinesisClientRecord> convertToKinesis(List<KinesisEventRecord> inputRecords) { List<KinesisClientRecord> response = new ArrayList<>(); inputRecords.stream().forEachOrdered(record -> { response.add(KinesisClientRecord.fromRecord(convertOne(record))); }); return response; } @SuppressWarnings("unchecked") private List<KinesisClientRecord> convertType(List<T> inputRecords) throws Exception { List<KinesisClientRecord> records = null; if (inputRecords.size() > 0 && inputRecords.get(0) instanceof KinesisEventRecord) { records = convertToKinesis((List<KinesisEventRecord>) inputRecords); } else if (inputRecords.size() > 0 && inputRecords.get(0) instanceof Record) { records = new ArrayList<>(); for (Record rec : (List<Record>) inputRecords) { records.add(KinesisClientRecord.fromRecord((Record) rec)); } } else { if (inputRecords.size() == 0) { return new ArrayList<KinesisClientRecord>(); } else { throw new Exception("Input Types must be Kinesis Event or Model Records"); } } return records; } /** * Method to process a set of Kinesis user records from a Stream of Kinesis * Event Records using the Java 8 Streams API * * @param inputStream The Kinesis Records provided by AWS Lambda or the * Kinesis SDK * @param streamConsumer Instance implementing the Consumer interface to process * the deaggregated UserRecords * @return Void */ public Void stream(Stream<T> inputStream, Consumer<KinesisClientRecord> streamConsumer) throws Exception { // deaggregate UserRecords from the Kinesis Records List<T> streamList = inputStream.collect(Collectors.toList()); List<KinesisClientRecord> deaggregatedRecords = new AggregatorUtil().deaggregate(convertType(streamList)); deaggregatedRecords.stream().forEachOrdered(streamConsumer); return null; } /** * Method to process a set of Kinesis user records from a list of Kinesis * Records using pre-Streams style API * * @param inputRecords The Kinesis Records provided by AWS Lambda * @param processor Instance implementing KinesisUserRecordProcessor * @return Void */ public Void processRecords(List<T> inputRecords, KinesisUserRecordProcessor processor) throws Exception { // invoke provided processor return processor.process(new AggregatorUtil().deaggregate(convertType(inputRecords))); } /** * Method to bulk deaggregate a set of Kinesis user records from a list of * Kinesis Event Records. * * @param inputRecords The Kinesis Records provided by AWS Lambda * @return A list of Kinesis UserRecord objects obtained by deaggregating the * input list of KinesisEventRecords */ public List<KinesisClientRecord> deaggregate(List<T> inputRecords) throws Exception { List<KinesisClientRecord> outputRecords = new LinkedList<>(); outputRecords.addAll(new AggregatorUtil().deaggregate(convertType(inputRecords))); return outputRecords; } /** * Method to deaggregate a single Kinesis record into a List of UserRecords * * @param inputRecord The Kinesis Record provided by AWS Lambda or Kinesis SDK * @return A list of Kinesis UserRecord objects obtained by deaggregating the * input list of KinesisEventRecords */ public List<KinesisClientRecord> deaggregate(T inputRecord) throws Exception { return new AggregatorUtil().deaggregate(convertType(Arrays.asList(inputRecord))); } }
3e0fb569ce708707e38561a02d790da7e0bb844e
926
java
Java
xsl_erp_pojo/src/main/java/xsl/erp/pojo/XslOriented.java
tjutBountyHunter/cms
f0278d5acf9f4a6cd1ed813d7a8dc24023c9106b
[ "Apache-2.0" ]
1
2019-07-01T03:47:59.000Z
2019-07-01T03:47:59.000Z
xsl_erp_pojo/src/main/java/xsl/erp/pojo/XslOriented.java
tjutBountyHunter/cms
f0278d5acf9f4a6cd1ed813d7a8dc24023c9106b
[ "Apache-2.0" ]
4
2019-11-13T09:43:48.000Z
2020-06-30T22:34:00.000Z
xsl_erp_pojo/src/main/java/xsl/erp/pojo/XslOriented.java
tjutBountyHunter/cms
f0278d5acf9f4a6cd1ed813d7a8dc24023c9106b
[ "Apache-2.0" ]
null
null
null
21.534884
78
0.639309
6,673
package xsl.erp.pojo; public class XslOriented { private Integer id; private String orientedId; private String orientedName; private String orientedInfo; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOrientedId() { return orientedId; } public void setOrientedId(String orientedId) { this.orientedId = orientedId == null ? null : orientedId.trim(); } public String getOrientedName() { return orientedName; } public void setOrientedName(String orientedName) { this.orientedName = orientedName == null ? null : orientedName.trim(); } public String getOrientedInfo() { return orientedInfo; } public void setOrientedInfo(String orientedInfo) { this.orientedInfo = orientedInfo == null ? null : orientedInfo.trim(); } }
3e0fb5957f086a69153ba5e344c5024c7cce70e3
2,681
java
Java
src/org/usfirst/frc/team2832/robot/commands/auton/autongroups/ScaleDualCube.java
FRC2832/Robot_2018
4d99bd86ca765578e1d61d0d35e0a773623a77fd
[ "BSD-3-Clause" ]
5
2018-01-13T01:12:10.000Z
2018-03-26T00:11:08.000Z
src/org/usfirst/frc/team2832/robot/commands/auton/autongroups/ScaleDualCube.java
FRC2832/Robot_2018
4d99bd86ca765578e1d61d0d35e0a773623a77fd
[ "BSD-3-Clause" ]
5
2018-01-13T23:01:46.000Z
2018-04-03T17:53:09.000Z
src/org/usfirst/frc/team2832/robot/commands/auton/autongroups/ScaleDualCube.java
FRC2832/Robot_2018
4d99bd86ca765578e1d61d0d35e0a773623a77fd
[ "BSD-3-Clause" ]
1
2018-02-03T00:31:15.000Z
2018-02-03T00:31:15.000Z
36.22973
78
0.692279
6,674
package org.usfirst.frc.team2832.robot.commands.auton.autongroups; import org.usfirst.frc.team2832.robot.Dashboard; import org.usfirst.frc.team2832.robot.Dashboard.SIDE; import org.usfirst.frc.team2832.robot.commands.LowerIngestor; import org.usfirst.frc.team2832.robot.commands.auton.drivetrain.DriveDistance; import org.usfirst.frc.team2832.robot.commands.auton.drivetrain.TurnPID; import org.usfirst.frc.team2832.robot.commands.auton.lift.ExpelCube; import org.usfirst.frc.team2832.robot.commands.auton.lift.MoveLiftTime; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.command.CommandGroup; import edu.wpi.first.wpilibj.command.TimedCommand; /** * */ public class ScaleDualCube extends CommandGroup { //Right SIDE public ScaleDualCube(SIDE side) { String gameData = DriverStation.getInstance().getGameSpecificMessage(); if (side == Dashboard.SIDE.LEFTSIDE) { if (gameData.charAt(1) == 'L') { addParallel(new MoveLiftTime(2.7, 1, 1.5)); addSequential(new DriveDistance(.8f, -280d, 8d)); addParallel(new LowerIngestor(.1)); addSequential(new TurnPID(50f, 1.5)); addSequential(new ExpelCube(.7, 0.8)); addSequential(new TurnPID(80, 1.5)); addParallel(new MoveLiftTime(2.5, -1)); addParallel(new LowerIngestor(.7)); addSequential(new DriveDistance(.7, -40, 3)); //TODO: Set this distance addSequential(new TurnPID(40, 1.5)); addParallel(new ExpelCube(-1, 2.0)); addSequential(new DriveDistance(.6, -40, 2)); //TODO: Set this distance addParallel(new MoveLiftTime(2.7, 1)); addSequential(new TurnPID(165, 2.0)); addSequential(new DriveDistance(.7, -40, 3)); //TODO: Set this distance addSequential(new ExpelCube(0.6)); } } if (side == Dashboard.SIDE.RIGHTSIDE) { if (gameData.charAt(1) == 'R') { addParallel(new MoveLiftTime(2.7, 1, 1.5)); addSequential(new DriveDistance(.8f, -230d, 8d)); addParallel(new LowerIngestor(.1)); addSequential(new TurnPID(-50f, 1.5)); addSequential(new ExpelCube(.7, 0.8)); addSequential(new TurnPID(-80, 1.5)); addParallel(new MoveLiftTime(2.7, -1)); addSequential(new DriveDistance(.7, -40, 3)); //TODO: Set this distance addParallel(new LowerIngestor(.7)); addSequential(new TurnPID(-40, 1.5)); addParallel(new ExpelCube(-1, 2.0)); addSequential(new DriveDistance(.6, -40, 2)); //TODO: Set this distance addParallel(new MoveLiftTime(2.7, 1)); addSequential(new TurnPID(-165, 2.0)); addSequential(new DriveDistance(.7, -40, 3)); //TODO: Set this distance addSequential(new ExpelCube(0.6)); } } } }
3e0fb666405ab023695e5dbfce93ac09cfb1fa6a
87
java
Java
src/main/java/org/aksw/mlbenchmark/package-info.java
AKSW/STILE
278dbeab8224776bc97f77b71002f2eefe659589
[ "Apache-2.0" ]
14
2017-09-20T23:26:30.000Z
2020-04-24T09:42:32.000Z
src/main/java/org/aksw/mlbenchmark/package-info.java
AKSW/DL-Learning-Benchmark
278dbeab8224776bc97f77b71002f2eefe659589
[ "Apache-2.0" ]
12
2016-03-16T11:08:33.000Z
2017-03-06T17:31:01.000Z
src/main/java/org/aksw/mlbenchmark/package-info.java
AKSW/DL-Learning-Benchmark
278dbeab8224776bc97f77b71002f2eefe659589
[ "Apache-2.0" ]
3
2016-04-29T13:40:23.000Z
2016-11-01T12:39:12.000Z
14.5
29
0.678161
6,675
/** * The base package * @author Lorenz Buehmann * */ package org.aksw.mlbenchmark;
3e0fb673f70e04fa4d81ae28343a3580566ba11a
2,318
java
Java
src/main/java/com/acidmanic/cicdassistant/wiki/convert/anchorsources/GitLabCommitHashAnchorSource.java
Acidmanic/pactbroker-server
39de285d69beae9867e1e9b873065566f8065937
[ "MIT" ]
null
null
null
src/main/java/com/acidmanic/cicdassistant/wiki/convert/anchorsources/GitLabCommitHashAnchorSource.java
Acidmanic/pactbroker-server
39de285d69beae9867e1e9b873065566f8065937
[ "MIT" ]
null
null
null
src/main/java/com/acidmanic/cicdassistant/wiki/convert/anchorsources/GitLabCommitHashAnchorSource.java
Acidmanic/pactbroker-server
39de285d69beae9867e1e9b873065566f8065937
[ "MIT" ]
null
null
null
28.975
84
0.70233
6,676
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.acidmanic.cicdassistant.wiki.convert.anchorsources; import com.acidmanic.cicdassistant.repositoryinfo.gitlab.GitlabCommit; import com.acidmanic.cicdassistant.repositoryinfo.gitlab.GitlabConfiguration; import com.acidmanic.cicdassistant.repositoryinfo.gitlab.GitlabInterface; import com.acidmanic.cicdassistant.utility.CommonRegExes; import com.acidmanic.cicdassistant.utility.StringUtils; import com.acidmanic.cicdassistant.wiki.convert.autolink.Anchor; import com.acidmanic.lightweight.logger.SilentLogger; import com.acidmanic.repositoryinfo.Commit; /** * * @author diego */ public class GitLabCommitHashAnchorSource extends RegexStringExtractorAnchorSource { private final KeyNormalizingDataFetchAnchorCache cache; private final GitlabConfiguration configurations; public GitLabCommitHashAnchorSource(GitlabConfiguration configurations) { this.cache = new KeyNormalizingDataFetchAnchorCache( hash -> fetchHashAsAnchor(hash), hash -> normalizeHash(hash), "gitlab-hashes-cache", new SilentLogger()); this.configurations = configurations; } @Override protected Anchor createAnchor(String hash) { return cache.get(hash); } private Anchor fetchHashAsAnchor(String hash) { GitlabInterface ginterface = new GitlabInterface(); ginterface.setConfigurations(configurations); Commit commit = ginterface.getSingleCommit(hash); if (commit != null) { GitlabCommit gitlabCommit = (GitlabCommit) commit; Anchor anchor = new Anchor(); anchor.setHref(gitlabCommit.getWebUrl()); anchor.setText(gitlabCommit.getShortId()); anchor.setTitle(gitlabCommit.getTitle()); return anchor; } return null; } private static String normalizeHash(String hash) { if (StringUtils.isNullOrEmpty(hash)) { return ""; } return hash.toLowerCase(); } @Override protected String getRegEx() { return CommonRegExes.SHA1_REGEX; } }
3e0fb675b4bde1dec203b3bd38de5e47b9a01de8
17,707
java
Java
killrvideo-service-videocatalog/src/test/java/com/killrvideo/service/video/grpc/VideoCatalogServiceGrpcTest.java
jeffersonsong/killrvideo-java
0974c0be9f4c5e6d521809bcd6c3b0f695938c5f
[ "Apache-2.0" ]
null
null
null
killrvideo-service-videocatalog/src/test/java/com/killrvideo/service/video/grpc/VideoCatalogServiceGrpcTest.java
jeffersonsong/killrvideo-java
0974c0be9f4c5e6d521809bcd6c3b0f695938c5f
[ "Apache-2.0" ]
null
null
null
killrvideo-service-videocatalog/src/test/java/com/killrvideo/service/video/grpc/VideoCatalogServiceGrpcTest.java
jeffersonsong/killrvideo-java
0974c0be9f4c5e6d521809bcd6c3b0f695938c5f
[ "Apache-2.0" ]
null
null
null
43.187805
111
0.719489
6,677
package com.killrvideo.service.video.grpc; import com.killrvideo.dse.dto.ResultListPage; import com.killrvideo.dse.dto.Video; import com.killrvideo.messaging.dao.MessagingDao; import com.killrvideo.service.video.dto.LatestVideosPage; import com.killrvideo.service.video.dto.UserVideo; import com.killrvideo.service.video.request.GetLatestVideoPreviewsRequestData; import com.killrvideo.service.video.request.GetUserVideoPreviewsRequestData; import com.killrvideo.service.video.repository.VideoCatalogRepository; import com.killrvideo.utils.GrpcMappingUtils; import io.grpc.stub.StreamObserver; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.*; import killrvideo.video_catalog.events.VideoCatalogEvents; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static com.killrvideo.utils.GrpcMappingUtils.uuidToUuid; import static java.util.Collections.singletonList; import static org.mockito.Mockito.*; @SuppressWarnings("unchecked") class VideoCatalogServiceGrpcTest { @InjectMocks private VideoCatalogServiceGrpc service; @Mock private MessagingDao messagingDao; @Mock private VideoCatalogRepository videoCatalogRepository; @Mock private VideoCatalogServiceGrpcValidator validator; @Mock private VideoCatalogServiceGrpcMapper mapper; private AutoCloseable closeable; @BeforeEach public void openMocks() { closeable = MockitoAnnotations.openMocks(this); } @AfterEach public void releaseMocks() throws Exception { closeable.close(); } @Test public void testSubmitYouTubeVideoWithValidationFailure() { SubmitYouTubeVideoRequest grpcReq = SubmitYouTubeVideoRequest.getDefaultInstance(); StreamObserver<SubmitYouTubeVideoResponse > grpcResObserver = mock(StreamObserver.class); doThrow(new IllegalArgumentException()).when(this.validator) .validateGrpcRequest_submitYoutubeVideo(any(), any()); Assertions.assertThrows(IllegalArgumentException.class, () -> service.submitYouTubeVideo(grpcReq, grpcResObserver) ); } @Test public void testSubmitYouTubeVideoWithInsertFailure() { SubmitYouTubeVideoRequest grpcReq = SubmitYouTubeVideoRequest.getDefaultInstance(); StreamObserver<SubmitYouTubeVideoResponse > grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_submitYoutubeVideo(any(), any()); Video video = mock(Video.class); when(this.mapper.mapSubmitYouTubeVideoRequestAsVideo(any())).thenReturn(video); when(this.videoCatalogRepository.insertVideoAsync(any())).thenReturn( CompletableFuture.failedFuture(new Exception()) ); service.submitYouTubeVideo(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test public void testSubmitYouTubeVideoWithSendFailure() { SubmitYouTubeVideoRequest grpcReq = SubmitYouTubeVideoRequest.getDefaultInstance(); StreamObserver<SubmitYouTubeVideoResponse > grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_submitYoutubeVideo(any(), any()); Video video = mock(Video.class); when(this.mapper.mapSubmitYouTubeVideoRequestAsVideo(any())).thenReturn(video); when(this.videoCatalogRepository.insertVideoAsync(any())).thenReturn( CompletableFuture.completedFuture(null) ); VideoCatalogEvents.YouTubeVideoAdded event = VideoCatalogEvents.YouTubeVideoAdded.getDefaultInstance(); when(this.mapper.createYouTubeVideoAddedEvent(any())).thenReturn(event); when(this.messagingDao.sendEvent(any(), any())).thenReturn( CompletableFuture.failedFuture(new Exception()) ); service.submitYouTubeVideo(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test public void testSubmitYouTubeVideo() { SubmitYouTubeVideoRequest grpcReq = SubmitYouTubeVideoRequest.getDefaultInstance(); StreamObserver<SubmitYouTubeVideoResponse > grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_submitYoutubeVideo(any(), any()); Video video = mock(Video.class); when(this.mapper.mapSubmitYouTubeVideoRequestAsVideo(any())).thenReturn(video); when(this.videoCatalogRepository.insertVideoAsync(any())).thenReturn( CompletableFuture.completedFuture(null) ); VideoCatalogEvents.YouTubeVideoAdded event = VideoCatalogEvents.YouTubeVideoAdded.getDefaultInstance(); when(this.mapper.createYouTubeVideoAddedEvent(any())).thenReturn(event); when(this.messagingDao.sendEvent(any(), any())).thenReturn( CompletableFuture.completedFuture(null) ); service.submitYouTubeVideo(grpcReq, grpcResObserver); verify(grpcResObserver, times(0)).onError(any()); verify(grpcResObserver, times(1)).onNext(any()); verify(grpcResObserver, times(1)).onCompleted(); } @Test void testGetLatestVideoPreviewsWithValidationFailure() { GetLatestVideoPreviewsRequest grpcReq = GetLatestVideoPreviewsRequest.getDefaultInstance(); StreamObserver<GetLatestVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doThrow(new IllegalArgumentException()).when(this.validator) .validateGrpcRequest_getLatestPreviews(any(), any()); Assertions.assertThrows(IllegalArgumentException.class, () -> service.getLatestVideoPreviews(grpcReq, grpcResObserver) ); } @Test void testGetLatestVideoPreviewsWithQueryFailure() { GetLatestVideoPreviewsRequest grpcReq = GetLatestVideoPreviewsRequest.getDefaultInstance(); StreamObserver<GetLatestVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getLatestPreviews(any(), any()); GetLatestVideoPreviewsRequestData requestData = mock(GetLatestVideoPreviewsRequestData.class); when(this.mapper.parseGetLatestVideoPreviewsRequest(any(), any())).thenReturn(requestData); when(videoCatalogRepository.getLatestVideoPreviewsAsync(any())).thenReturn( CompletableFuture.failedFuture(new RuntimeException()) ); service.getLatestVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test void testGetLatestVideoPreviews() { GetLatestVideoPreviewsRequest grpcReq = GetLatestVideoPreviewsRequest.getDefaultInstance(); StreamObserver<GetLatestVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getLatestPreviews(any(), any()); GetLatestVideoPreviewsRequestData requestData = mock(GetLatestVideoPreviewsRequestData.class); when(this.mapper.parseGetLatestVideoPreviewsRequest(any(), any())).thenReturn(requestData); LatestVideosPage returnedPage = mock(LatestVideosPage.class); when(videoCatalogRepository.getLatestVideoPreviewsAsync(any())).thenReturn( CompletableFuture.completedFuture(returnedPage) ); GetLatestVideoPreviewsResponse response = GetLatestVideoPreviewsResponse.getDefaultInstance(); when(this.mapper.mapLatestVideoToGrpcResponse(any())).thenReturn(response); service.getLatestVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(0)).onError(any()); verify(grpcResObserver, times(1)).onNext(any()); verify(grpcResObserver, times(1)).onCompleted(); } @Test void testGetVideoWithValidationFailure() { GetVideoRequest grpcReq = GetVideoRequest.getDefaultInstance(); StreamObserver<GetVideoResponse> grpcResObserver = mock(StreamObserver.class); doThrow(new IllegalArgumentException()).when(this.validator) .validateGrpcRequest_getVideo(any(), any()); Assertions.assertThrows(IllegalArgumentException.class, () -> service.getVideo(grpcReq, grpcResObserver) ); } @Test void testGetVideoWithQueryFailure() { GetVideoRequest grpcReq = getVideoRequest(UUID.randomUUID()); StreamObserver<GetVideoResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getVideo(any(), any()); when(videoCatalogRepository.getVideoById(any())).thenReturn( CompletableFuture.failedFuture(new Exception()) ); service.getVideo(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test void testGetVideoWithNoVideoFound() { GetVideoRequest grpcReq = getVideoRequest(UUID.randomUUID()); StreamObserver<GetVideoResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getVideo(any(), any()); when(videoCatalogRepository.getVideoById(any())).thenReturn( CompletableFuture.completedFuture(null) ); service.getVideo(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test void testGetVideo() { GetVideoRequest grpcReq = getVideoRequest(UUID.randomUUID()); StreamObserver<GetVideoResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getVideo(any(), any()); Video video = mock(Video.class); when(videoCatalogRepository.getVideoById(any())).thenReturn( CompletableFuture.completedFuture(video) ); GetVideoResponse response = GetVideoResponse.getDefaultInstance(); when(this.mapper.mapFromVideotoVideoResponse(any())).thenReturn(response); service.getVideo(grpcReq, grpcResObserver); verify(grpcResObserver, times(0)).onError(any()); verify(grpcResObserver, times(1)).onNext(any()); verify(grpcResObserver, times(1)).onCompleted(); } @Test void testGetVideoPreviewsWithValidationFailure() { GetVideoPreviewsRequest grpcReq = GetVideoPreviewsRequest.getDefaultInstance(); StreamObserver<GetVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doThrow(new IllegalArgumentException()).when(this.validator) .validateGrpcRequest_getVideoPreviews(any(), any()); Assertions.assertThrows(IllegalArgumentException.class, () -> service.getVideoPreviews(grpcReq, grpcResObserver) ); } @Test void testGetVideoPreviewsWithoutVideioId() { GetVideoPreviewsRequest grpcReq = getVideoPreviewsRequest(); StreamObserver<GetVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getVideoPreviews(any(), any()); service.getVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(0)).onError(any()); verify(grpcResObserver, times(1)).onNext(any()); verify(grpcResObserver, times(1)).onCompleted(); } @Test void testGetVideoPreviewsWithQueryFailure() { UUID videoid = UUID.randomUUID(); GetVideoPreviewsRequest grpcReq = getVideoPreviewsRequest(videoid); StreamObserver<GetVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getVideoPreviews(any(), any()); when(this.videoCatalogRepository.getVideoPreview(any())).thenReturn( CompletableFuture.failedFuture(new Exception()) ); service.getVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test void testGetVideoPreviews() { UUID videoid = UUID.randomUUID(); GetVideoPreviewsRequest grpcReq = getVideoPreviewsRequest(videoid); StreamObserver<GetVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getVideoPreviews(any(), any()); Video video = mock(Video.class); List<Video> videos = singletonList(video); when(this.videoCatalogRepository.getVideoPreview(any())).thenReturn( CompletableFuture.completedFuture(videos) ); GetVideoPreviewsResponse response = GetVideoPreviewsResponse.getDefaultInstance(); when(this.mapper.mapToGetVideoPreviewsResponse(any())).thenReturn(response); service.getVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(0)).onError(any()); verify(grpcResObserver, times(1)).onNext(any()); verify(grpcResObserver, times(1)).onCompleted(); } @Test void testGetUserVideoPreviewsWithValidationFailure() { GetUserVideoPreviewsRequest grpcReq = GetUserVideoPreviewsRequest.getDefaultInstance(); StreamObserver<GetUserVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doThrow(new IllegalArgumentException()).when(this.validator) .validateGrpcRequest_getUserVideoPreviews(any(), any()); Assertions.assertThrows(IllegalArgumentException.class, () -> service.getUserVideoPreviews(grpcReq, grpcResObserver) ); } @Test void testGetUserVideoPreviewsWithQueryFailure() { UUID userid = UUID.randomUUID(); GetUserVideoPreviewsRequest grpcReq = getUserVideoPreviewsRequest(userid); StreamObserver<GetUserVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getUserVideoPreviews(any(), any()); GetUserVideoPreviewsRequestData requestData = getUserVideoPreviewsRequestData(userid); when(this.mapper.parseGetUserVideoPreviewsRequest(grpcReq)).thenReturn(requestData); when(this.videoCatalogRepository.getUserVideosPreview(any())).thenReturn( CompletableFuture.failedFuture(new Exception()) ); service.getUserVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(1)).onError(any()); verify(grpcResObserver, times(0)).onNext(any()); verify(grpcResObserver, times(0)).onCompleted(); } @Test void testGetUserVideoPreviews() { UUID userid = UUID.randomUUID(); GetUserVideoPreviewsRequest grpcReq = getUserVideoPreviewsRequest(userid); StreamObserver<GetUserVideoPreviewsResponse> grpcResObserver = mock(StreamObserver.class); doNothing().when(this.validator).validateGrpcRequest_getUserVideoPreviews(any(), any()); GetUserVideoPreviewsRequestData requestData = getUserVideoPreviewsRequestData(userid); when(this.mapper.parseGetUserVideoPreviewsRequest(grpcReq)).thenReturn(requestData); ResultListPage<UserVideo> resultListPage = mock(ResultListPage.class); when(this.videoCatalogRepository.getUserVideosPreview(any())).thenReturn( CompletableFuture.completedFuture(resultListPage) ); GetUserVideoPreviewsResponse response = GetUserVideoPreviewsResponse.getDefaultInstance(); when(this.mapper.mapToGetUserVideoPreviewsResponse(any(), any())).thenReturn(response); service.getUserVideoPreviews(grpcReq, grpcResObserver); verify(grpcResObserver, times(0)).onError(any()); verify(grpcResObserver, times(1)).onNext(any()); verify(grpcResObserver, times(1)).onCompleted(); } private GetVideoRequest getVideoRequest(UUID videoid) { return GetVideoRequest.newBuilder() .setVideoId(uuidToUuid(videoid)) .build(); } private GetVideoPreviewsRequest getVideoPreviewsRequest(UUID... videoIds) { return GetVideoPreviewsRequest.newBuilder() .addAllVideoIds( Arrays.stream(videoIds).map(GrpcMappingUtils::uuidToUuid).collect(Collectors.toList()) ) .build(); } private GetUserVideoPreviewsRequest getUserVideoPreviewsRequest(UUID userid) { return GetUserVideoPreviewsRequest.newBuilder() .setUserId(uuidToUuid(userid)) .build(); } private GetUserVideoPreviewsRequestData getUserVideoPreviewsRequestData(UUID userid) { return new GetUserVideoPreviewsRequestData(userid); } }
3e0fb6ee15ea1a0c2f4a94dc6dddf739787ba17a
308
java
Java
src/org/sda/block/image/RangeSet.java
dmix75/android_image_extraction
a61f47c7000fd4d2a1c4a9eb29c00b97a1e05a5f
[ "Apache-2.0" ]
null
null
null
src/org/sda/block/image/RangeSet.java
dmix75/android_image_extraction
a61f47c7000fd4d2a1c4a9eb29c00b97a1e05a5f
[ "Apache-2.0" ]
null
null
null
src/org/sda/block/image/RangeSet.java
dmix75/android_image_extraction
a61f47c7000fd4d2a1c4a9eb29c00b97a1e05a5f
[ "Apache-2.0" ]
null
null
null
16.210526
45
0.678571
6,678
package org.sda.block.image; public class RangeSet { private int[] rangeSet; private int count; public RangeSet(int count, int[] rangeSet) { super(); this.rangeSet = rangeSet; this.count = count; } public int[] getRangeSet() { return rangeSet; } public int getCount() { return count; } }
3e0fb75115dc3a49c5981afc3172b385fb52e5d0
169
java
Java
hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/miracle/PrintsOn.java
xiayingfeng/hexa.tools
604c804901b1bb13fe10b3823cc4a639f8993363
[ "MIT" ]
48
2015-04-01T10:31:08.000Z
2022-02-08T11:18:18.000Z
hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/miracle/PrintsOn.java
xiayingfeng/hexa.tools
604c804901b1bb13fe10b3823cc4a639f8993363
[ "MIT" ]
11
2015-05-18T07:33:52.000Z
2017-03-22T17:05:37.000Z
hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/miracle/PrintsOn.java
xiayingfeng/hexa.tools
604c804901b1bb13fe10b3823cc4a639f8993363
[ "MIT" ]
15
2015-04-09T09:19:29.000Z
2022-02-08T02:08:19.000Z
21.125
48
0.751479
6,679
package fr.lteconsulting.hexa.client.ui.miracle; public interface PrintsOn<T> { // return false to say printer can be reused void print( T data, Printer printer ); }
3e0fb798045ec725043157be2be7b919de4b3b63
2,892
java
Java
go-lisa/src/main/java/it/unive/golisa/cfg/runtime/strings/GoHasPrefix.java
UniVE-SSV/go-lisa
7a13975195210e80cd2e893f4e3555b97ae28d07
[ "MIT" ]
3
2021-06-20T09:25:22.000Z
2021-09-20T10:10:58.000Z
go-lisa/src/main/java/it/unive/golisa/cfg/runtime/strings/GoHasPrefix.java
UniVE-SSV/go-lisa
7a13975195210e80cd2e893f4e3555b97ae28d07
[ "MIT" ]
16
2021-04-25T11:10:26.000Z
2021-11-02T07:57:04.000Z
go-lisa/src/main/java/it/unive/golisa/cfg/runtime/strings/GoHasPrefix.java
UniVE-SSV/go-lisa
7a13975195210e80cd2e893f4e3555b97ae28d07
[ "MIT" ]
null
null
null
41.314286
103
0.780775
6,680
package it.unive.golisa.cfg.runtime.strings; import it.unive.golisa.cfg.type.GoBoolType; import it.unive.golisa.cfg.type.GoStringType; import it.unive.lisa.analysis.AbstractState; import it.unive.lisa.analysis.AnalysisState; import it.unive.lisa.analysis.SemanticException; import it.unive.lisa.analysis.heap.HeapDomain; import it.unive.lisa.analysis.value.ValueDomain; import it.unive.lisa.caches.Caches; import it.unive.lisa.interprocedural.InterproceduralAnalysis; import it.unive.lisa.program.CompilationUnit; import it.unive.lisa.program.cfg.CFG; import it.unive.lisa.program.cfg.CFGDescriptor; import it.unive.lisa.program.cfg.CodeLocation; import it.unive.lisa.program.cfg.NativeCFG; import it.unive.lisa.program.cfg.Parameter; import it.unive.lisa.program.cfg.statement.Expression; import it.unive.lisa.program.cfg.statement.PluggableStatement; import it.unive.lisa.program.cfg.statement.Statement; import it.unive.lisa.program.cfg.statement.call.BinaryNativeCall; import it.unive.lisa.symbolic.SymbolicExpression; import it.unive.lisa.symbolic.value.BinaryExpression; import it.unive.lisa.symbolic.value.BinaryOperator; public class GoHasPrefix extends NativeCFG { public GoHasPrefix(CodeLocation location, CompilationUnit stringUnit) { super(new CFGDescriptor(location, stringUnit, false, "HasPrefix", GoBoolType.INSTANCE, new Parameter(location, "this", GoStringType.INSTANCE), new Parameter(location, "other", GoStringType.INSTANCE)), HasPrefix.class); } public static class HasPrefix extends BinaryNativeCall implements PluggableStatement { private Statement original; @Override public void setOriginatingStatement(Statement st) { original = st; } public static HasPrefix build(CFG cfg, CodeLocation location, Expression... params) { return new HasPrefix(cfg, location, params[0], params[1]); } public HasPrefix(CFG cfg, CodeLocation location, Expression left, Expression right) { super(cfg, location, "HasPrefix", GoBoolType.INSTANCE, left, right); } @Override protected <A extends AbstractState<A, H, V>, H extends HeapDomain<H>, V extends ValueDomain<V>> AnalysisState<A, H, V> binarySemantics(AnalysisState<A, H, V> entryState, InterproceduralAnalysis<A, H, V> interprocedural, AnalysisState<A, H, V> leftState, SymbolicExpression leftExp, AnalysisState<A, H, V> rightState, SymbolicExpression rightExp) throws SemanticException { if (!leftExp.getDynamicType().isStringType() && !leftExp.getDynamicType().isUntyped()) return entryState.bottom(); if (!rightExp.getDynamicType().isStringType() && !rightExp.getDynamicType().isUntyped()) return entryState.bottom(); return rightState .smallStepSemantics(new BinaryExpression(Caches.types().mkSingletonSet(GoBoolType.INSTANCE), leftExp, rightExp, BinaryOperator.STRING_STARTS_WITH, getLocation()), original); } } }
3e0fb7dbce4cdcf0e2b7a83f72e72fcb1a5397cf
1,770
java
Java
springfox-boot-starter/src/main/java/springfox/boot/starter/autoconfigure/OpenApiAutoConfiguration.java
sigand/springfox
cbb17fb8a4ef0c37f287cdfb9bed79260aa634bf
[ "Apache-2.0" ]
5,703
2015-03-24T16:01:38.000Z
2022-03-30T14:20:12.000Z
springfox-boot-starter/src/main/java/springfox/boot/starter/autoconfigure/OpenApiAutoConfiguration.java
sigand/springfox
cbb17fb8a4ef0c37f287cdfb9bed79260aa634bf
[ "Apache-2.0" ]
3,445
2015-03-24T05:11:02.000Z
2022-03-31T09:55:29.000Z
springfox-boot-starter/src/main/java/springfox/boot/starter/autoconfigure/OpenApiAutoConfiguration.java
sigand/springfox
cbb17fb8a4ef0c37f287cdfb9bed79260aa634bf
[ "Apache-2.0" ]
1,689
2015-03-24T03:37:02.000Z
2022-03-31T09:05:39.000Z
53.636364
110
0.877401
6,681
package springfox.boot.starter.autoconfigure; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration; import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; import springfox.documentation.oas.configuration.OpenApiDocumentationConfiguration; import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration; import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration; @Configuration @EnableConfigurationProperties(SpringfoxConfigurationProperties.class) @ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true) @Import({ OpenApiDocumentationConfiguration.class, SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class, Swagger2DocumentationConfiguration.class, SwaggerUiWebFluxConfiguration.class, SwaggerUiWebMvcConfiguration.class }) @AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) public class OpenApiAutoConfiguration { }
3e0fb86e5b5ef5994ec9fbc6d43d64ff24a3dc08
2,167
java
Java
rookit-web-crawler/rookit-observer-api/src/main/java/org/rookit/crawler/RequestDispatcherImpl.java
JPDSousa/rookit
37805fd0b58aed89cec912c03bddc4eacfcf8bae
[ "MIT" ]
null
null
null
rookit-web-crawler/rookit-observer-api/src/main/java/org/rookit/crawler/RequestDispatcherImpl.java
JPDSousa/rookit
37805fd0b58aed89cec912c03bddc4eacfcf8bae
[ "MIT" ]
1
2017-12-29T09:59:55.000Z
2018-01-06T19:08:47.000Z
rookit-web-crawler/rookit-observer-api/src/main/java/org/rookit/crawler/RequestDispatcherImpl.java
JPDSousa/rookit
37805fd0b58aed89cec912c03bddc4eacfcf8bae
[ "MIT" ]
1
2022-03-03T13:33:48.000Z
2022-03-03T13:33:48.000Z
38.017544
80
0.663129
6,682
/******************************************************************************* * Copyright (C) 2018 Joao Sousa * * 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.rookit.crawler; import com.google.common.base.MoreObjects; import com.google.common.util.concurrent.RateLimiter; import com.wrapper.spotify.methods.Request; import java.io.IOException; final class RequestDispatcherImpl implements RequestDispatcher { private static final Validator VALIDATOR = ; private final RateLimiter limiter; RequestDispatcherImpl(final RateLimiter limiter) { this.limiter = limiter; } @Override public <T> T exec(final Request<T> request) { try { this.limiter.acquire(); return request.exec(); } catch (final IOException e) { VALIDATOR.handleException().inputOutputException(e); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("limiter", this.limiter) .toString(); } }
3e0fb8ccd2d6ced51dcaa428a749964e80c91c37
3,463
java
Java
common/protocol/src/main/java/org/sdo/iotplatformsdk/common/protocol/security/Signatures.java
sharoncornelius/iot-platform-sdk
acd2bca6c274c54f4ed558c98a3c73aa65ab6cc3
[ "Apache-2.0" ]
6
2020-03-06T16:26:03.000Z
2020-12-17T08:21:32.000Z
common/protocol/src/main/java/org/sdo/iotplatformsdk/common/protocol/security/Signatures.java
sharoncornelius/iot-platform-sdk
acd2bca6c274c54f4ed558c98a3c73aa65ab6cc3
[ "Apache-2.0" ]
9
2020-02-20T16:59:38.000Z
2021-12-16T04:36:13.000Z
common/protocol/src/main/java/org/sdo/iotplatformsdk/common/protocol/security/Signatures.java
sharoncornelius/iot-platform-sdk
acd2bca6c274c54f4ed558c98a3c73aa65ab6cc3
[ "Apache-2.0" ]
21
2020-03-02T05:16:29.000Z
2021-06-10T04:10:55.000Z
33.95098
96
0.72827
6,683
// Copyright 2020 Intel Corporation // SPDX-License-Identifier: Apache 2.0 package org.sdo.iotplatformsdk.common.protocol.security; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.security.spec.AlgorithmParameterSpec; import org.sdo.iotplatformsdk.common.protocol.types.EpidKey; public abstract class Signatures { private static final String ECDSA = "ECDSA"; private static final String RSA = "RSA"; private static final String SHA = "SHA"; private static final String WITH = "with"; /** * Convert from a {@link java.security.Key}'s algorithm string to the * {@link java.security.Signature} algorithm string which should be matched to that key. */ public static Signature getInstance(Key key) throws NoSuchAlgorithmException { if (key instanceof RSAKey) { return getInstance((RSAKey) key); } else if (key instanceof ECKey) { return getInstance((ECKey) key); } else if (key instanceof EpidKey) { return getInstance((EpidKey) key); } else { throw new UnsupportedOperationException(key.getAlgorithm() + "is not supported"); } } private static Signature getInstance(RSAKey key) throws NoSuchAlgorithmException { int bytes = key.getModulus().bitLength() / Byte.SIZE; String name = SHA + bytes + WITH + RSA; return Signature.getInstance(name); } private static Signature getInstance(ECKey key) throws NoSuchAlgorithmException { int bytes = key.getParams().getCurve().getField().getFieldSize(); String name = SHA + bytes + WITH + ECDSA; return Signature.getInstance(name); } private static Signature getInstance(EpidKey key) throws NoSuchAlgorithmException { return Signature.getInstance(key.getAlgorithm()); } /** * Verifies a signed block of data. * * @param data The data 'message' which has been signed. * @param signature The signature. * @param verificationKey The public key to use for verification. * @return True if the signature verifies successfully. */ public static boolean verifySignature(final byte[] data, final byte[] signature, final PublicKey verificationKey) { return verifySignature(data, signature, verificationKey, null); } /** * Verifies a signed block of data. * * @param data The data 'message' which has been signed. * @param signature The signature. * @param verificationKey The public key to use for verification. * @param params The algorithm parameters, or null if not needed. * @return True if the signature verifies successfully. */ public static boolean verifySignature(final byte[] data, final byte[] signature, final PublicKey verificationKey, final AlgorithmParameterSpec params) { try { Signature verifier = getInstance(verificationKey); verifier.initVerify(verificationKey); if (null != params) { verifier.setParameter(params); } verifier.update(data); return verifier.verify(signature); } catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | SignatureException e) { throw new RuntimeException(e); } } }
3e0fba42592b9a42d2f95ce8168e02ed12447ce2
798
java
Java
staf-interpreter/src/main/java/com/sparkit/staf/core/visitors/KeywordBodyVisitor.java
Virmak/staf
94306a68eded76959bc106d921c448cf3046b236
[ "MIT" ]
2
2020-05-14T06:58:06.000Z
2020-05-26T16:24:58.000Z
staf-interpreter/src/main/java/com/sparkit/staf/core/visitors/KeywordBodyVisitor.java
Virmak/staf
94306a68eded76959bc106d921c448cf3046b236
[ "MIT" ]
6
2020-06-24T13:53:29.000Z
2022-02-27T04:47:06.000Z
staf-interpreter/src/main/java/com/sparkit/staf/core/visitors/KeywordBodyVisitor.java
Virmak/staf
94306a68eded76959bc106d921c448cf3046b236
[ "MIT" ]
null
null
null
34.695652
83
0.763158
6,684
package com.sparkit.staf.core.visitors; import com.sparkit.staf.core.parser.StafBaseVisitor; import com.sparkit.staf.core.parser.StafParser; import com.sparkit.staf.core.ast.IStatement; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; public class KeywordBodyVisitor extends StafBaseVisitor<List<IStatement>> { @Autowired private StatementVisitor statementVisitor; @Override public List<IStatement> visitKeyword_body(StafParser.Keyword_bodyContext ctx) { List<IStatement> statements = new ArrayList<>(); for (StafParser.StatementContext statementContext: ctx.statement()) { statements.add(statementVisitor.visitStatement(statementContext)); } return statements; } }
3e0fba739682e83c0b1997b4708356ebfaf57393
1,009
java
Java
core/api/src/test/java/org/onosproject/net/intent/MockIdGenerator.java
LenkayHuang/Onos-PNC-for-PCEP
bd7d201aba89a713f5ba6ffb473aacff85e4d38c
[ "Apache-2.0" ]
1
2017-07-30T06:10:57.000Z
2017-07-30T06:10:57.000Z
core/api/src/test/java/org/onosproject/net/intent/MockIdGenerator.java
LenkayHuang/Onos-PNC-for-PCEP
bd7d201aba89a713f5ba6ffb473aacff85e4d38c
[ "Apache-2.0" ]
null
null
null
core/api/src/test/java/org/onosproject/net/intent/MockIdGenerator.java
LenkayHuang/Onos-PNC-for-PCEP
bd7d201aba89a713f5ba6ffb473aacff85e4d38c
[ "Apache-2.0" ]
null
null
null
30.575758
76
0.713578
6,685
/* * Copyright 2014 Open Networking Laboratory * * 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.onosproject.net.intent; import org.onosproject.core.IdGenerator; import java.util.concurrent.atomic.AtomicLong; /** * Mock id generator for testing. */ public class MockIdGenerator implements IdGenerator { private AtomicLong nextId = new AtomicLong(0); @Override public long getNewId() { return nextId.getAndIncrement(); } }
3e0fbafb09d350ad4aed3a39c254aa8e0209ff0b
906
java
Java
src/main/java/com/lothrazar/cyclic/item/craftingsimple/CraftingStickContainerProvider.java
henkelmax/Cyclic
b2cb467e780cd0e8535c3f9ac312c7fa55bf0846
[ "MIT" ]
37
2016-07-12T15:50:35.000Z
2018-11-29T15:52:20.000Z
src/main/java/com/lothrazar/cyclic/item/craftingsimple/CraftingStickContainerProvider.java
henkelmax/Cyclic
b2cb467e780cd0e8535c3f9ac312c7fa55bf0846
[ "MIT" ]
725
2016-06-28T03:00:34.000Z
2018-12-09T23:12:13.000Z
src/main/java/com/lothrazar/cyclic/item/craftingsimple/CraftingStickContainerProvider.java
henkelmax/Cyclic
b2cb467e780cd0e8535c3f9ac312c7fa55bf0846
[ "MIT" ]
50
2016-11-03T01:30:23.000Z
2018-11-29T15:52:24.000Z
31.241379
92
0.811258
6,686
package com.lothrazar.cyclic.item.craftingsimple; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.InteractionHand; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; public class CraftingStickContainerProvider implements MenuProvider { private InteractionHand hand; public CraftingStickContainerProvider(InteractionHand handIn) { this.hand = handIn; } @Override public Component getDisplayName() { return new TranslatableComponent("item.cyclic.crafting_stick"); } @Override public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player player) { return new CraftingStickContainer(i, playerInventory, player, hand); } }
3e0fbbd0e98064ee9d67e6a78174c83927134004
2,607
java
Java
finalExamPrep/extra/P04HornetArmadav2.java
1vaPetkova/programmingFundamentalsJava
ada7ac4eaee2eb2b6e85cdbb37377506e1347fac
[ "MIT" ]
null
null
null
finalExamPrep/extra/P04HornetArmadav2.java
1vaPetkova/programmingFundamentalsJava
ada7ac4eaee2eb2b6e85cdbb37377506e1347fac
[ "MIT" ]
null
null
null
finalExamPrep/extra/P04HornetArmadav2.java
1vaPetkova/programmingFundamentalsJava
ada7ac4eaee2eb2b6e85cdbb37377506e1347fac
[ "MIT" ]
null
null
null
42.048387
113
0.522823
6,687
package finalExamPrep.extra; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class P04HornetArmadav2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int lines = Integer.parseInt(scan.nextLine()); //legionName - lastActivity Map<String, Long> activities = new LinkedHashMap<>(); //legionName - soldier Type - soldier count Map<String, Map<String, Long>> soldiers = new LinkedHashMap<>(); Pattern regex = Pattern.compile("([0-9]+) = ([^=\\-\\>: ]+) -> ([^=\\-\\>: ]+):([0-9]+)"); while (lines-- > 0) { Matcher m = regex.matcher(scan.nextLine()); String legionName = ""; String soldierType = ""; long lastActivity = 0; long soldierCount = 0L; while (m.find()) { lastActivity = Integer.parseInt(m.group(1)); legionName = m.group(2); soldierType = m.group(3); soldierCount = Long.parseLong(m.group(4)); } activities.putIfAbsent(legionName, 0L); activities.put(legionName, Math.max(lastActivity, activities.get(legionName))); soldiers.putIfAbsent(legionName, new LinkedHashMap<>()); soldiers.get(legionName).putIfAbsent(soldierType, 0L); soldiers.get(legionName) .put(soldierType, soldiers.get(legionName).get(soldierType) + soldierCount); } String[] input = scan.nextLine().split("\\\\"); if (input.length > 1) { long activity = Long.parseLong(input[0]); String soldierType = input[1]; soldiers.entrySet().stream().filter(l -> l.getValue().containsKey(soldierType)) .sorted((a, b) -> Long.compare(b.getValue().get(soldierType), a.getValue().get(soldierType))) .forEach(l -> { if (activities.get(l.getKey()) < activity) { System.out.printf("%s -> %d\n", l.getKey(), l.getValue().get(soldierType)); } }); } else { String soldierType = input[0]; activities.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .forEach(a -> { if (soldiers.get(a.getKey()).containsKey(soldierType)) { System.out.println(a.getValue() + " : " + a.getKey()); } }); } } }
3e0fbc4a9ee7bbca059eefc234fcb919830f306b
1,872
java
Java
infrastructure/src/main/java/org/corfudb/infrastructure/NodeHealth.java
NunoEdgarGFlowHub/CorfuDB
2aaa2ef95913fa3afa4c896869aec91ff3bed5dd
[ "Apache-2.0" ]
null
null
null
infrastructure/src/main/java/org/corfudb/infrastructure/NodeHealth.java
NunoEdgarGFlowHub/CorfuDB
2aaa2ef95913fa3afa4c896869aec91ff3bed5dd
[ "Apache-2.0" ]
null
null
null
infrastructure/src/main/java/org/corfudb/infrastructure/NodeHealth.java
NunoEdgarGFlowHub/CorfuDB
2aaa2ef95913fa3afa4c896869aec91ff3bed5dd
[ "Apache-2.0" ]
null
null
null
27.130435
77
0.668269
6,688
package org.corfudb.infrastructure; import lombok.Data; import org.corfudb.format.Types.NodeMetrics; /** * NodeHealth: * Contains the health status of the state of a node. * This state is utilized by the management server to * make decisions on the state of the cluster and handle * failures if needed. * <p> * Created by zlokhandwala on 1/13/17. */ @Data public class NodeHealth { private final String endpoint; private final NodeMetrics nodeMetrics; private final Long networkLatency; private final Double pollSuccessRate; private NodeHealth(NodeHealthBuilder nodeHealthBuilder) { this.endpoint = nodeHealthBuilder.endpoint; this.nodeMetrics = nodeHealthBuilder.nodeMetrics; this.networkLatency = nodeHealthBuilder.networkLatency; this.pollSuccessRate = nodeHealthBuilder.pollSuccessRate; } /** * Builder for the NodeHealth */ public static class NodeHealthBuilder { private String endpoint; private NodeMetrics nodeMetrics; private Long networkLatency; private Double pollSuccessRate; public NodeHealthBuilder() { } public NodeHealthBuilder setEndpoint(String endpoint) { this.endpoint = endpoint; return this; } public NodeHealthBuilder setNodeMetrics(NodeMetrics nodeMetrics) { this.nodeMetrics = nodeMetrics; return this; } public NodeHealthBuilder setNetworkLatency(Long networkLatency) { this.networkLatency = networkLatency; return this; } public NodeHealthBuilder setPollSuccessRate(Double pollSuccessRate) { this.pollSuccessRate = pollSuccessRate; return this; } public NodeHealth build() { return new NodeHealth(this); } } }
3e0fbc75953fde1ea81f30d435c5f11e08320442
852
java
Java
persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/BaseEntity.java
eas5/tutorials
4b460a9e25f6f0b0292e98144add0ce631a9e05e
[ "MIT" ]
32,544
2015-01-02T16:59:22.000Z
2022-03-31T21:04:05.000Z
persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/BaseEntity.java
eas5/tutorials
4b460a9e25f6f0b0292e98144add0ce631a9e05e
[ "MIT" ]
1,577
2015-02-21T17:47:03.000Z
2022-03-31T14:25:58.000Z
persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/BaseEntity.java
eas5/tutorials
4b460a9e25f6f0b0292e98144add0ce631a9e05e
[ "MIT" ]
55,853
2015-01-01T07:52:09.000Z
2022-03-31T21:08:15.000Z
22.421053
62
0.676056
6,689
package com.baeldung.hibernate.types; import com.vladmihalcea.hibernate.type.json.JsonBinaryType; import com.vladmihalcea.hibernate.type.json.JsonStringType; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import javax.persistence.*; @TypeDefs({ @TypeDef(name = "json", typeClass = JsonStringType.class), @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) }) @MappedSuperclass public class BaseEntity { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "id", unique = true, nullable = false) long id; String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3e0fbd3711c5e132b5ba4b6dca37cc61cceb5d5b
3,148
java
Java
network/resource-manager/v2018_12_01/src/main/java/com/microsoft/azure/management/network/v2018_12_01/implementation/SubnetsImpl.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
3
2021-09-15T16:25:19.000Z
2021-12-17T05:41:00.000Z
network/resource-manager/v2018_12_01/src/main/java/com/microsoft/azure/management/network/v2018_12_01/implementation/SubnetsImpl.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
306
2019-09-27T06:41:56.000Z
2019-10-14T08:19:57.000Z
network/resource-manager/v2018_12_01/src/main/java/com/microsoft/azure/management/network/v2018_12_01/implementation/SubnetsImpl.java
minaltolpadi/azure-sdk-for-java
a6bb33fc71f21ee92d4246d6b5fe30ad8a5689cb
[ "MIT" ]
1
2019-10-05T04:59:12.000Z
2019-10-05T04:59:12.000Z
35.370787
195
0.704257
6,690
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * */ package com.microsoft.azure.management.network.v2018_12_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.network.v2018_12_01.Subnets; import rx.Completable; import rx.Observable; import rx.functions.Func1; import com.microsoft.azure.Page; import com.microsoft.azure.management.network.v2018_12_01.PrepareNetworkPoliciesRequest; import com.microsoft.azure.management.network.v2018_12_01.Subnet; class SubnetsImpl extends WrapperImpl<SubnetsInner> implements Subnets { private final NetworkManager manager; SubnetsImpl(NetworkManager manager) { super(manager.inner().subnets()); this.manager = manager; } public NetworkManager manager() { return this.manager; } @Override public SubnetImpl define(String name) { return wrapModel(name); } private SubnetImpl wrapModel(SubnetInner inner) { return new SubnetImpl(inner, manager()); } private SubnetImpl wrapModel(String name) { return new SubnetImpl(name, this.manager()); } @Override public Completable prepareNetworkPoliciesAsync(String resourceGroupName, String virtualNetworkName, String subnetName, PrepareNetworkPoliciesRequest prepareNetworkPoliciesRequestParameters) { SubnetsInner client = this.inner(); return client.prepareNetworkPoliciesAsync(resourceGroupName, virtualNetworkName, subnetName, prepareNetworkPoliciesRequestParameters).toCompletable(); } @Override public Observable<Subnet> listAsync(final String resourceGroupName, final String virtualNetworkName) { SubnetsInner client = this.inner(); return client.listAsync(resourceGroupName, virtualNetworkName) .flatMapIterable(new Func1<Page<SubnetInner>, Iterable<SubnetInner>>() { @Override public Iterable<SubnetInner> call(Page<SubnetInner> page) { return page.items(); } }) .map(new Func1<SubnetInner, Subnet>() { @Override public Subnet call(SubnetInner inner) { return wrapModel(inner); } }); } @Override public Observable<Subnet> getAsync(String resourceGroupName, String virtualNetworkName, String subnetName) { SubnetsInner client = this.inner(); return client.getAsync(resourceGroupName, virtualNetworkName, subnetName) .map(new Func1<SubnetInner, Subnet>() { @Override public Subnet call(SubnetInner inner) { return wrapModel(inner); } }); } @Override public Completable deleteAsync(String resourceGroupName, String virtualNetworkName, String subnetName) { SubnetsInner client = this.inner(); return client.deleteAsync(resourceGroupName, virtualNetworkName, subnetName).toCompletable(); } }
3e0fbdbb45183d8a60a89929881a0919af59f3df
86
java
Java
src/main/java/se/ltu/studentgruppvt19/bibliotekssystemet/AdminController.java
weleoka/bibliotekssystemet
a1c65d7fc52cd1ea8a32b12e3e3f5da76439a8ed
[ "MIT" ]
null
null
null
src/main/java/se/ltu/studentgruppvt19/bibliotekssystemet/AdminController.java
weleoka/bibliotekssystemet
a1c65d7fc52cd1ea8a32b12e3e3f5da76439a8ed
[ "MIT" ]
null
null
null
src/main/java/se/ltu/studentgruppvt19/bibliotekssystemet/AdminController.java
weleoka/bibliotekssystemet
a1c65d7fc52cd1ea8a32b12e3e3f5da76439a8ed
[ "MIT" ]
null
null
null
17.2
51
0.837209
6,691
package se.ltu.studentgruppvt19.bibliotekssystemet; public class AdminController { }
3e0fbe870377df620dcfe7974b229ae2d0307e94
5,664
java
Java
src/test/java/com/alibaba/druid/sql/oracle/demo/Demo1.java
haimli/druid
97ed996c05380cc817a4d527ebe7d5f79e9d11ec
[ "Apache-2.0" ]
25
2016-06-19T09:26:05.000Z
2021-08-10T13:11:40.000Z
src/test/java/com/alibaba/druid/sql/oracle/demo/Demo1.java
haimli/druid
97ed996c05380cc817a4d527ebe7d5f79e9d11ec
[ "Apache-2.0" ]
null
null
null
src/test/java/com/alibaba/druid/sql/oracle/demo/Demo1.java
haimli/druid
97ed996c05380cc817a4d527ebe7d5f79e9d11ec
[ "Apache-2.0" ]
16
2015-09-06T04:12:22.000Z
2019-12-12T06:33:22.000Z
34.748466
104
0.618114
6,692
/* * Copyright 1999-2017 Alibaba Group Holding 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 com.alibaba.druid.sql.oracle.demo; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr; import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr; import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr; import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr; import com.alibaba.druid.sql.ast.statement.SQLExprTableSource; import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleSelectTableReference; import com.alibaba.druid.sql.dialect.oracle.parser.OracleStatementParser; import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitorAdapter; import com.alibaba.druid.sql.parser.SQLStatementParser; public class Demo1 extends TestCase { public void test_0() throws Exception { String sql = "select * from user where uid = ? and uname = ?"; List<Object> parameters = new ArrayList<Object>(); parameters.add(1); parameters.add("wenshao"); SQLStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); // SQLStatement first = (SQLStatement) stmtList.get(0); GetVariantVisitor variantVisitor = new GetVariantVisitor(); first.accept(variantVisitor); SQLVariantRefExpr firstVar = variantVisitor.getVariantList().get(0); int varIndex = (Integer) firstVar.getAttribute("varIndex"); Integer param = (Integer) parameters.get(varIndex); String tableName; if (param.intValue() == 1) { tableName = "user_1"; } else { tableName = "user_x"; } MyOracleVisitor visitor = new MyOracleVisitor(tableName); first.accept(visitor); String realSql = SQLUtils.toOracleString(first); System.out.println(realSql); } private static class GetVariantVisitor extends OracleASTVisitorAdapter { private int varIndex = 0; private List<SQLVariantRefExpr> variantList = new ArrayList<SQLVariantRefExpr>(); public boolean visit(SQLVariantRefExpr x) { x.getAttributes().put("varIndex", varIndex++); return true; } public boolean visit(SQLBinaryOpExpr x) { if (x.getLeft() instanceof SQLIdentifierExpr && x.getRight() instanceof SQLVariantRefExpr) { SQLIdentifierExpr identExpr = (SQLIdentifierExpr) x.getLeft(); String ident = identExpr.getName(); if (ident.equals("uid")) { variantList.add((SQLVariantRefExpr) x.getRight()); } } return true; } public int getVarIndex() { return varIndex; } public void setVarIndex(int varIndex) { this.varIndex = varIndex; } public List<SQLVariantRefExpr> getVariantList() { return variantList; } public void setVariantList(List<SQLVariantRefExpr> variantList) { this.variantList = variantList; } } private static class MyOracleVisitor extends OracleASTVisitorAdapter { private String tableName; public MyOracleVisitor(String tableName){ this.tableName = tableName; } public boolean visit(OracleSelectTableReference x) { SQLExpr expr = x.getExpr(); if (expr instanceof SQLIdentifierExpr) { SQLIdentifierExpr identExpr = (SQLIdentifierExpr) expr; String tableName = identExpr.getName(); if (tableName.equals("user")) { identExpr.setName(this.tableName); } } else if (expr instanceof SQLPropertyExpr) { SQLPropertyExpr proExpr = (SQLPropertyExpr) expr; String tableName = proExpr.getName(); if (tableName.equals("user")) { proExpr.setName(this.tableName); } } return true; } public boolean visit(SQLExprTableSource x) { SQLExpr expr = x.getExpr(); if (expr instanceof SQLIdentifierExpr) { SQLIdentifierExpr identExpr = (SQLIdentifierExpr) expr; String tableName = identExpr.getName(); if (tableName.equals("user")) { identExpr.setName(this.tableName); } } else if (expr instanceof SQLPropertyExpr) { SQLPropertyExpr proExpr = (SQLPropertyExpr) expr; String tableName = proExpr.getName(); if (tableName.equals("user")) { proExpr.setName(this.tableName); } } return true; } } }
3e0fbf0a95f26c0ee29e5a8ad70ad3bfaf6b6965
1,103
java
Java
src/test/java/socialite/storage/JsonSerializableCommandHistoryTest.java
david-eom/tp
f573ab7e4583cd70414d1d8f7ad517cb850bcfdf
[ "MIT" ]
null
null
null
src/test/java/socialite/storage/JsonSerializableCommandHistoryTest.java
david-eom/tp
f573ab7e4583cd70414d1d8f7ad517cb850bcfdf
[ "MIT" ]
141
2021-09-16T02:05:32.000Z
2021-11-11T02:01:53.000Z
src/test/java/socialite/storage/JsonSerializableCommandHistoryTest.java
david-eom/tp
f573ab7e4583cd70414d1d8f7ad517cb850bcfdf
[ "MIT" ]
7
2021-09-10T09:33:30.000Z
2021-09-27T08:03:38.000Z
40.851852
120
0.798731
6,693
package socialite.storage; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import socialite.commons.util.JsonUtil; import socialite.model.CommandHistory; import socialite.testutil.TypicalCommandHistory; public class JsonSerializableCommandHistoryTest { private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonSerializableCommandHistoryTest"); private static final Path TYPICAL_COMMAND_HISTORY_FILE = TEST_DATA_FOLDER.resolve("typicalCommandHistory.json"); @Test public void toModelType_commandHistoryFile_success() throws Exception { JsonSerializableCommandHistory dataFromFile = JsonUtil.readJsonFile(TYPICAL_COMMAND_HISTORY_FILE, JsonSerializableCommandHistory.class).get(); CommandHistory commandHistoryFromFile = dataFromFile.toModelType(); CommandHistory typicalCommandHistory = TypicalCommandHistory.getTypicalCommandHistory(); assertEquals(commandHistoryFromFile, typicalCommandHistory); } }
3e0fbf80172859085943c7d016f6a62c9d4d5e30
2,942
java
Java
spring-cloud-gcp-data-spanner/src/test/java/org/springframework/cloud/gcp/data/spanner/core/admin/SpannerSchemaUtilsTests.java
hashimati/spring-cloud-gcp
652de88b833ab7f31cc9c608c96e4532a21b8ddd
[ "Apache-2.0" ]
1
2018-06-27T08:59:54.000Z
2018-06-27T08:59:54.000Z
spring-cloud-gcp-data-spanner/src/test/java/org/springframework/cloud/gcp/data/spanner/core/admin/SpannerSchemaUtilsTests.java
hashimati/spring-cloud-gcp
652de88b833ab7f31cc9c608c96e4532a21b8ddd
[ "Apache-2.0" ]
null
null
null
spring-cloud-gcp-data-spanner/src/test/java/org/springframework/cloud/gcp/data/spanner/core/admin/SpannerSchemaUtilsTests.java
hashimati/spring-cloud-gcp
652de88b833ab7f31cc9c608c96e4532a21b8ddd
[ "Apache-2.0" ]
null
null
null
29.42
87
0.75051
6,694
/* * Copyright 2018 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.cloud.gcp.data.spanner.core.admin; import java.util.List; import com.google.cloud.ByteArray; import com.google.cloud.spanner.Key; import org.junit.Before; import org.junit.Test; import org.springframework.cloud.gcp.data.spanner.core.convert.MappingSpannerConverter; import org.springframework.cloud.gcp.data.spanner.core.mapping.Column; import org.springframework.cloud.gcp.data.spanner.core.mapping.ColumnLength; import org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey; import org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerMappingContext; import org.springframework.cloud.gcp.data.spanner.core.mapping.Table; import static org.junit.Assert.assertEquals; /** * @author Chengyuan Zhao */ public class SpannerSchemaUtilsTests { private SpannerMappingContext spannerMappingContext; private SpannerSchemaUtils spannerSchemaUtils; @Before public void setUp() { this.spannerMappingContext = new SpannerMappingContext(); this.spannerSchemaUtils = new SpannerSchemaUtils(this.spannerMappingContext, new MappingSpannerConverter(this.spannerMappingContext)); } @Test public void getDropDDLTest() { assertEquals("DROP TABLE custom_test_table", this.spannerSchemaUtils.getDropTableDDLString(TestEntity.class)); } @Test public void getCreateDDLTest() { assertEquals("CREATE TABLE custom_test_table ( id STRING(MAX) , id2 INT64 " + ", custom_col STRING(MAX) , other STRING(333) , bytes BYTES(MAX) " + ", bytesList ARRAY<BYTES(111)> , integerList ARRAY<INT64> " + ", doubles ARRAY<FLOAT64> ) PRIMARY KEY ( id , id2 )", this.spannerSchemaUtils.getCreateTableDDLString(TestEntity.class)); } @Test public void getIdTest() { TestEntity t = new TestEntity(); t.id = "aaa"; t.id2 = 3L; assertEquals(Key.newBuilder().append(t.id).append(t.id2).build(), this.spannerSchemaUtils.getKey(t)); } @Table(name = "custom_test_table") private static class TestEntity { @PrimaryKey(keyOrder = 1) String id; @PrimaryKey(keyOrder = 2) long id2; @Column(name = "custom_col") String something; @ColumnLength(maxLength = 333) @Column(name = "") String other; ByteArray bytes; @ColumnLength(maxLength = 111) List<ByteArray> bytesList; List<Integer> integerList; double[] doubles; } }
3e0fc04ef2afa1d26247497b12509be87fa5a34a
8,315
java
Java
code-builder/src/main/java/com/ychp/code/builder/Builder.java
ychp/coding
45773e26752d731e14963f49fd9a427f047698c3
[ "Apache-2.0" ]
null
null
null
code-builder/src/main/java/com/ychp/code/builder/Builder.java
ychp/coding
45773e26752d731e14963f49fd9a427f047698c3
[ "Apache-2.0" ]
null
null
null
code-builder/src/main/java/com/ychp/code/builder/Builder.java
ychp/coding
45773e26752d731e14963f49fd9a427f047698c3
[ "Apache-2.0" ]
null
null
null
36.951111
327
0.57746
6,695
package com.ychp.code.builder; import com.github.jknack.handlebars.Handlebars; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.util.Map; import static com.ychp.code.builder.utils.BuilderUtils.*; /** * Desc: * Author: <a href="kenaa@example.com">应程鹏</a> * Date: 17/2/9 */ public abstract class Builder { public void build(String ... args){ Map<String, String> argsMap = getArgsMap(args); BufferedReader paramReader = null; try { paramReader = getParamReader(argsMap.get(PARAM_PATH_KEY)); Map<String, Object> paramMap = getParams(paramReader); String templatePath = paramMap.get(TEMPLATE_PATH_KEY) != null ? (String)paramMap.get(TEMPLATE_PATH_KEY) : null; String[] templates = getTemplatePath(templatePath); String[] fileSuff = getFileSuff(paramMap.get(FILE_SUFF_KEY)); if(fileSuff.length > templates.length){ throw new RuntimeException("file suff cannot more than template"); } String content; String outPath = paramMap.get(OUT_PATH_KEY) != null ? (String)paramMap.get(OUT_PATH_KEY) : getDefaultOutPath(paramMap); String fullOutPath = outPath.endsWith("/") ? outPath + (StringUtils.isEmpty((String)paramMap.get(FILE_NAME_KEY)) ? DEFAULT_OUT_FILE_NAME : (String)paramMap.get(FILE_NAME_KEY)) : outPath + "/" + (StringUtils.isEmpty((String)paramMap.get(FILE_NAME_KEY)) ? DEFAULT_OUT_FILE_NAME : (String)paramMap.get(FILE_NAME_KEY)); Map<String, Object> templateParamMap = generalTemplateParamMap(paramMap); for(int i = 0; i < templates.length; i++){ if(StringUtils.isEmpty(templates[i])){ continue; } content = buildFile(templates[i], templateParamMap); if (fileSuff.length == templates.length){ writeToLocal(fullOutPath, fileSuff[i], content); } else if (fileSuff.length == 1){ writeToLocal(fullOutPath, fileSuff[1], content); } else if (fileSuff.length == 0){ writeToLocal(fullOutPath, null, content); } } } catch (IOException e){ e.printStackTrace(); }finally { if(paramReader != null){ try { paramReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } protected Map<String,Object> generalTemplateParamMap(Map<String, Object> paramMap) { paramMap.remove(TEMPLATE_PATH_KEY); paramMap.remove(FILE_SUFF_KEY); paramMap.remove(OUT_PATH_KEY); paramMap.remove(FILE_NAME_KEY); return paramMap; } protected String getDefaultOutPath(Map<String, Object> paramMap){ String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); int lastIndex = path.lastIndexOf(File.separator) + 1; return path.substring(0, lastIndex) + (StringUtils.isEmpty((String)paramMap.get(FILE_NAME_KEY)) ? "" : (String)paramMap.get(FILE_NAME_KEY)); } protected String[] getFileSuff(Object fileSuffStr){ if(fileSuffStr == null || StringUtils.isEmpty((String)fileSuffStr)){ return new String[0]; } else { return ((String) fileSuffStr).split(SPLIT_COM); } } private void writeToLocal(String outPath, String fileSuf, String content){ BufferedWriter bufferedWriter = null; try{ String fileName = outPath + (StringUtils.isEmpty(fileSuf) ? "" : fileSuf); File file = new File(fileName); bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bufferedWriter.write(content); } catch (IOException e) { e.printStackTrace(); } finally { if(bufferedWriter != null){ try { bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } protected abstract String buildFile(String templatePath, Map<String, Object> paramMap) throws IOException; protected Handlebars getHandlebars(){ Handlebars handlebars = new Handlebars(); handlebars.registerHelper("equals", (context, options) -> { CharSequence result; String right = context.toString(); String left = options.param(0).toString(); if ((right != null) && (left != null)) { if (right.equals(left)) { result = options.fn(context); } else { result = options.inverse(context); } return result; } else { return null; } }); handlebars.registerHelper("unequals", (context, options) -> { CharSequence result; String right = context.toString(); String left = options.param(0).toString(); if ((right != null) && (left != null)) { if (!right.equals(left)) { result = options.fn(context); } else { result = options.inverse(context); } return result; } else { return null; } }); return handlebars; } private String[] getTemplatePath(String templatePath) throws FileNotFoundException { if(templatePath == null){ return getDefaultTemplate().trim().split(SPLIT_COM); } else { return templatePath.trim().split(SPLIT_COM); } } /** * 获取运行变量 * @param args main函数变量 * @return 变量map */ private Map<String,String> getArgsMap(String[] args) { Map<String,String> argsMap = Maps.newHashMap(); for(int i=0; i < args.length; ) { if(args[i].startsWith("--")) { argsMap.put(args[i].substring(2), args[i + 1]); i+=2; } } return argsMap; } /** * 获取参数文件流 * @param paramPath 参数文件路径 * @return 文件流 * @throws FileNotFoundException 文件不存在异常 */ private BufferedReader getParamReader(String paramPath) throws FileNotFoundException { BufferedReader bufferedReader; if(StringUtils.isEmpty(paramPath)){ InputStream in = ClassLoader.getSystemResourceAsStream(getDefaultParamPath()); bufferedReader = new BufferedReader(new InputStreamReader(in)); } else { File paramFile = new File(paramPath); if(!paramFile.exists()){ InputStream in = ClassLoader.getSystemResourceAsStream(getDefaultParamPath()); bufferedReader = new BufferedReader(new InputStreamReader(in)); } else { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(paramFile))); } } return bufferedReader; } protected abstract String getDefaultParamPath(); /** * 解析参数文件 * @param bufferedReader 参数文件流 * @return 参数map * @throws IOException 文件异常 */ protected Map<String,Object> getParams(BufferedReader bufferedReader) throws IOException { Map<String,Object> paramMap = Maps.newHashMap(); String line; while ((line = bufferedReader.readLine()) != null){ parseNormalParam(line, paramMap); } return paramMap; } protected void parseNormalParam(String line, Map<String, Object> paramMap){ if(!StringUtils.isEmpty(line.trim()) && !line.trim().startsWith(NOTE_COM) && line.contains(PARAM_SPLIT_REGEX)){ String[] paramKV = line.split(PARAM_SPLIT_REGEX); String key = paramKV[0]; String value = paramKV[1]; paramMap.put(key, value); if(value.contains(SPLIT_COM)){ paramMap.put(key + "s", value.split(SPLIT_COM)); } } } protected abstract String getDefaultTemplate(); }
3e0fc060f05e05b51aa0d6c87556e238e82f98bf
3,641
java
Java
pippo-metrics-parent/pippo-metrics/src/main/java/ro/pippo/metrics/MetricsTransformer.java
AutoscanForJavaFork/ro.pippo-pippo-parent
8e0b2186cf2dd7e547c3655693f25f5651e2733f
[ "Apache-2.0" ]
184
2018-03-27T07:17:48.000Z
2022-03-19T12:22:39.000Z
pippo-metrics-parent/pippo-metrics/src/main/java/ro/pippo/metrics/MetricsTransformer.java
AutoscanForJavaFork/ro.pippo-pippo-parent
8e0b2186cf2dd7e547c3655693f25f5651e2733f
[ "Apache-2.0" ]
181
2018-03-26T20:32:49.000Z
2022-03-08T21:11:11.000Z
pippo-metrics-parent/pippo-metrics/src/main/java/ro/pippo/metrics/MetricsTransformer.java
AutoscanForJavaFork/ro.pippo-pippo-parent
8e0b2186cf2dd7e547c3655693f25f5651e2733f
[ "Apache-2.0" ]
53
2018-03-27T12:58:00.000Z
2022-02-11T18:09:44.000Z
40.455556
121
0.684427
6,696
/* * Copyright (C) 2016-present 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 ro.pippo.metrics; import com.codahale.metrics.MetricRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.pippo.core.PippoRuntimeException; import ro.pippo.core.route.Route; import ro.pippo.core.route.RouteContext; import ro.pippo.core.route.RouteHandler; import ro.pippo.core.route.RouteTransformer; import ro.pippo.core.util.LangUtils; import ro.pippo.core.util.StringUtils; import java.lang.reflect.Method; /** * @author Decebal Suiu */ public class MetricsTransformer implements RouteTransformer { private static final Logger log = LoggerFactory.getLogger(MetricsTransformer.class); private MetricRegistry metricRegistry; public MetricsTransformer(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } @Override public Route transform(Route route) { Method method = route.getAttribute("__controllerMethod"); if (method == null) { try { method = route.getRouteHandler().getClass().getMethod("handle", RouteContext.class); } catch (NoSuchMethodException e) { throw new PippoRuntimeException(e); } } RouteHandler handler = null; if (method.isAnnotationPresent(Metered.class)) { log.debug("Found '{}' annotation on method '{}'", Metered.class.getSimpleName(), LangUtils.toString(method)); Metered metered = method.getAnnotation(Metered.class); String metricName = !metered.value().isEmpty() ? metered.value() : getMetricName(route, method); handler = new MeteredHandler(metricName, metricRegistry, route.getRouteHandler()); } else if (method.isAnnotationPresent(Timed.class)) { log.debug("Found '{}' annotation on method '{}'", Timed.class.getSimpleName(), LangUtils.toString(method)); Timed timed = method.getAnnotation(Timed.class); String metricName = !timed.value().isEmpty() ? timed.value() : getMetricName(route, method); handler = new TimedHandler(metricName, metricRegistry, route.getRouteHandler()); } else if (method.isAnnotationPresent(Counted.class)) { log.debug("Found '{}' annotation on method '{}'", Counted.class.getSimpleName(), LangUtils.toString(method)); Counted counted = method.getAnnotation(Counted.class); String metricName = !counted.value().isEmpty() ? counted.value() : getMetricName(route, method); handler = new CountedHandler(metricName, counted.active(), metricRegistry, route.getRouteHandler()); } if (handler != null) { route.setRouteHandler(handler); } return route; } private String getMetricName(Route route, Method method) { String metricName = route.getName(); if (StringUtils.isNullOrEmpty(metricName)) { metricName = MetricRegistry.name(method.getDeclaringClass(), method.getName()); } return metricName; } }
3e0fc0f0eac0cd2ec1c2bafeb7dfdef4466c0ad9
422
java
Java
something-learned/Algorithms and Data-Structures/dsalgo/src/com/dsalgo/MaxAlternatingSequence.java
gopala-kr/Code-Rush-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
5
2018-05-09T04:02:04.000Z
2021-02-21T19:27:56.000Z
something-learned/Algorithms and Data-Structures/dsalgo/src/com/dsalgo/MaxAlternatingSequence.java
gopala-kr/Code-Rush-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
null
null
null
something-learned/Algorithms and Data-Structures/dsalgo/src/com/dsalgo/MaxAlternatingSequence.java
gopala-kr/Code-Rush-101
dd27b767cdc0c667655ab8e32e020ed4248bd112
[ "MIT" ]
5
2018-02-23T22:08:28.000Z
2020-08-19T08:31:47.000Z
17.583333
63
0.630332
6,697
package com.dsalgo; public class MaxAlternatingSequence { public static void main(String[] args) { int[] arr={5,3,4,6,7,1,2,8,7,5,7,4,6,3,4,2,8,9,8,9,6,8,5,7}; } public static int[]getLongestAlternatingSubsequence(int[]arr){ int startIndex = 0; int endIndex = 0; int maxStartIndex = 0; int maxEndIndex = 0; int maxLength = 0; for(int i=0;i<arr.length-1;++i){ } return new int[]{-1}; } }
3e0fc144bfdbb864bb5db5f10a13e6c60c2d78c7
6,469
java
Java
Banka/src/main/java/rs/ac/uns/ftn/xws/dao/util/ParserUtil.java
dejano/NiceHead
8ee5e03c65ea4ac555c2344d0d68f8df73e449f0
[ "MIT" ]
null
null
null
Banka/src/main/java/rs/ac/uns/ftn/xws/dao/util/ParserUtil.java
dejano/NiceHead
8ee5e03c65ea4ac555c2344d0d68f8df73e449f0
[ "MIT" ]
null
null
null
Banka/src/main/java/rs/ac/uns/ftn/xws/dao/util/ParserUtil.java
dejano/NiceHead
8ee5e03c65ea4ac555c2344d0d68f8df73e449f0
[ "MIT" ]
null
null
null
30.804762
89
0.743392
6,698
package rs.ac.uns.ftn.xws.dao.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; //import javax.swing.text.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; //import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; //import javax.xml.transform.TransformerConfigurationException; //import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; //import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; //import org.w3c.dom.Node; ////import org.w3c.dom.Document; import org.xml.sax.InputSource; //import org.xml.sax.SAXException; import org.xml.sax.SAXException; import rs.ac.uns.ftn.xws.dao.PaymentDataDao; import rs.ac.uns.ftn.xws.dao.PaymentOrderDataDao; import rs.ac.uns.ftn.xws.domain.bsb.PaymentData; import rs.ac.uns.ftn.xws.generated.po.PaymentOrder; import rs.ac.uns.ftn.xws.misc.XmlHelper; public class ParserUtil { // public static List<String> getPayments(String input) { // List<String> retList = new ArrayList<String>(); // // String[] parts = input.split("</bsb:paymentData>"); // for (String string : parts) { // retList.add(string + "</bsb:paymentData>"); // } // // // retList = new ArrayList<String>(Arrays.asList(parts)); // return retList; // } public static Document StringToXML(String xmlRecord) { Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); try { doc = builder .parse(new InputSource(new StringReader(xmlRecord))); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } return doc; } public static void test(Document doc) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(doc); Result outputTarget = new StreamResult(outputStream); try { TransformerFactory.newInstance().newTransformer() .transform(xmlSource, outputTarget); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream is = new ByteArrayInputStream(outputStream.toByteArray()); } // TODO @bandjur izbaci PaymentDataDao.getPayments() odnosno napravi generic parsiranje public static List<PaymentData> transformXmlListIntoPaymentDataList(String input) { List<PaymentData> retList = new ArrayList<PaymentData>(); List<String> list = PaymentDataDao.getPayments(input); for (String xmlRecord : list) { Document newDocument = StringToXML(xmlRecord); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(newDocument); Result outputTarget = new StreamResult(outputStream); try { TransformerFactory.newInstance().newTransformer() .transform(xmlSource, outputTarget); InputStream is = new ByteArrayInputStream( outputStream.toByteArray()); PaymentData payment = XmlHelper.unmarshall(is, PaymentData.class); retList.add(payment); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return retList; } // TODO @bandjur izbaci PaymentDataDao.getPayments() odnosno napravi generic parsiranje public static List<PaymentOrder> transformXmlListIntoPaymentOrderList(String input) { List<PaymentOrder> retList = new ArrayList<PaymentOrder>(); List<String> list = PaymentOrderDataDao.getPaymentOrdersStrings(input); for (String xmlRecord : list) { Document newDocument = StringToXML(xmlRecord); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(newDocument); Result outputTarget = new StreamResult(outputStream); try { TransformerFactory.newInstance().newTransformer() .transform(xmlSource, outputTarget); InputStream is = new ByteArrayInputStream( outputStream.toByteArray()); PaymentOrder paymentOrder = XmlHelper.unmarshall(is, PaymentOrder.class); retList.add(paymentOrder); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return retList; } // <? extends T> public static <T> T transformStringIntoJAXBeans(String xmlRecord, Class<T> clazz) { // <T> retVal = null; T retVal = null; Document newDocument = StringToXML(xmlRecord); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Source xmlSource = new DOMSource(newDocument); Result outputTarget = new StreamResult(outputStream); try { TransformerFactory.newInstance().newTransformer() .transform(xmlSource, outputTarget); InputStream is = new ByteArrayInputStream( outputStream.toByteArray()); T retObject = XmlHelper.unmarshall(is, clazz); retVal = (retObject != null) ? retObject : retVal; } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return retVal; } }
3e0fc2b47deaaf2eb25e720c04b33faa7cf755f2
3,732
java
Java
calc/src/main/java/org/javamoney/calc/securities/StockPresentValue.java
Izakey/javamoney-lib
0a8f341b22a2d6bab9ee34e3d0893716eedcb90a
[ "Apache-2.0" ]
1
2018-04-09T08:44:13.000Z
2018-04-09T08:44:13.000Z
calc/src/main/java/org/javamoney/calc/securities/StockPresentValue.java
achabill/javamoney-lib
0d9bb899a99db2393cb2d107d896f7039a5fe30a
[ "Apache-2.0" ]
null
null
null
calc/src/main/java/org/javamoney/calc/securities/StockPresentValue.java
achabill/javamoney-lib
0d9bb899a99db2393cb2d107d896f7039a5fe30a
[ "Apache-2.0" ]
1
2020-05-07T10:57:47.000Z
2020-05-07T10:57:47.000Z
35.542857
283
0.743301
6,699
package org.javamoney.calc.securities; import javax.money.MonetaryAmount; import javax.money.MonetaryOperator; import org.javamoney.calc.common.Rate; /** * <img src="http://www.financeformulas.net/formulaimages/PV%20of%20Stock%20-%20Constant%20Growth%201.gif" /> * <img src="http://www.financeformulas.net/formulaimages/PV%20of%20Stock%20-%20Zero%20Growth%201.gif" /> * <p> The formula for the present value of a stock with constant growth is the estimated dividends to be paid divided by the difference between the required rate of return and the growth rate. * <p> The formula for the present value of a stock with zero growth is dividends per period divided by the required return per period. The present value of stock formulas are not to be considered an exact or guaranteed approach to valuing a stock but is a more theoretical approach. * * @author Manuela Grindei * @link http://www.financeformulas.net/Present-Value-of-Stock-with-Constant-Growth.html * @link http://www.financeformulas.net/Present-Value-of-Stock-with-Zero-Growth.html */ public class StockPresentValue implements MonetaryOperator { private Rate requiredRateOfReturn; private Rate growthRate; /** * Private constructor. */ private StockPresentValue(Rate requiredRateOfReturn, Rate growthRate) { this.requiredRateOfReturn = requiredRateOfReturn; this.growthRate = growthRate; } public Rate getRequiredRateOfReturn() { return requiredRateOfReturn; } public Rate getGrowthRate() { return growthRate; } /** * Access a MonetaryOperator for calculation. * * @param requiredRateOfReturn the required rate of return * @param growthRate the growth rate * @return the operator */ public static StockPresentValue of(Rate requiredRateOfReturn, Rate growthRate) { return new StockPresentValue(requiredRateOfReturn, growthRate); } /** * Calculates the present value of a stock for constant growth. * * @param estimatedDividends the estimated dividends for next period * @param requiredRateOfReturn the required rate of return * @param the growth rate * @return the present value of the stock */ public static MonetaryAmount calculateForConstantGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn, Rate growthRate) { return estimatedDividends.divide(requiredRateOfReturn.get().subtract(growthRate.get())); } /** * Calculates the present value of a stock for constant growth. * * @param estimatedDividends the estimated dividends for next period * @param requiredRateOfReturn the required rate of return * @return the present value of the stock */ public static MonetaryAmount calculateForZeroGrowth(MonetaryAmount estimatedDividends, Rate requiredRateOfReturn) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, Rate.ZERO); } @Override public MonetaryAmount apply(MonetaryAmount estimatedDividends) { return calculateForConstantGrowth(estimatedDividends, requiredRateOfReturn, growthRate); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StockPresentValue that = (StockPresentValue) o; return requiredRateOfReturn.equals(that.requiredRateOfReturn) && growthRate.equals(that.growthRate); } @Override public int hashCode() { int result = requiredRateOfReturn.hashCode(); result = 31 * result + growthRate.hashCode(); return result; } @Override public String toString() { return "StockPresentValue{" + "requiredRateOfReturn=" + requiredRateOfReturn + ", growthRate=" + growthRate + '}'; } }
3e0fc316f3771f5a5b9e56b836f0241b000640b9
559
java
Java
apps/app-web/src/main/java/org/jpwh/web/jsf/CatalogSeekService.java
ytachi0026/road.to.hibernate.master
67615f1855284d262cb2a314149bef2fa7d858e0
[ "MIT" ]
null
null
null
apps/app-web/src/main/java/org/jpwh/web/jsf/CatalogSeekService.java
ytachi0026/road.to.hibernate.master
67615f1855284d262cb2a314149bef2fa7d858e0
[ "MIT" ]
null
null
null
apps/app-web/src/main/java/org/jpwh/web/jsf/CatalogSeekService.java
ytachi0026/road.to.hibernate.master
67615f1855284d262cb2a314149bef2fa7d858e0
[ "MIT" ]
null
null
null
23.291667
66
0.679785
6,700
package org.jpwh.web.jsf; import org.jpwh.web.dao.Page; import org.jpwh.web.dao.SeekPage; import org.jpwh.web.model.Item_; import javax.enterprise.context.RequestScoped; import javax.inject.Named; @Named @RequestScoped public class CatalogSeekService extends CatalogService<SeekPage> { @Override protected SeekPage createPage() { return new SeekPage( 3, itemDAO.getCount(), Item_.name, Page.SortDirection.ASC, Item_.id, Item_.name, Item_.auctionEnd, Item_.maxBidAmount); } }
3e0fc3b7f4561005bb507fcdb01bc0db1c2d05c8
952
java
Java
chapter_001/src/test/java/ru/job4j/condition/TriangleTest.java
vladislavXXL/vivanov
0500de48d258bb020ccf9231936cf30b88dc00fb
[ "Apache-2.0" ]
null
null
null
chapter_001/src/test/java/ru/job4j/condition/TriangleTest.java
vladislavXXL/vivanov
0500de48d258bb020ccf9231936cf30b88dc00fb
[ "Apache-2.0" ]
2
2020-10-13T09:48:11.000Z
2021-03-31T21:25:04.000Z
chapter_001/src/test/java/ru/job4j/condition/TriangleTest.java
vladislavXXL/vivanov
0500de48d258bb020ccf9231936cf30b88dc00fb
[ "Apache-2.0" ]
null
null
null
21.636364
52
0.642857
6,701
package ru.job4j.condition; import org.junit.Test; import static org.junit.Assert.assertThat; //import static org.hamcrest.core.Is.is; import static org.hamcrest.number.IsCloseTo.closeTo; /** * Triangle area test. * @author vivanov * @version 1 * @since 11.03.2017 */ public class TriangleTest { /** * Test A(1, 1), B(1, 5), C(3, 5). */ @Test public void whenAOneOneAndBOneFiveAndCThreeFive() { Point a = new Point(1, 1); Point b = new Point(1, 5); Point c = new Point(3, 5); Triangle shape = new Triangle(a, b, c); double result = shape.area(); double expected = 4.0; assertThat(result, closeTo(expected, 0.01)); } /** * Test A(2, 0), B(3, 5), C(3, 6). */ @Test public void test2() { Point a = new Point(2, 0); Point b = new Point(3, 5); Point c = new Point(3, 6); Triangle shape = new Triangle(a, b, c); double result = shape.area(); double expected = 0.5; assertThat(result, closeTo(expected, 0.01)); } }
3e0fc3b7ff5d0caa5557bb45c533c91340f4965f
4,659
java
Java
samples/src/java/org/datanucleus/samples/one_many/map/MapHolder.java
yunus/tests
3b9412622d3f1df680538f5a2ee2512c1aba7ed8
[ "Apache-2.0" ]
8
2015-06-10T13:23:02.000Z
2021-10-14T16:57:41.000Z
samples/src/java/org/datanucleus/samples/one_many/map/MapHolder.java
yunus/tests
3b9412622d3f1df680538f5a2ee2512c1aba7ed8
[ "Apache-2.0" ]
16
2016-04-15T08:59:12.000Z
2021-12-10T07:48:31.000Z
samples/src/java/org/datanucleus/samples/one_many/map/MapHolder.java
yunus/tests
3b9412622d3f1df680538f5a2ee2512c1aba7ed8
[ "Apache-2.0" ]
16
2015-02-11T02:16:43.000Z
2021-12-30T13:43:15.000Z
26.930636
141
0.570079
6,702
/********************************************************************** Copyright (c) 2006 Andy Jefferson and others. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: ... **********************************************************************/ package org.datanucleus.samples.one_many.map; import java.util.HashMap; import java.util.Map; /** * Sample class with various Map fields, testing all combinations of the types of Map field possible. */ public class MapHolder { private long id; // Used for app identity private String name; private Map<String, String> joinMapNonNon; // Map<String,String> using join table private Map<String, String> joinMapNonNon2; // Map<String,String> using join table (in case 2 ways of mapping it) private Map<String, MapValueItem> joinMapNonPC; // Map<String,MapValueItem> using join table private Map<MapKeyItem, String> joinMapPCNon; // Map<MapKeyitem,String> using join table private Map<MapKeyItem, MapValueItem> joinMapPCPC; // Map<MapKeyItem,MapValueItem> using join table private Map<String, MapValueItem> joinMapNonPCSerial; // Map<String,MapValueItem> using join table with value serialised into join table private Map<String, MapFKValueItem> fkMapKey; // Map<String,MapFKValueItem> with key stored in value private Map fkMapKey2; // Map<String,MapHolder> with key stored in value private Map fkMapValue; // Map<MapFKKeyItem,String> with value stored in key private Map mapNonNon; // Map<String,String> with no join table specified ... so serialised private Map mapSerial; // Map<String,String> serialised into single column public MapHolder() { } public MapHolder(long id) { this.id = id; } public MapHolder(String name) { this.name = name; } public long getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public Map<String, String> getJoinMapNonNon() { if (joinMapNonNon == null) { joinMapNonNon = new HashMap<>(); } return joinMapNonNon; } public Map<String, String> getJoinMapNonNon2() { if (joinMapNonNon2 == null) { joinMapNonNon2 = new HashMap<>(); } return joinMapNonNon2; } public Map<String, MapValueItem> getJoinMapNonPC() { if (joinMapNonPC == null) { joinMapNonPC = new HashMap<>(); } return joinMapNonPC; } public Map getJoinMapPCNon() { if (joinMapPCNon == null) { joinMapPCNon = new HashMap<>(); } return joinMapPCNon; } public Map<MapKeyItem, MapValueItem> getJoinMapPCPC() { if (joinMapPCPC == null) { joinMapPCPC = new HashMap<>(); } return joinMapPCPC; } public Map<String, MapValueItem> getJoinMapNonPCSerial() { if (joinMapNonPCSerial == null) { joinMapNonPCSerial = new HashMap<>(); } return joinMapNonPCSerial; } public Map getFkMapKey() { if (fkMapKey == null) { fkMapKey = new HashMap<>(); } return fkMapKey; } public Map getFkMapKey2() { if (fkMapKey2 == null) { fkMapKey2 = new HashMap<>(); } return fkMapKey2; } public Map getFkMapValue() { if (fkMapValue == null) { fkMapValue = new HashMap<>(); } return fkMapValue; } public Map getMapNonNon() { if (mapNonNon == null) { mapNonNon = new HashMap<>(); } return mapNonNon; } public Map getMapSerial() { if (mapSerial == null) { mapSerial = new HashMap<>(); } return mapSerial; } }
3e0fc49c2d9ad8e68a8187c4b58b37960a746bf0
4,897
java
Java
FasterSprintingTrait/src/trait/FasterSprintingTrait.java
tobiyas/AllTraits
a090eb3980f7c355a16da1731b703e819f43dfa1
[ "Apache-2.0" ]
null
null
null
FasterSprintingTrait/src/trait/FasterSprintingTrait.java
tobiyas/AllTraits
a090eb3980f7c355a16da1731b703e819f43dfa1
[ "Apache-2.0" ]
null
null
null
FasterSprintingTrait/src/trait/FasterSprintingTrait.java
tobiyas/AllTraits
a090eb3980f7c355a16da1731b703e819f43dfa1
[ "Apache-2.0" ]
null
null
null
30.60625
111
0.762508
6,703
/******************************************************************************* * Copyright 2014 Tob * * 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 trait; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerToggleSprintEvent; import de.tobiyas.racesandclasses.datacontainer.player.RaCPlayer; import de.tobiyas.racesandclasses.datacontainer.player.RaCPlayerManager; import de.tobiyas.racesandclasses.datacontainer.traitholdercontainer.TraitHolderCombinder; import de.tobiyas.racesandclasses.eventprocessing.eventresolvage.EventWrapper; import de.tobiyas.racesandclasses.eventprocessing.eventresolvage.EventWrapperFactory; import de.tobiyas.racesandclasses.traitcontainer.interfaces.AbstractBasicTrait; import de.tobiyas.racesandclasses.traitcontainer.interfaces.TraitResults; import de.tobiyas.racesandclasses.traitcontainer.interfaces.annotations.configuration.TraitConfigurationField; import de.tobiyas.racesandclasses.traitcontainer.interfaces.annotations.configuration.TraitConfigurationNeeded; import de.tobiyas.racesandclasses.traitcontainer.interfaces.annotations.configuration.TraitEventsUsed; import de.tobiyas.racesandclasses.traitcontainer.interfaces.annotations.configuration.TraitInfos; import de.tobiyas.racesandclasses.traitcontainer.interfaces.markerinterfaces.Trait; import de.tobiyas.racesandclasses.traitcontainer.interfaces.markerinterfaces.TraitRestriction; import de.tobiyas.racesandclasses.util.traitutil.TraitConfiguration; import de.tobiyas.racesandclasses.util.traitutil.TraitConfigurationFailedException; public class FasterSprintingTrait extends AbstractBasicTrait { private static final double NORMAL_MOD = 0.3; private double sprintMod = NORMAL_MOD; /** * The Set of sprinting people. */ private final Set<UUID> sprinting = new HashSet<UUID>(); @TraitEventsUsed(registerdClasses = {}) @Override public void generalInit() { plugin.registerEvents(this); } @EventHandler public void playerStartSprinting(PlayerToggleSprintEvent event){ if(event.isCancelled()) return; boolean sprinting = event.isSprinting(); Player player = event.getPlayer(); UUID id = player.getUniqueId(); RaCPlayer racPlayer = RaCPlayerManager.get().getPlayer(player); if(!TraitHolderCombinder.checkContainer(racPlayer, this)) return; //Now do the Action: if(sprinting){ //First check restrictions: if(super.checkRestrictions(EventWrapperFactory.buildFromEvent(event)) != TraitRestriction.None) return; this.sprinting.add(id); player.setWalkSpeed((float)sprintMod); }else{ this.sprinting.remove(id); player.setWalkSpeed((float)NORMAL_MOD); } } @Override public String getName(){ return "FasterSprintingTrait"; } @Override protected String getPrettyConfigIntern(){ return "Sprint fast: " + sprintMod; } @TraitConfigurationNeeded(fields = { @TraitConfigurationField(fieldName = "speed", classToExpect = Double.class), }) @Override public void setConfiguration(TraitConfiguration configMap) throws TraitConfigurationFailedException { super.setConfiguration(configMap); this.sprintMod = configMap.getAsDouble("speed"); } @Override public TraitResults trigger(EventWrapper eventWrapper) { return TraitResults.False(); } public static List<String> getHelpForTrait(){ List<String> helpList = new LinkedList<String>(); helpList.add(ChatColor.YELLOW + "The trait lets you sprint faster."); return helpList; } @Override public boolean isBetterThan(Trait trait) { if(!(trait instanceof FasterSprintingTrait)) return false; FasterSprintingTrait otherTrait = (FasterSprintingTrait) trait; return sprintMod >= otherTrait.sprintMod; } @TraitInfos(category="passive", traitName="FasterSprintingTrait", visible=true) @Override public void importTrait() { } @Override public boolean canBeTriggered(EventWrapper wrapper) { return false; } @Override public boolean triggerButHasUplink(EventWrapper wrapper) { return false; } @Override public boolean notifyTriggeredUplinkTime(EventWrapper wrapper) { return false; } }
3e0fc4c2e5849e760d7d43a60c9eca7133d00e9d
3,722
java
Java
src/main/java/pulse/problem/schemes/solvers/ExplicitLinearisedSolver.java
kotik-coder/PULsE
7b9081f4a35f5faeb62d13968536bc18dcbce787
[ "Apache-2.0" ]
null
null
null
src/main/java/pulse/problem/schemes/solvers/ExplicitLinearisedSolver.java
kotik-coder/PULsE
7b9081f4a35f5faeb62d13968536bc18dcbce787
[ "Apache-2.0" ]
null
null
null
src/main/java/pulse/problem/schemes/solvers/ExplicitLinearisedSolver.java
kotik-coder/PULsE
7b9081f4a35f5faeb62d13968536bc18dcbce787
[ "Apache-2.0" ]
2
2020-02-23T11:49:51.000Z
2020-09-30T09:41:33.000Z
36.490196
111
0.680279
6,704
package pulse.problem.schemes.solvers; import pulse.problem.schemes.DifferenceScheme; import pulse.problem.schemes.ExplicitScheme; import pulse.problem.statements.ClassicalProblem; import pulse.problem.statements.Problem; import pulse.properties.NumericProperty; /** * Performs a fully-dimensionless calculation for the {@code LinearisedProblem}. * <p> * Relies on using the heat equation to calculate the value of the grid-function * at the next timestep. Fills the {@code grid} completely at each specified * spatial point. The heating curve is updated with the rear-side temperature * <math><i>&Theta;(x<sub>N</sub>,t<sub>i</sub></i></math>) (here * <math><i>N</i></math> is the grid density) at the end of {@code timeLimit} * intervals, which comprise of {@code timeLimit/tau} time steps. The * {@code HeatingCurve} is scaled (re-normalised) by a factor of * {@code maxTemp/maxVal}, where {@code maxVal} is the absolute maximum of the * calculated solution (with respect to time), and {@code maxTemp} is the * {@code maximumTemperature} {@code NumericProperty} of {@code problem}. * </p> * <p> * The explicit scheme uses a standard 4-point template on a one-dimensional * grid that utilises the following grid-function values on each step: * <math><i>&Theta;(x<sub>i</sub>,t<sub>m</sub>), * &Theta;(x<sub>i</sub>,t<sub>m+1</sub>), * &Theta;(x<sub>i-1</sub>,t<sub>m</sub>), * &Theta;(x<sub>i+1</sub>,t<sub>m</sub>)</i></math>. Hence, the calculation of * the grid-function at the timestep <math><i>m</i>+1</math> can be done * <i>explicitly</i>. The derivative in the boundary conditions is approximated * using a simple forward difference. * </p> * <p> * The explicit scheme is stable only if <math><i>&tau; &le; * h<sup>2</sup></i></math> and has an order of approximation of * <math><i>O(&tau; + h)</i></math>. Note that this scheme is only used for * validating more complex schemes and does not give accurate results due to the * lower order of approximation. When calculations using this scheme are * performed, the <code>gridDensity</code> is chosen to be at least 80, which * ensures that the error is not too high (typically a {@code 1.5E-2} relative * error). * </p> * * @see super.solve(Problem) */ public class ExplicitLinearisedSolver extends ExplicitScheme implements Solver<ClassicalProblem> { private int N; private double hx; private double a; public ExplicitLinearisedSolver() { super(); } public ExplicitLinearisedSolver(NumericProperty N, NumericProperty timeFactor) { super(N, timeFactor); } public ExplicitLinearisedSolver(NumericProperty N, NumericProperty timeFactor, NumericProperty timeLimit) { super(N, timeFactor, timeLimit); } @Override public void prepare(Problem problem) { super.prepare(problem); N = (int) getGrid().getGridDensity().getValue(); hx = getGrid().getXStep(); final double Bi1 = (double) problem.getProperties().getHeatLoss().getValue(); a = 1. / (1. + Bi1 * hx); } @Override public void solve(ClassicalProblem problem) { prepare(problem); runTimeSequence(problem); } @Override public void timeStep(int m) { explicitSolution(); var V = getCurrentSolution(); setSolutionAt(0, (V[1] + hx * pulse(m)) * a); setSolutionAt(N, V[N - 1] * a); } @Override public DifferenceScheme copy() { var grid = getGrid(); return new ExplicitLinearisedSolver(grid.getGridDensity(), grid.getTimeFactor(), getTimeLimit()); } @Override public Class<? extends Problem> domain() { return ClassicalProblem.class; } }
3e0fc51de32174a8336ea5122b8ff5d129768d6e
2,418
java
Java
ddal-common/src/test/java/studio/raptor/ddal/common/sql/SQLHintSpecTest.java
Raptor-team/raptor-ddal
b5a827dfcfbf07c380dc5ea3ecb4c61749426a81
[ "ECL-2.0", "Apache-2.0" ]
1
2021-06-02T14:12:11.000Z
2021-06-02T14:12:11.000Z
ddal-common/src/test/java/studio/raptor/ddal/common/sql/SQLHintSpecTest.java
Raptor-team/raptor-ddal
b5a827dfcfbf07c380dc5ea3ecb4c61749426a81
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
ddal-common/src/test/java/studio/raptor/ddal/common/sql/SQLHintSpecTest.java
Raptor-team/raptor-ddal
b5a827dfcfbf07c380dc5ea3ecb4c61749426a81
[ "ECL-2.0", "Apache-2.0" ]
2
2020-01-16T09:48:26.000Z
2021-06-02T14:12:12.000Z
35.043478
99
0.710918
6,705
/* * 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 studio.raptor.ddal.common.sql; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import org.junit.Assert; import org.junit.Test; import studio.raptor.ddal.common.sql.SQLHintParser.SQLHint; /** * @author Sam * @since 3.0.0 */ public class SQLHintSpecTest { @Test public void testSqlHintSpec_1() { String sql = "/*!hint page(offset=0, count=10); shard(id=10000);*/ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); Assert .assertEquals("/*!hint page(offset=0, count=10); shard(id=10000); */", sqlHint.toString()); assertThat(sqlHint.toSpec(), is("DDALHintSpec;page;shard+id")); } @Test public void testSqlHintSpec_2() { String sql = "/*!hint page(offset=0, count=5); */ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); assertThat(sqlHint.toSpec(), is("DDALHintSpec;page")); } @Test public void testSqlHintSpec_3() { String sql = "/*!hint shard(user_id=10000);*/ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); Assert.assertEquals("/*!hint shard(user_id=10000); */", sqlHint.toString()); assertThat(sqlHint.toSpec(), is("DDALHintSpec;shard+user_id")); } @Test public void testSqlHintSpec_4() { String sql = "/*!hint page(offset=0, count=5); readonly; */ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); assertThat(sqlHint.toSpec(), is("DDALHintSpec;page;readonly")); } }
3e0fc54fe237a14d96d40585a2a66189b69f79c4
2,389
java
Java
JUC2021/src/main/java/com/chihsien/juc2021/rwlock/ReentrantReadWriteLockDemo.java
ChiHsiencheng/springcloudDemo
a1169f2aabfcf4fd315968e38f91b7041e9b54c5
[ "MIT" ]
1
2021-06-02T06:39:27.000Z
2021-06-02T06:39:27.000Z
JUC2021/src/main/java/com/chihsien/juc2021/rwlock/ReentrantReadWriteLockDemo.java
ChiHsiencheng/springcloudDemo
a1169f2aabfcf4fd315968e38f91b7041e9b54c5
[ "MIT" ]
null
null
null
JUC2021/src/main/java/com/chihsien/juc2021/rwlock/ReentrantReadWriteLockDemo.java
ChiHsiencheng/springcloudDemo
a1169f2aabfcf4fd315968e38f91b7041e9b54c5
[ "MIT" ]
1
2021-06-02T06:39:31.000Z
2021-06-02T06:39:31.000Z
27.45977
109
0.547928
6,706
package com.chihsien.juc2021.rwlock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class MyResource { Map<String,String> map = new HashMap<>(); //=====ReentrantLock 等价于 =====synchronized Lock lock = new ReentrantLock(); //=====ReentrantReadWriteLock 一体两面,读写互斥,读读共享 ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); public void write(String key,String value) { rwLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t"+"---正在写入"); map.put(key,value); try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"\t"+"---完成写入"); }finally { rwLock.writeLock().unlock(); } } public void read(String key) { rwLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t"+"---正在读取"); String result = map.get(key); //暂停几秒钟线程 try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"\t"+"---完成读取result: "+result); }finally { rwLock.readLock().unlock(); } } } /*** * @describe * * @return * @author ChiHsien<br> * @version */ public class ReentrantReadWriteLockDemo { public static void main(String[] args) { MyResource myResource = new MyResource(); for (int i = 1; i <=10; i++) { int finalI = i; new Thread(() -> { myResource.write(finalI +"", finalI +""); },String.valueOf(i)).start(); } for (int i = 1; i <=10; i++) { int finalI = i; new Thread(() -> { myResource.read(finalI +""); },String.valueOf(i)).start(); } for (int i = 1; i <=3; i++) { int finalI = i; new Thread(() -> { myResource.write(finalI +"", finalI +""); },"马羽成"+String.valueOf(i)).start(); } } }
3e0fc5adfccf61810c31d7c43a49c073332d0adc
3,058
java
Java
src/test/java/it/polimi/deib/newdem/adrenaline/model/game/changes/TestAmmoLossGameChange.java
NoImaginationGuy/adrenaline
b0a95d767475fb2ce807cffe4f64fe1b088497e8
[ "Apache-2.0" ]
null
null
null
src/test/java/it/polimi/deib/newdem/adrenaline/model/game/changes/TestAmmoLossGameChange.java
NoImaginationGuy/adrenaline
b0a95d767475fb2ce807cffe4f64fe1b088497e8
[ "Apache-2.0" ]
null
null
null
src/test/java/it/polimi/deib/newdem/adrenaline/model/game/changes/TestAmmoLossGameChange.java
NoImaginationGuy/adrenaline
b0a95d767475fb2ce807cffe4f64fe1b088497e8
[ "Apache-2.0" ]
null
null
null
35.55814
90
0.739372
6,707
package it.polimi.deib.newdem.adrenaline.model.game.changes; import it.polimi.deib.newdem.adrenaline.TestingUtils; import it.polimi.deib.newdem.adrenaline.controller.Config; import it.polimi.deib.newdem.adrenaline.model.game.ColorUserPair; import it.polimi.deib.newdem.adrenaline.model.game.Game; import it.polimi.deib.newdem.adrenaline.model.game.GameImpl; import it.polimi.deib.newdem.adrenaline.model.game.GameParameters; import it.polimi.deib.newdem.adrenaline.model.game.player.Player; import it.polimi.deib.newdem.adrenaline.model.game.player.PlayerColor; import it.polimi.deib.newdem.adrenaline.model.items.AmmoColor; import it.polimi.deib.newdem.adrenaline.model.items.AmmoSet; import it.polimi.deib.newdem.adrenaline.model.items.Weapon; import it.polimi.deib.newdem.adrenaline.model.map.Map; import it.polimi.deib.newdem.adrenaline.model.mgmt.User; import it.polimi.deib.newdem.adrenaline.view.server.NullVirtualGameView; import it.polimi.deib.newdem.adrenaline.view.server.VirtualDamageBoardView; import it.polimi.deib.newdem.adrenaline.view.server.VirtualGameView; import it.polimi.deib.newdem.adrenaline.view.server.VirtualKillTrackView; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class TestAmmoLossGameChange { private Player p1; private Game game; private VirtualGameView vgv; private AmmoSet ammoSet; private Map map; private AmmoLossGameChange gameChange; @Before public void setUp() throws Exception { TestingUtils.loadSingleton(); map = Map.createMap("Map0_0.json"); GameParameters gp = GameParameters.fromConfig(Config.getDefaultConfig()); ColorUserPair colorUserPair1 = new ColorUserPair(PlayerColor.YELLOW, new User()); ColorUserPair colorUserPair2 = new ColorUserPair(PlayerColor.GREEN, new User()); ColorUserPair colorUserPair3 = new ColorUserPair(PlayerColor.GRAY, new User()); ColorUserPair colorUserPair4 = new ColorUserPair(PlayerColor.MAGENTA, new User()); List<ColorUserPair> listPairs = new ArrayList<>(); listPairs.add(colorUserPair1); listPairs.add(colorUserPair2); listPairs.add(colorUserPair3); listPairs.add(colorUserPair4); gp.setColorUserOrder(listPairs); gp.setGameMap(map); TestingUtils.loadSingleton(); game = new GameImpl(gp); VirtualGameView vgv = new NullVirtualGameView(); game.setGameListener(vgv); game.setKillTrackListener(new VirtualKillTrackView(vgv)); //??? game.init(); p1 = game.getPlayerFromColor(PlayerColor.YELLOW); p1.getDamageBoard().setListener(new VirtualDamageBoardView(p1, vgv)); p1.getInventory().addAmmo(AmmoColor.BLUE, 3); ammoSet = new AmmoSet(0, 0 ,3); gameChange = new AmmoLossGameChange(p1, ammoSet); } @Test public void revert() { gameChange.revert(game); assertEquals(3, p1.getInventory().getBlue()); } }
3e0fc5ccf3ecb2ccdcc8d180d8a46f96acf584b3
1,639
java
Java
jenkins-editor-plugin/src/main/java/de/jcup/jenkins/OutlinePipelineDSL.java
BeckerFrank/eclipse-jenkins-editor
5f4704da575830869b8132e1b3f41a4151cde24a
[ "Apache-2.0" ]
41
2017-09-29T11:35:14.000Z
2022-03-09T09:27:53.000Z
jenkins-editor-plugin/src/main/java/de/jcup/jenkins/OutlinePipelineDSL.java
BeckerFrank/eclipse-jenkins-editor
5f4704da575830869b8132e1b3f41a4151cde24a
[ "Apache-2.0" ]
90
2017-09-26T11:34:47.000Z
2022-03-14T15:07:51.000Z
jenkins-editor-plugin/src/main/java/de/jcup/jenkins/OutlinePipelineDSL.java
BeckerFrank/eclipse-jenkins-editor
5f4704da575830869b8132e1b3f41a4151cde24a
[ "Apache-2.0" ]
9
2017-09-29T12:00:41.000Z
2021-12-31T08:57:18.000Z
19.987805
75
0.678462
6,708
/* * Copyright 2017 Albert Tregnaghi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * */ package de.jcup.jenkins; /** * Pipeline DSL enum containing parts rendered in outline. * See https://jenkins.io/doc/book/pipeline/syntax/ * @author Albert Tregnaghi * */ public enum OutlinePipelineDSL{ /* @formatter:off*/ AGENT, DOCKER, DOCKERFILE, PARALLEL, PIPELINE, SCRIPT, STAGE, STAGES, STEPS, TOOLS, TRIGGERS, WHEN, ENVIRONMENT, EXPRESSION, NOT, ALLOF, ANYOF, OPTIONS, PARAMETERS, NODE, POST, ALWAYS, FAILURE, CHANGED, SUCCESS, UNSTABLE, ABORTED, INPUT, ; /* @formatter:on*/ private String path; private String id; private OutlinePipelineDSL(){ path="/icons/jenkinseditor/outline/dsl/"+name().toLowerCase()+".png"; id=name().toLowerCase(); } public String getRelativePathInsidePlugin(){ return path; } public static final OutlinePipelineDSL tryToFind(String lowerCasedId){ for (OutlinePipelineDSL dsl: values()){ if (dsl.id.equals(lowerCasedId)){ return dsl; } } return null; } }
3e0fc661a84eb7dea3f816520d47603c6d506e7f
2,566
java
Java
src/main/java/org/librairy/client/topics/LDA.java
librairy/client
1082937100ae0941ab9f2c2bdcf96dc0982d0f9a
[ "Apache-2.0" ]
null
null
null
src/main/java/org/librairy/client/topics/LDA.java
librairy/client
1082937100ae0941ab9f2c2bdcf96dc0982d0f9a
[ "Apache-2.0" ]
null
null
null
src/main/java/org/librairy/client/topics/LDA.java
librairy/client
1082937100ae0941ab9f2c2bdcf96dc0982d0f9a
[ "Apache-2.0" ]
null
null
null
30.270588
74
0.60513
6,709
/* * Copyright (C) 2007 by * * Xuan-Hieu Phan * hzdkv@example.com or dycjh@example.com * Graduate School of Information Sciences * Tohoku University * * Cam-Tu Nguyen * anpch@example.com * College of Technology * Vietnam National University, Hanoi * * JGibbsLDA is a 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 2 of the License, * or (at your option) any later version. * * JGibbsLDA 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 JGibbsLDA; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package org.librairy.client.topics; import java.io.FileNotFoundException; import org.kohsuke.args4j.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * JGibbLabeledLDA */ public class LDA { private static final Logger LOG = LoggerFactory.getLogger(LDA.class); public static void main(String args[]) { LDACmdOption option = new LDACmdOption(); CmdLineParser parser = new CmdLineParser(option); try { if (args.length == 0){ showHelp(parser); return; } parser.parseArgument(args); if (option.est || option.estc){ Estimator estimator = new Estimator(option); estimator.estimate(); } else if (option.inf){ Inferencer inferencer = new Inferencer(option); Model newModel = inferencer.inference(); } } catch (CmdLineException cle){ LOG.debug("Command line error: " + cle.getMessage()); showHelp(parser); return; } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (Exception e){ LOG.debug("Error in main: " + e.getMessage()); e.printStackTrace(); return; } } public static void showHelp(CmdLineParser parser){ LOG.debug("LDA [options ...] [arguments...]"); parser.printUsage(System.out); } }
3e0fc6d139cbf9a4aacaf79ed7402fc244cf2807
513
java
Java
hackerearth/julyeasy15/the-falling-eagle.java
harry-7/mycodes
442d84fab9dddde12fa0e68fd1a43f7bf13f849d
[ "MIT" ]
1
2016-11-10T13:21:57.000Z
2016-11-10T13:21:57.000Z
hackerearth/julyeasy15/the-falling-eagle.java
harry-7/mycodes
442d84fab9dddde12fa0e68fd1a43f7bf13f849d
[ "MIT" ]
null
null
null
hackerearth/julyeasy15/the-falling-eagle.java
harry-7/mycodes
442d84fab9dddde12fa0e68fd1a43f7bf13f849d
[ "MIT" ]
null
null
null
22.304348
60
0.60039
6,710
/* Author: Hemanth Kumar Veeranki */ /* Handle: harry7 */ import java.io.*; import java.util.*; import java.math.*; class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); /*sc for taking input*/ PrintStream op=System.out;/*op for printing output*/ for(int t=sc.nextInt();t!=0;t--){ int i,n; long ans=0; n=sc.nextInt(); long[] a=new long[n+1]; for(i=0;i<n;i++){ a[i]=sc.nextLong(); if(i!=0)ans+=Math.max(a[i-1],a[i]); } op.println(ans); } } }
3e0fc6f99d15ad368f30995a6bea535e0a8494bb
202
java
Java
app/src/main/java/com/example/administrator/boshide2/Modular/View/timepicker/WheelAdapter.java
njjames/bsd
37a96dcd2f7a689077b7775c1f515661dad18d9d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/administrator/boshide2/Modular/View/timepicker/WheelAdapter.java
njjames/bsd
37a96dcd2f7a689077b7775c1f515661dad18d9d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/administrator/boshide2/Modular/View/timepicker/WheelAdapter.java
njjames/bsd
37a96dcd2f7a689077b7775c1f515661dad18d9d
[ "Apache-2.0" ]
null
null
null
18.363636
67
0.792079
6,711
package com.example.administrator.boshide2.Modular.View.timepicker; public interface WheelAdapter { public int getItemsCount(); public String getItem(int index); public int getMaximumLength(); }
3e0fc76012b30fb6b8a2209cacf36cd1d5c9c70b
192
java
Java
parent/core/src/main/java/cn/gyyx/bts/core/ctrl/TimerCtrl.java
ssstzbs/bts
a9d934c3b375c6bd660e62db778f4280095c84e6
[ "Apache-2.0" ]
null
null
null
parent/core/src/main/java/cn/gyyx/bts/core/ctrl/TimerCtrl.java
ssstzbs/bts
a9d934c3b375c6bd660e62db778f4280095c84e6
[ "Apache-2.0" ]
4
2020-03-04T22:40:11.000Z
2021-12-09T21:29:40.000Z
parent/core/src/main/java/cn/gyyx/bts/core/ctrl/TimerCtrl.java
ssstzbs/bts
a9d934c3b375c6bd660e62db778f4280095c84e6
[ "Apache-2.0" ]
null
null
null
13.714286
45
0.75
6,712
package cn.gyyx.bts.core.ctrl; import com.google.inject.Inject; import cn.gyyx.bts.core.TriggerSystem; public class TimerCtrl extends TriggerSystem{ @Inject public TimerCtrl() { } }
3e0fc95b9ba916a4ba6553c885743b1dba4be954
1,936
java
Java
rxjava-contrib/rxjava-android/src/main/java/rx/android/subscriptions/AndroidSubscriptions.java
tomrozb/RxJava
fc86f8c340c3fc9d1ba983013383c3cac4c30c17
[ "Apache-2.0" ]
3
2015-03-12T22:49:13.000Z
2017-06-26T11:02:01.000Z
rxjava-contrib/rxjava-android/src/main/java/rx/android/subscriptions/AndroidSubscriptions.java
tomrozb/RxJava
fc86f8c340c3fc9d1ba983013383c3cac4c30c17
[ "Apache-2.0" ]
null
null
null
rxjava-contrib/rxjava-android/src/main/java/rx/android/subscriptions/AndroidSubscriptions.java
tomrozb/RxJava
fc86f8c340c3fc9d1ba983013383c3cac4c30c17
[ "Apache-2.0" ]
null
null
null
33.37931
90
0.61312
6,713
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.android.subscriptions; import rx.Scheduler.Worker; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action0; import rx.functions.Action1; import rx.subscriptions.Subscriptions; import android.os.Looper; public final class AndroidSubscriptions { private AndroidSubscriptions() { // no instance } /** * Create an Subscription that always runs <code>unsubscribe</code> in the UI thread. * * @param unsubscribe * @return an Subscription that always runs <code>unsubscribe</code> in the UI thread. */ public static Subscription unsubscribeInUiThread(final Action0 unsubscribe) { return Subscriptions.create(new Action0() { @Override public void call() { if (Looper.getMainLooper() == Looper.myLooper()) { unsubscribe.call(); } else { final Worker inner = AndroidSchedulers.mainThread().createWorker(); inner.schedule(new Action0() { @Override public void call() { unsubscribe.call(); inner.unsubscribe(); } }); } } }); } }
3e0fc9c7d59318c1d23f7b8534f6a261e06684e2
1,013
java
Java
src/main/java/org/lastaflute/di/core/customizer/ext/ConcreteDrivenCustomizerChain.java
lastaflute/lasta-di
5b576c1e4ee118d8bc01814faebbd1febff84e03
[ "Apache-2.0" ]
8
2015-09-30T11:30:14.000Z
2021-12-29T14:49:20.000Z
src/main/java/org/lastaflute/di/core/customizer/ext/ConcreteDrivenCustomizerChain.java
lastaflute/lasta-di
5b576c1e4ee118d8bc01814faebbd1febff84e03
[ "Apache-2.0" ]
4
2015-08-19T07:05:38.000Z
2021-07-29T16:02:05.000Z
src/main/java/org/lastaflute/di/core/customizer/ext/ConcreteDrivenCustomizerChain.java
lastaflute/lasta-di
5b576c1e4ee118d8bc01814faebbd1febff84e03
[ "Apache-2.0" ]
6
2015-05-29T08:47:48.000Z
2015-08-19T01:28:03.000Z
32.677419
71
0.754195
6,714
/* * Copyright 2015-2021 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.lastaflute.di.core.customizer.ext; import org.lastaflute.di.core.customizer.AspectCustomizer; import org.lastaflute.di.core.customizer.CustomizerChain; /** * @author jflute */ public class ConcreteDrivenCustomizerChain extends CustomizerChain { @Override protected AspectCustomizer newAspectCustomizer() { return new ConcreteDrivenAspectCustomizer(); } }
3e0fca6187c16f9cd239bcf0e5dd08acc469c61e
2,728
java
Java
graphwrap/src/main/java/iiuf/swing/propertiespanel/NumberField.java
Alex-Ikanow/pdfxtk
f5d37104bf99a640fbaa25adf8904057b620edc6
[ "Apache-2.0" ]
1
2017-07-04T21:36:07.000Z
2017-07-04T21:36:07.000Z
graphwrap/src/main/java/iiuf/swing/propertiespanel/NumberField.java
Alex-Ikanow/pdfxtk
f5d37104bf99a640fbaa25adf8904057b620edc6
[ "Apache-2.0" ]
null
null
null
graphwrap/src/main/java/iiuf/swing/propertiespanel/NumberField.java
Alex-Ikanow/pdfxtk
f5d37104bf99a640fbaa25adf8904057b620edc6
[ "Apache-2.0" ]
null
null
null
28.715789
126
0.69978
6,715
package iiuf.swing.propertiespanel; import java.awt.GridBagConstraints; import java.util.Hashtable; import javax.swing.JLabel; import javax.swing.JComponent; import javax.swing.KeyStroke; import java.awt.event.KeyEvent; import iiuf.awt.Awt; import iiuf.swing.JNumberField; /** NumberField property implementation.<p> (c) 2000, 2001, IIUF, DIUF<p> @author $Author: ohitz $ @version $Name: $ $Revision: 1.1 $ */ public class NumberField extends Property { private String label; private double value; private double min; private double max; private boolean integer; public NumberField(boolean required, String key, String label_, double value_, double min_, double max_, boolean integer_) { super(required, key); label = label_; value = value_; min = min_; max = max_; } public NumberField(String key, String label, double value, double min, double max, boolean integer) { this(false, key, label, value, min, max, integer); } public void read(PropertiesPanel panel, Hashtable values) { if(((JNumberField)panel.getCmp(this)).getText().length() > 0) values.put(key, ((JNumberField)panel.valuecmps.get(key)).getText()); } public void write(PropertiesPanel panel, Hashtable values) { Object v = values.get(key); if(v != null) ((JNumberField)panel.getCmp(this)).setText(v.toString()); } public boolean isValid(PropertiesPanel panel, JComponent cmp) { return required ? ((JNumberField)cmp).getText().length() > 0 : true; } public void create(PropertiesPanel panel) { JLabel l =new JLabel(label); l.setForeground(required ? PropertiesPanel.REQUIRED : PropertiesPanel.NON_REQUIRED); panel.container.add(l, Awt.constraints(false)); JNumberField tf = null; if(required) tf = panel.createCheckingNF(value, min, max, integer); else if(integer) tf = new JNumberField((int)value, (int)min, (int)max); else tf = new JNumberField(value, min, max); tf.setEnabled(enabled); tf.getKeymap().removeKeyStrokeBinding(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)); panel.valuecmps.put(key, tf); panel.container.add(tf, Awt.constraints(true, GridBagConstraints.HORIZONTAL)); } } /* $Log: NumberField.java,v $ Revision 1.1 2002/07/11 12:09:52 ohitz Initial checkin Revision 1.1 2001/03/12 17:53:42 schubige Added version support to sourcewatch and enhanced soundium Revision 1.3 2001/02/14 17:25:38 schubige implemented resizing, select all and key-shortcuts for graph panel Revision 1.2 2001/01/04 16:28:40 schubige Header update for 2001 and DIUF Revision 1.1 2000/10/09 06:49:27 schubige Added properties panel */
3e0fcb2acd39a381f976a6337827aa408face15b
5,556
java
Java
presto-main/src/main/java/com/facebook/presto/operator/SetBuilderOperator.java
stagraqubole/presto
d7f77266b610b9b8e6ae2c51aa9ff3c381524197
[ "Apache-2.0" ]
null
null
null
presto-main/src/main/java/com/facebook/presto/operator/SetBuilderOperator.java
stagraqubole/presto
d7f77266b610b9b8e6ae2c51aa9ff3c381524197
[ "Apache-2.0" ]
null
null
null
presto-main/src/main/java/com/facebook/presto/operator/SetBuilderOperator.java
stagraqubole/presto
d7f77266b610b9b8e6ae2c51aa9ff3c381524197
[ "Apache-2.0" ]
null
null
null
28.787565
133
0.652808
6,716
/* * 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.facebook.presto.operator; import com.facebook.presto.operator.ChannelSet.ChannelSetBuilder; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import javax.annotation.concurrent.ThreadSafe; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; @ThreadSafe public class SetBuilderOperator implements Operator { public static class SetSupplier { private final Type type; private final SettableFuture<ChannelSet> channelSetFuture = SettableFuture.create(); public SetSupplier(Type type) { this.type = checkNotNull(type, "type is null"); } public Type getType() { return type; } public ListenableFuture<ChannelSet> getChannelSet() { return channelSetFuture; } void setChannelSet(ChannelSet channelSet) { boolean wasSet = channelSetFuture.set(checkNotNull(channelSet, "channelSet is null")); checkState(wasSet, "ChannelSet already set"); } } public static class SetBuilderOperatorFactory implements OperatorFactory { private final int operatorId; private final SetSupplier setProvider; private final int setChannel; private final int expectedPositions; private boolean closed; public SetBuilderOperatorFactory( int operatorId, List<Type> types, int setChannel, int expectedPositions) { this.operatorId = operatorId; Preconditions.checkArgument(setChannel >= 0, "setChannel is negative"); this.setProvider = new SetSupplier(checkNotNull(types, "types is null").get(setChannel)); this.setChannel = setChannel; this.expectedPositions = checkNotNull(expectedPositions, "expectedPositions is null"); } public SetSupplier getSetProvider() { return setProvider; } @Override public List<Type> getTypes() { return ImmutableList.of(); } @Override public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, SetBuilderOperator.class.getSimpleName()); return new SetBuilderOperator(operatorContext, setProvider, setChannel, expectedPositions); } @Override public void close() { closed = true; } } private final OperatorContext operatorContext; private final SetSupplier setSupplier; private final int setChannel; private final ChannelSetBuilder channelSetBuilder; private boolean finished; public SetBuilderOperator( OperatorContext operatorContext, SetSupplier setSupplier, int setChannel, int expectedPositions) { this.operatorContext = checkNotNull(operatorContext, "operatorContext is null"); this.setSupplier = checkNotNull(setSupplier, "setProvider is null"); this.setChannel = setChannel; this.channelSetBuilder = new ChannelSetBuilder( setSupplier.getType(), expectedPositions, checkNotNull(operatorContext, "operatorContext is null")); } @Override public OperatorContext getOperatorContext() { return operatorContext; } @Override public List<Type> getTypes() { return ImmutableList.of(); } @Override public void finish() { if (finished) { return; } ChannelSet channelSet = channelSetBuilder.build(); setSupplier.setChannelSet(channelSet); operatorContext.recordGeneratedOutput(channelSet.getEstimatedSizeInBytes(), channelSet.size()); finished = true; } @Override public boolean isFinished() { return finished; } @Override public ListenableFuture<?> isBlocked() { return NOT_BLOCKED; } @Override public boolean needsInput() { return !finished; } @Override public void addInput(Page page) { checkNotNull(page, "page is null"); checkState(!isFinished(), "Operator is already finished"); Block sourceBlock = page.getBlock(setChannel); channelSetBuilder.addBlock(sourceBlock); } @Override public Page getOutput() { return null; } }
3e0fcb4ef89e68003dc85642c68a25fe93583ea6
2,089
java
Java
string-calc-kata/string-calc-day-8/src/main/java/ua/kata/StringCalc.java
alex-dukhno/java-tdd-katas
c3f76c4308988e7d83bad78fd0f34193afa83af7
[ "MIT" ]
null
null
null
string-calc-kata/string-calc-day-8/src/main/java/ua/kata/StringCalc.java
alex-dukhno/java-tdd-katas
c3f76c4308988e7d83bad78fd0f34193afa83af7
[ "MIT" ]
null
null
null
string-calc-kata/string-calc-day-8/src/main/java/ua/kata/StringCalc.java
alex-dukhno/java-tdd-katas
c3f76c4308988e7d83bad78fd0f34193afa83af7
[ "MIT" ]
null
null
null
24.011494
88
0.568214
6,717
package ua.kata; import java.util.Map; import java.util.function.IntBinaryOperator; public class StringCalc { public int compute(String src) { return new Parser(src).parseExpression(); } private static class Parser { private final Map<Character, IntBinaryOperator> lowOrderOperations = Map.ofEntries( Map.entry('+', (a, b) -> a + b), Map.entry('-', (a, b) -> a - b) ); private final Map<Character, IntBinaryOperator> highOrderOperations = Map.ofEntries( Map.entry('*', (a, b) -> a * b), Map.entry('/', (a, b) -> a / b) ); private final String src; private int index; Parser(String src) { this.src = src; } private int parseExpression() { int num = parseTerm(); IntBinaryOperator operation; while ((operation = lowOrderOperations.get(parseOperation())) != null) { skip(); num = operation.applyAsInt(num, parseTerm()); } return num; } int parseTerm() { int num = parseArgument(); IntBinaryOperator operator; while ((operator = highOrderOperations.get(parseOperation())) != null) { skip(); num = operator.applyAsInt(num, parseArgument()); } return num; } int parseArgument() { if (isSubexpression()) { return parseSubexpression(); } else { int start = index; int end = findEndOfNumber(); index = end; return Integer.parseInt(src.substring(start, end)); } } private int findEndOfNumber() { int end = src.charAt(index) == '-' ? index + 1 : index; while (end < src.length() && Character.isDigit(src.charAt(end))) { end++; } return end; } private int parseSubexpression() { skip(); int num = parseExpression(); skip(); return num; } private boolean isSubexpression() { return src.charAt(index) == '('; } char parseOperation() { return index >= src.length() ? 0 : src.charAt(index); } void skip() { index++; } } }
3e0fcb9c2db51bfa0d5fd4b0f0dc194471aafaf6
625
java
Java
src/main/java/be/intec/services/exceptions/TestException.java
yilmazchef/jobs4me
f9e55c897bfc8be12126c9243cc29912ca24758e
[ "Unlicense" ]
null
null
null
src/main/java/be/intec/services/exceptions/TestException.java
yilmazchef/jobs4me
f9e55c897bfc8be12126c9243cc29912ca24758e
[ "Unlicense" ]
null
null
null
src/main/java/be/intec/services/exceptions/TestException.java
yilmazchef/jobs4me
f9e55c897bfc8be12126c9243cc29912ca24758e
[ "Unlicense" ]
null
null
null
16.447368
78
0.72
6,718
package be.intec.services.exceptions; import java.util.Arrays; public class TestException extends RuntimeException { public TestException( String message ) { super( message ); } public TestException notFound() { return new TestException( "Test not found" ); } public TestException alreadyExists() { return new TestException( "Test already exists" ); } public TestException requiredFields( String... fields ) { return new TestException( "Required fields: " + Arrays.toString( fields ) ); } public TestException nullTestException() { return new TestException( "Test cannot be null" ); } }
3e0fcc77d8a0ef79b9f4dc25cc375ab5f5956214
1,361
java
Java
service/src/main/java/org/apache/fineract/cn/group/internal/command/UpdateLeadersCommand.java
cabrelkemfang/fineract-cn-group
3fa848834ab8e519b3b4d15c6d81b97184a8e264
[ "Apache-2.0" ]
4
2018-04-17T16:54:09.000Z
2021-11-10T19:43:11.000Z
service/src/main/java/org/apache/fineract/cn/group/internal/command/UpdateLeadersCommand.java
cabrelkemfang/fineract-cn-group
3fa848834ab8e519b3b4d15c6d81b97184a8e264
[ "Apache-2.0" ]
3
2018-08-14T14:48:23.000Z
2018-09-07T09:39:02.000Z
service/src/main/java/org/apache/fineract/cn/group/internal/command/UpdateLeadersCommand.java
cabrelkemfang/fineract-cn-group
3fa848834ab8e519b3b4d15c6d81b97184a8e264
[ "Apache-2.0" ]
154
2018-01-24T12:52:50.000Z
2022-01-27T04:27:30.000Z
32.404762
95
0.753123
6,719
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.cn.group.internal.command; import java.util.Set; public class UpdateLeadersCommand { private final String identifier; private final Set<String> customerIdentifiers; public UpdateLeadersCommand(final String identifier, final Set<String> customerIdentifiers) { super(); this.identifier = identifier; this.customerIdentifiers = customerIdentifiers; } public String identifier() { return this.identifier; } public Set<String> customerIdentifiers() { return this.customerIdentifiers; } }
3e0fcd24103498757605ab79eaaab82ee17463ca
8,706
java
Java
droid-core-interfaces/src/main/java/uk/gov/nationalarchives/droid/core/interfaces/config/DroidGlobalProperty.java
kparmar1/droid
efa2a2bb0101cd8a19a258469d8d490550b7ada1
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
176
2015-01-12T10:58:00.000Z
2022-03-17T06:26:51.000Z
droid-core-interfaces/src/main/java/uk/gov/nationalarchives/droid/core/interfaces/config/DroidGlobalProperty.java
kparmar1/droid
efa2a2bb0101cd8a19a258469d8d490550b7ada1
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
424
2015-01-13T09:14:21.000Z
2022-03-30T15:11:42.000Z
droid-core-interfaces/src/main/java/uk/gov/nationalarchives/droid/core/interfaces/config/DroidGlobalProperty.java
kparmar1/droid
efa2a2bb0101cd8a19a258469d8d490550b7ada1
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
64
2015-01-20T08:47:24.000Z
2022-02-28T10:28:59.000Z
36.329167
108
0.671407
6,720
/* * Copyright (c) 2016, The National Archives <lyhxr@example.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the The National Archives nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package uk.gov.nationalarchives.droid.core.interfaces.config; import java.util.HashMap; import java.util.Map; import org.apache.commons.configuration.Configuration; /** * All DROID global properties. * @author rflitcroft * */ public enum DroidGlobalProperty { /** Default throttle. */ DEFAULT_THROTTLE("profile.defaultThrottle", PropertyType.INTEGER, true), /** THe default version for signature files. */ DEFAULT_BINARY_SIG_FILE_VERSION("profile.defaultBinarySigFileVersion", PropertyType.TEXT, true), /** THe default version for signature files. */ DEFAULT_CONTAINER_SIG_FILE_VERSION("profile.defaultContainerSigFileVersion", PropertyType.TEXT, true), /** THe default version for signature files. */ DEFAULT_TEXT_SIG_FILE_VERSION("profile.defaultTextSigFileVersion", PropertyType.TEXT, true), /** PRONOM Update URL. */ BINARY_UPDATE_URL("pronom.update.url", PropertyType.TEXT, true), /** PRONOM Update URL. */ CONTAINER_UPDATE_URL("container.update.url", PropertyType.TEXT, true), /** PRONOM Update URL. */ TEXT_UPDATE_URL("text.update.url", PropertyType.TEXT, true), /** Update auto check. */ UPDATE_AUTO_CHECK("update.autoCheck", PropertyType.BOOLEAN, true), /** Update frequency of days to check for updates. */ UPDATE_FREQUENCY_DAYS("update.frequency.days", PropertyType.INTEGER, true), /** Check for updates on startup. */ UPDATE_ON_STARTUP("update.frequency.startup", PropertyType.BOOLEAN, true), /** Update proxy server used. */ UPDATE_USE_PROXY("update.proxy", PropertyType.BOOLEAN, true), /** Update proxy host. */ UPDATE_PROXY_HOST("update.proxy.host", PropertyType.TEXT, true), /** Update proxy port. */ UPDATE_PROXY_PORT("update.proxy.port", PropertyType.INTEGER, true), /** Autoset the default signature to latest downloaded. */ UPDATE_AUTOSET_DEFAULT("update.autoSetDefault", PropertyType.BOOLEAN, true), /** Autoset the default signature to latest downloaded. */ UPDATE_DOWNLOAD_PROMPT("update.downloadPrompt", PropertyType.BOOLEAN, true), /** Autoset the default signature to latest downloaded. */ LAST_UPDATE_CHECK("update.lastCheck", PropertyType.LONG, false), /** Development mode. */ DEV_MODE("development_mode", PropertyType.BOOLEAN, false), /** Whether to process tar files in archives. */ PROCESS_TAR("profile.processTar", PropertyType.BOOLEAN, true), /** Whether to process zip files in archives. */ PROCESS_ZIP("profile.processZip", PropertyType.BOOLEAN, true), /** Whether to process gzip files in archives. */ PROCESS_GZIP("profile.processGzip", PropertyType.BOOLEAN, true), /** Whether to process rar files in archives. */ PROCESS_RAR("profile.processRar", PropertyType.BOOLEAN, true), /** Whether to process 7zip files in archives. */ PROCESS_7ZIP("profile.process7zip", PropertyType.BOOLEAN, true), /** Whether to process iso files in archives. */ PROCESS_ISO("profile.processIso", PropertyType.BOOLEAN, true), /** Whether to process bzip2 files in archives. */ PROCESS_BZIP2("profile.processBzip2", PropertyType.BOOLEAN, true), /** Whether to process arc files in archives. */ PROCESS_ARC("profile.processArc", PropertyType.BOOLEAN, true), /** Whether to process warc files in archives. */ PROCESS_WARC("profile.processWarc", PropertyType.BOOLEAN, true), /** Whether to process files in archives. */ PUID_URL_PATTERN("puid.urlPattern", PropertyType.TEXT, true), /** Generate hashes for each file analysed?. */ GENERATE_HASH("profile.generateHash", PropertyType.BOOLEAN, true), /** Default hash algorithm to use (currently only md5, sha1, sha256 available). */ HASH_ALGORITHM("profile.hashAlgorithm", PropertyType.TEXT, true), /** CSV Export one row per format. */ CSV_EXPORT_ROW_PER_FORMAT("export.rowPerFormat", PropertyType.BOOLEAN, true), /** The max number of bytes to scan from the beginning or * end of a file, or negative, meaning unlimited scanning. */ MAX_BYTES_TO_SCAN("profile.maxBytesToScan", PropertyType.LONG, true), /** Whether to match all extensions, or just ones without another signature attached. */ EXTENSION_ALL("profile.matchAllExtensions", PropertyType.BOOLEAN, true), /** Whether the database plays safe (=true), or gains performance * but loses resilience in the face of failures (=false). */ DATABASE_DURABILITY("database.durability", PropertyType.BOOLEAN, true); private static Map<String, DroidGlobalProperty> allValues = new HashMap<String, DroidGlobalProperty>(); static { for (DroidGlobalProperty prop : DroidGlobalProperty.values()) { allValues.put(prop.getName(), prop); } } private String name; private PropertyType type; private boolean userConfigurable; private DroidGlobalProperty(String name, PropertyType type, boolean userConfigurable) { this.name = name; this.type = type; this.userConfigurable = userConfigurable; } /** * @return the name */ public String getName() { return name; } /** * @return the numeric */ public PropertyType getType() { return type; } /** * @return the userConfigurable */ boolean isUserConfigurable() { return userConfigurable; } /** * @author rflitcroft * */ public static enum PropertyType { /** Text. */ TEXT { @Override public Object getTypeSafeValue(Configuration config, String key) { return config.getString(key); } }, /** Numeric. */ INTEGER { @Override public Object getTypeSafeValue(Configuration config, String key) { return config.getInt(key); } }, /** Boolean. */ BOOLEAN { @Override public Object getTypeSafeValue(Configuration config, String key) { return config.getBoolean(key); } }, /** Long Integer. */ LONG { @Override public Object getTypeSafeValue(Configuration config, String key) { return config.getBigInteger(key); } }; /** * Converts a String property to a type-safe value. * @param config the configuration * @param key the key * @return a type-safe object */ public abstract Object getTypeSafeValue(Configuration config, String key); } /** * @param key the name * @return a DroidGlobalProperty */ public static DroidGlobalProperty forName(String key) { DroidGlobalProperty property = allValues.get(key); return property != null && property.isUserConfigurable() ? property : null; } }
3e0fcd44b67b86bc7d2ad8d15ee8e201a7fb30a1
390
java
Java
src/info/phosco/forms/viewer/tabbed/browser/BrowserTree.java
witchi/fmx.6.decompiler
cc9baa1458f3c24086d314349677c86400fa42f6
[ "MIT" ]
5
2020-02-05T16:40:02.000Z
2021-08-09T02:15:02.000Z
src/info/phosco/forms/viewer/tabbed/browser/BrowserTree.java
witchi/fmx.6.decompiler
cc9baa1458f3c24086d314349677c86400fa42f6
[ "MIT" ]
1
2021-08-15T16:14:03.000Z
2021-12-28T11:48:07.000Z
src/info/phosco/forms/viewer/tabbed/browser/BrowserTree.java
witchi/fmx.6.decompiler
cc9baa1458f3c24086d314349677c86400fa42f6
[ "MIT" ]
3
2019-09-27T18:54:43.000Z
2021-02-12T18:09:50.000Z
20.526316
58
0.807692
6,721
package info.phosco.forms.viewer.tabbed.browser; import javafx.event.EventHandler; import javafx.scene.control.TreeView; import javafx.scene.input.MouseEvent; public interface BrowserTree { TreeView<BrowserTreeNode> getUI(); BrowserTreeItem getSelectedItem(); void setSelectedItem(BrowserTreeItem item); void setOnMouseClicked(EventHandler<MouseEvent> handler); void clear(); }
3e0fce2df3f1f5c0da6a136e2d58a6c6c2575f3c
1,954
java
Java
java-17-absolute-beginners/chapter07/src/main/java/com/apress/bgn/seven/multiex/SuperException.java
wwexperiments/java-prep
20c71a55390b6ab498c370515129d54b51939f92
[ "MIT" ]
null
null
null
java-17-absolute-beginners/chapter07/src/main/java/com/apress/bgn/seven/multiex/SuperException.java
wwexperiments/java-prep
20c71a55390b6ab498c370515129d54b51939f92
[ "MIT" ]
null
null
null
java-17-absolute-beginners/chapter07/src/main/java/com/apress/bgn/seven/multiex/SuperException.java
wwexperiments/java-prep
20c71a55390b6ab498c370515129d54b51939f92
[ "MIT" ]
null
null
null
36.867925
98
0.742579
6,722
/* Freeware License, some rights reserved Copyright (c) 2021 Iuliana Cosmina Permission is hereby granted, free of charge, to anyone obtaining a copy of this software and associated documentation files (the "Software"), to work with the Software within the limits of freeware distribution and fair use. This includes the rights to use, copy, and modify the Software for personal use. Users are also allowed and encouraged to submit corrections and modifications to the Software for the benefit of other users. It is not allowed to reuse, modify, or redistribute the Software for commercial use in any way, or for a user's educational materials such as books or blog articles without prior permission from the copyright holder. The above copyright notice and this permission notice need to 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 OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.apress.bgn.seven.multiex; /** * Created by iuliana.cosmina on 15/06/2021 */ class SuperException extends Exception{ } class SubException extends SuperException{ } class MultiExceptionsDemo { public static void main(String... args) { try { if(true) { throw new SuperException(); } } catch (SubException se) { // replace this with SuperException se.printStackTrace(); } catch (SuperException sse) { // replace this with SubException to cause a compiler error sse.printStackTrace(); } } }
3e0fd0a8f191712cd2f87812922eeb2ae8cdc172
1,403
java
Java
src/main/java/com/extraty/question14/Solution1.java
VWWL/leet-code-solutions
77044843d0f465deb162a15476af4783ae2648ce
[ "Apache-2.0" ]
1
2021-12-07T10:08:06.000Z
2021-12-07T10:08:06.000Z
src/main/java/com/extraty/question14/Solution1.java
VWWL/leet-code-solutions
77044843d0f465deb162a15476af4783ae2648ce
[ "Apache-2.0" ]
null
null
null
src/main/java/com/extraty/question14/Solution1.java
VWWL/leet-code-solutions
77044843d0f465deb162a15476af4783ae2648ce
[ "Apache-2.0" ]
null
null
null
30.5
81
0.622238
6,723
/* * Copyright 2020-2030 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 * * https://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.extraty.question14; /** * @author Created by Neil Wang * @version 1.0.0 * @date 2021/9/1 3:29 下午 */ public class Solution1 { public String longestCommonPrefix(String[] strs) { int length = strs[0].length(); int count = strs.length; for (int i = 0; i < length; i++) { char value = strs[0].charAt(i); for (int j = 1; j < count; j++) { if (outOfSize(strs[j], i) || diffValue(strs[j].charAt(i), value)) return strs[0].substring(0, i); } } return strs[0]; } private boolean diffValue(char target, char value) { return target != value; } private boolean outOfSize(String str, int i) { return i == str.length(); } }
3e0fd14cf5e3b9f959cab0889e1e7e30eb665bdf
706
java
Java
src/main/java/xyz/mrmelon54/BetterResourcePackSorting/mixin/MixinPackResourceMetadata.java
MrMelon54/better-resource-pack-sorting-fabric
9e434593ef6da1c5548ff5136bb9bea0699207b1
[ "MIT" ]
1
2022-02-25T18:49:03.000Z
2022-02-25T18:49:03.000Z
src/main/java/xyz/mrmelon54/BetterResourcePackSorting/mixin/MixinPackResourceMetadata.java
MrMelon54/better-resource-pack-sorting-fabric
9e434593ef6da1c5548ff5136bb9bea0699207b1
[ "MIT" ]
null
null
null
src/main/java/xyz/mrmelon54/BetterResourcePackSorting/mixin/MixinPackResourceMetadata.java
MrMelon54/better-resource-pack-sorting-fabric
9e434593ef6da1c5548ff5136bb9bea0699207b1
[ "MIT" ]
null
null
null
30.695652
110
0.803116
6,724
package xyz.mrmelon54.BetterResourcePackSorting.mixin; import net.minecraft.resource.metadata.PackResourceMetadata; import net.minecraft.text.Text; import org.spongepowered.asm.mixin.Mixin; import xyz.mrmelon54.BetterResourcePackSorting.duck.PackResourceCustomNameGetter; import xyz.mrmelon54.BetterResourcePackSorting.duck.PackResourceCustomNameSetter; @Mixin(PackResourceMetadata.class) public class MixinPackResourceMetadata implements PackResourceCustomNameGetter, PackResourceCustomNameSetter { private Text customName; @Override public Text getCustomName() { return customName; } @Override public void setCustomName(Text name) { customName = name; } }
3e0fd203485a755dc85d2384aceff03c62d3efeb
1,579
java
Java
2.2-Multithreading/src/main/java/ru/job4j/wait/FindFiles.java
fr3anthe/ifedorenko
8cffe7e860ba00f248795f2929c7809e25a4fa87
[ "Apache-2.0" ]
null
null
null
2.2-Multithreading/src/main/java/ru/job4j/wait/FindFiles.java
fr3anthe/ifedorenko
8cffe7e860ba00f248795f2929c7809e25a4fa87
[ "Apache-2.0" ]
17
2020-03-04T21:50:00.000Z
2022-03-31T21:31:19.000Z
2.2-Multithreading/src/main/java/ru/job4j/wait/FindFiles.java
fr3anthe/ifedorenko
8cffe7e860ba00f248795f2929c7809e25a4fa87
[ "Apache-2.0" ]
1
2018-01-21T09:04:17.000Z
2018-01-21T09:04:17.000Z
28.196429
94
0.656111
6,725
package ru.job4j.wait; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class FindFiles extends SimpleFileVisitor<Path> { private final List<String> ext; private final BlockingQueue<Path> files; /** * Constructor. * @param ext files extensions * @param files queue for adding files by extensions */ public FindFiles(List<String> ext, BlockingQueue<Path> files) { this.ext = ext; this.files = files; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException { if (attr.isRegularFile()) { int temp = file.toString().lastIndexOf('.'); if (ext.contains(file.toString().substring(temp + 1))) { try { files.put(file); } catch (InterruptedException e) { e.printStackTrace(); } } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } }
3e0fd4c4468d3a593d36781a657b3ad6c5c40edf
1,788
java
Java
src/main/java/frc/robot/commands/simpledriveshoot/runBalls.java
steinert-programming-2180/FinalRobotics2020
5bfb9afc657bc26d1fda197d26d1bbc528cb1007
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/simpledriveshoot/runBalls.java
steinert-programming-2180/FinalRobotics2020
5bfb9afc657bc26d1fda197d26d1bbc528cb1007
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/simpledriveshoot/runBalls.java
steinert-programming-2180/FinalRobotics2020
5bfb9afc657bc26d1fda197d26d1bbc528cb1007
[ "BSD-3-Clause" ]
null
null
null
30.827586
86
0.624161
6,726
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands.simpledriveshoot; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.Constants.ConveyerConstants; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter; public class runBalls extends CommandBase { /** * Creates a new runBalls. */ Intake intake; long setTime; CANSparkMax conveyer; Shooter shooter; public runBalls(Shooter ks) { // Use addRequirements() here to declare subsystem dependencies. addRequirements(ks); conveyer = new CANSparkMax(ConveyerConstants.motorPorts[0], MotorType.kBrushless); shooter = ks; } // Called when the command is initially scheduled. @Override public void initialize() { setTime = System.currentTimeMillis(); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { conveyer.set(0.7); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { conveyer.set(0.0); shooter.stopShooting(); } // Returns true when the command should end. @Override public boolean isFinished() { return System.currentTimeMillis() - setTime > 4000; } }
3e0fd5130bda730c9f25ce8e05a91d0389c290ea
1,234
java
Java
src/jt/rubicon/_java/org/pybee/rubicon/Python.java
karpierz/jtypes.rubicon
8f8196e47de93183eb9728fec0d08725fc368ee0
[ "BSD-3-Clause" ]
2
2018-11-29T06:19:05.000Z
2018-12-09T09:47:55.000Z
src/jt/rubicon/_java/org/pybee/rubicon/Python.java
karpierz/jtypes.rubicon
8f8196e47de93183eb9728fec0d08725fc368ee0
[ "BSD-3-Clause" ]
null
null
null
src/jt/rubicon/_java/org/pybee/rubicon/Python.java
karpierz/jtypes.rubicon
8f8196e47de93183eb9728fec0d08725fc368ee0
[ "BSD-3-Clause" ]
null
null
null
32.473684
92
0.641005
6,727
// Copyright (c) 2016-2019, Adam Karpierz // Licensed under the BSD license // http://opensource.org/licenses/BSD-3-Clause package org.pybee.rubicon; public class Python { // Start the Python runtime. // // @param pythonHome The value for the PYTHONHOME environment variable // @param pythonPath The value for the PYTHONPATH environment variable // @param rubiconLib The path to the Rubicon integration library. This library // will be explictly loaded as part of the startup of the // Python integration library. If null, it is assumed that // the system LD_LIBRARY_PATH (or equivalent) will contain // the Rubicon library // @return 0 on success; non-zero on failure. // public static native int start(String pythonHome, String pythonPath, String rubiconLib); // Run the Python script. // // @param script The path to the Python script to run // @return 0 on success; non-zero on failure. // public static native int run(String script); // Stop the Python runtime. // public static native void stop(); static { //!!!System.loadLibrary("rubicon"); } }
3e0fd524c6f68ff2948c93db64a85722b6ef7968
3,258
java
Java
geode-core/src/main/java/org/apache/geode/pdx/internal/TypeRegistrationStatistics.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
1,475
2016-12-06T06:10:53.000Z
2022-03-30T09:55:23.000Z
geode-core/src/main/java/org/apache/geode/pdx/internal/TypeRegistrationStatistics.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
2,809
2016-12-06T19:24:26.000Z
2022-03-31T22:02:20.000Z
geode-core/src/main/java/org/apache/geode/pdx/internal/TypeRegistrationStatistics.java
Kris-10-0/geode
7ccdc8297b1ded06175f41543884d945d5995c60
[ "Apache-2.0" ]
531
2016-12-06T05:48:47.000Z
2022-03-31T23:06:37.000Z
37.883721
100
0.724064
6,728
/* * 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.geode.pdx.internal; import org.apache.geode.StatisticDescriptor; import org.apache.geode.Statistics; import org.apache.geode.StatisticsFactory; import org.apache.geode.StatisticsType; class TypeRegistrationStatistics { static final String TYPE_DEFINED = "typeDefined"; static final String TYPE_CREATED = "typeCreated"; static final String ENUM_DEFINED = "enumDefined"; static final String ENUM_CREATED = "enumCreated"; static final String SIZE = "size"; private final TypeRegistration typeRegistration; private final int typeDefinedId; private final int typeCreatedId; private final int enumDefinedId; private final int enumCreatedId; private final Statistics statistics; TypeRegistrationStatistics(final StatisticsFactory statisticsFactory, final TypeRegistration typeRegistration) { this.typeRegistration = typeRegistration; final StatisticsType statisticsType = statisticsFactory.createType("PdxTypeRegistration", "PDX type registration statistics.", new StatisticDescriptor[] { statisticsFactory.createLongCounter(TYPE_DEFINED, "Number of PDX types defined.", "ops"), statisticsFactory.createLongCounter(TYPE_CREATED, "Number of PDX types created.", "ops"), statisticsFactory.createLongCounter(ENUM_DEFINED, "Number of PDX enums defined.", "ops"), statisticsFactory.createLongCounter(ENUM_CREATED, "Number of PDX enums created.", "ops"), statisticsFactory.createLongGauge(SIZE, "Size of PDX type and enum registry.", "entries") }); typeDefinedId = statisticsType.nameToId(TYPE_DEFINED); typeCreatedId = statisticsType.nameToId(TYPE_CREATED); enumDefinedId = statisticsType.nameToId(ENUM_DEFINED); enumCreatedId = statisticsType.nameToId(ENUM_CREATED); statistics = statisticsFactory.createAtomicStatistics(statisticsType, typeRegistration.getClass().getSimpleName()); } public void initialize() { statistics.setLongSupplier(SIZE, typeRegistration::getLocalSize); } void typeDefined() { statistics.incLong(typeDefinedId, 1); } void typeCreated() { statistics.incLong(typeCreatedId, 1); } void enumDefined() { statistics.incLong(enumDefinedId, 1); } void enumCreated() { statistics.incLong(enumCreatedId, 1); } }